1 //===-- InstSelectSimple.cpp - A simple instruction selector for PowerPC --===//
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 #define DEBUG_TYPE "isel"
12 #include "PowerPCInstrBuilder.h"
13 #include "PowerPCInstrInfo.h"
14 #include "PPC32TargetMachine.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Pass.h"
20 #include "llvm/CodeGen/IntrinsicLowering.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "Support/Debug.h"
30 #include "Support/Statistic.h"
35 Statistic<> GEPFolds("ppc-codegen", "Number of GEPs folded");
37 /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
38 /// PPC Representation.
41 cByte, cShort, cInt, cFP32, cFP64, cLong
45 /// getClass - Turn a primitive type into a "class" number which is based on the
46 /// size of the type, and whether or not it is floating point.
48 static inline TypeClass getClass(const Type *Ty) {
49 switch (Ty->getTypeID()) {
51 case Type::UByteTyID: return cByte; // Byte operands are class #0
53 case Type::UShortTyID: return cShort; // Short operands are class #1
56 case Type::PointerTyID: return cInt; // Ints and pointers are class #2
58 case Type::FloatTyID: return cFP32; // Single float is #3
59 case Type::DoubleTyID: return cFP64; // Double Point is #4
62 case Type::ULongTyID: return cLong; // Longs are class #5
64 assert(0 && "Invalid type to getClass!");
65 return cByte; // not reached
69 // getClassB - Just like getClass, but treat boolean values as ints.
70 static inline TypeClass getClassB(const Type *Ty) {
71 if (Ty == Type::BoolTy) return cByte;
76 struct ISel : public FunctionPass, InstVisitor<ISel> {
77 PPC32TargetMachine &TM;
78 MachineFunction *F; // The function we are compiling into
79 MachineBasicBlock *BB; // The current MBB we are compiling
80 int VarArgsFrameIndex; // FrameIndex for start of varargs area
82 std::map<Value*, unsigned> RegMap; // Mapping between Values and SSA Regs
84 // External functions used in the Module
85 Function *fmodfFn, *fmodFn, *__cmpdi2Fn, *__moddi3Fn, *__divdi3Fn,
86 *__umoddi3Fn, *__udivdi3Fn, *__fixsfdiFn, *__fixdfdiFn, *__fixunssfdiFn,
87 *__fixunsdfdiFn, *__floatdisfFn, *__floatdidfFn, *mallocFn, *freeFn;
89 // MBBMap - Mapping between LLVM BB -> Machine BB
90 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
92 // AllocaMap - Mapping from fixed sized alloca instructions to the
93 // FrameIndex for the alloca.
94 std::map<AllocaInst*, unsigned> AllocaMap;
96 // A Reg to hold the base address used for global loads and stores, and a
97 // flag to set whether or not we need to emit it for this function.
98 unsigned GlobalBaseReg;
99 bool GlobalBaseInitialized;
101 ISel(TargetMachine &tm) : TM(reinterpret_cast<PPC32TargetMachine&>(tm)),
104 bool doInitialization(Module &M) {
105 // Add external functions that we may call
106 Type *i = Type::IntTy;
107 Type *d = Type::DoubleTy;
108 Type *f = Type::FloatTy;
109 Type *l = Type::LongTy;
110 Type *ul = Type::ULongTy;
111 Type *voidPtr = PointerType::get(Type::SByteTy);
112 // float fmodf(float, float);
113 fmodfFn = M.getOrInsertFunction("fmodf", f, f, f, 0);
114 // double fmod(double, double);
115 fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
116 // int __cmpdi2(long, long);
117 __cmpdi2Fn = M.getOrInsertFunction("__cmpdi2", i, l, l, 0);
118 // long __moddi3(long, long);
119 __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
120 // long __divdi3(long, long);
121 __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
122 // unsigned long __umoddi3(unsigned long, unsigned long);
123 __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
124 // unsigned long __udivdi3(unsigned long, unsigned long);
125 __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
126 // long __fixsfdi(float)
127 __fixsfdiFn = M.getOrInsertFunction("__fixsfdi", l, f, 0);
128 // long __fixdfdi(double)
129 __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
130 // unsigned long __fixunssfdi(float)
131 __fixunssfdiFn = M.getOrInsertFunction("__fixunssfdi", ul, f, 0);
132 // unsigned long __fixunsdfdi(double)
133 __fixunsdfdiFn = M.getOrInsertFunction("__fixunsdfdi", ul, d, 0);
134 // float __floatdisf(long)
135 __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
136 // double __floatdidf(long)
137 __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
138 // void* malloc(size_t)
139 mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
141 freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
145 /// runOnFunction - Top level implementation of instruction selection for
146 /// the entire function.
148 bool runOnFunction(Function &Fn) {
149 // First pass over the function, lower any unknown intrinsic functions
150 // with the IntrinsicLowering class.
151 LowerUnknownIntrinsicFunctionCalls(Fn);
153 F = &MachineFunction::construct(&Fn, TM);
155 // Create all of the machine basic blocks for the function...
156 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
157 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
161 // Make sure we re-emit a set of the global base reg if necessary
162 GlobalBaseInitialized = false;
164 // Copy incoming arguments off of the stack...
165 LoadArgumentsToVirtualRegs(Fn);
167 // Instruction select everything except PHI nodes
170 // Select the PHI nodes
177 // We always build a machine code representation for the function
181 virtual const char *getPassName() const {
182 return "PowerPC Simple Instruction Selection";
185 /// visitBasicBlock - This method is called when we are visiting a new basic
186 /// block. This simply creates a new MachineBasicBlock to emit code into
187 /// and adds it to the current MachineFunction. Subsequent visit* for
188 /// instructions will be invoked for all instructions in the basic block.
190 void visitBasicBlock(BasicBlock &LLVM_BB) {
191 BB = MBBMap[&LLVM_BB];
194 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
195 /// function, lowering any calls to unknown intrinsic functions into the
196 /// equivalent LLVM code.
198 void LowerUnknownIntrinsicFunctionCalls(Function &F);
200 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
201 /// from the stack into virtual registers.
203 void LoadArgumentsToVirtualRegs(Function &F);
205 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
206 /// because we have to generate our sources into the source basic blocks,
207 /// not the current one.
209 void SelectPHINodes();
211 // Visitation methods for various instructions. These methods simply emit
212 // fixed PowerPC code for each instruction.
214 // Control flow operators
215 void visitReturnInst(ReturnInst &RI);
216 void visitBranchInst(BranchInst &BI);
222 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
223 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
226 // This struct is for recording the necessary operations to emit the GEP
227 struct CollapsedGepOp {
231 CollapsedGepOp(bool mul, Value *i, ConstantSInt *s) :
232 isMul(mul), index(i), size(s) {}
235 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
236 const std::vector<ValueRecord> &Args, bool isVarArg);
237 void visitCallInst(CallInst &I);
238 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
240 // Arithmetic operators
241 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
242 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
243 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
244 void visitMul(BinaryOperator &B);
246 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
247 void visitRem(BinaryOperator &B) { visitDivRem(B); }
248 void visitDivRem(BinaryOperator &B);
251 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
252 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
253 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
255 // Comparison operators...
256 void visitSetCondInst(SetCondInst &I);
257 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
258 MachineBasicBlock *MBB,
259 MachineBasicBlock::iterator MBBI);
260 void visitSelectInst(SelectInst &SI);
263 // Memory Instructions
264 void visitLoadInst(LoadInst &I);
265 void visitStoreInst(StoreInst &I);
266 void visitGetElementPtrInst(GetElementPtrInst &I);
267 void visitAllocaInst(AllocaInst &I);
268 void visitMallocInst(MallocInst &I);
269 void visitFreeInst(FreeInst &I);
272 void visitShiftInst(ShiftInst &I);
273 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
274 void visitCastInst(CastInst &I);
275 void visitVANextInst(VANextInst &I);
276 void visitVAArgInst(VAArgInst &I);
278 void visitInstruction(Instruction &I) {
279 std::cerr << "Cannot instruction select: " << I;
283 /// promote32 - Make a value 32-bits wide, and put it somewhere.
285 void promote32(unsigned targetReg, const ValueRecord &VR);
287 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
288 /// constant expression GEP support.
290 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
291 Value *Src, User::op_iterator IdxBegin,
292 User::op_iterator IdxEnd, unsigned TargetReg,
293 bool CollapseRemainder, ConstantSInt **Remainder,
294 unsigned *PendingAddReg);
296 /// emitCastOperation - Common code shared between visitCastInst and
297 /// constant expression cast support.
299 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
300 Value *Src, const Type *DestTy, unsigned TargetReg);
302 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
303 /// and constant expression support.
305 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
306 MachineBasicBlock::iterator IP,
307 Value *Op0, Value *Op1,
308 unsigned OperatorClass, unsigned TargetReg);
310 /// emitBinaryFPOperation - This method handles emission of floating point
311 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
312 void emitBinaryFPOperation(MachineBasicBlock *BB,
313 MachineBasicBlock::iterator IP,
314 Value *Op0, Value *Op1,
315 unsigned OperatorClass, unsigned TargetReg);
317 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
318 Value *Op0, Value *Op1, unsigned TargetReg);
320 void doMultiply(MachineBasicBlock *MBB,
321 MachineBasicBlock::iterator IP,
322 unsigned DestReg, Value *Op0, Value *Op1);
324 /// doMultiplyConst - This method will multiply the value in Op0Reg by the
325 /// value of the ContantInt *CI
326 void doMultiplyConst(MachineBasicBlock *MBB,
327 MachineBasicBlock::iterator IP,
328 unsigned DestReg, Value *Op0, ConstantInt *CI);
330 void emitDivRemOperation(MachineBasicBlock *BB,
331 MachineBasicBlock::iterator IP,
332 Value *Op0, Value *Op1, bool isDiv,
335 /// emitSetCCOperation - Common code shared between visitSetCondInst and
336 /// constant expression support.
338 void emitSetCCOperation(MachineBasicBlock *BB,
339 MachineBasicBlock::iterator IP,
340 Value *Op0, Value *Op1, unsigned Opcode,
343 /// emitShiftOperation - Common code shared between visitShiftInst and
344 /// constant expression support.
346 void emitShiftOperation(MachineBasicBlock *MBB,
347 MachineBasicBlock::iterator IP,
348 Value *Op, Value *ShiftAmount, bool isLeftShift,
349 const Type *ResultTy, unsigned DestReg);
351 /// emitSelectOperation - Common code shared between visitSelectInst and the
352 /// constant expression support.
354 void emitSelectOperation(MachineBasicBlock *MBB,
355 MachineBasicBlock::iterator IP,
356 Value *Cond, Value *TrueVal, Value *FalseVal,
359 /// copyGlobalBaseToRegister - Output the instructions required to put the
360 /// base address to use for accessing globals into a register.
362 void ISel::copyGlobalBaseToRegister(MachineBasicBlock *MBB,
363 MachineBasicBlock::iterator IP,
366 /// copyConstantToRegister - Output the instructions required to put the
367 /// specified constant into the specified register.
369 void copyConstantToRegister(MachineBasicBlock *MBB,
370 MachineBasicBlock::iterator MBBI,
371 Constant *C, unsigned Reg);
373 void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
374 unsigned LHS, unsigned RHS);
376 /// makeAnotherReg - This method returns the next register number we haven't
379 /// Long values are handled somewhat specially. They are always allocated
380 /// as pairs of 32 bit integer values. The register number returned is the
381 /// high 32 bits of the long value, and the regNum+1 is the low 32 bits.
383 unsigned makeAnotherReg(const Type *Ty) {
384 assert(dynamic_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo()) &&
385 "Current target doesn't have PPC reg info??");
386 const PowerPCRegisterInfo *PPCRI =
387 static_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo());
388 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
389 const TargetRegisterClass *RC = PPCRI->getRegClassForType(Type::IntTy);
390 // Create the upper part
391 F->getSSARegMap()->createVirtualRegister(RC);
392 // Create the lower part.
393 return F->getSSARegMap()->createVirtualRegister(RC)-1;
396 // Add the mapping of regnumber => reg class to MachineFunction
397 const TargetRegisterClass *RC = PPCRI->getRegClassForType(Ty);
398 return F->getSSARegMap()->createVirtualRegister(RC);
401 /// getReg - This method turns an LLVM value into a register number.
403 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
404 unsigned getReg(Value *V) {
405 // Just append to the end of the current bb.
406 MachineBasicBlock::iterator It = BB->end();
407 return getReg(V, BB, It);
409 unsigned getReg(Value *V, MachineBasicBlock *MBB,
410 MachineBasicBlock::iterator IPt);
412 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
413 /// is okay to use as an immediate argument to a certain binary operation
414 bool canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Opcode);
416 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
417 /// that is to be statically allocated with the initial stack frame
419 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
423 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
424 /// instruction in the entry block, return it. Otherwise, return a null
426 static AllocaInst *dyn_castFixedAlloca(Value *V) {
427 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
428 BasicBlock *BB = AI->getParent();
429 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
435 /// getReg - This method turns an LLVM value into a register number.
437 unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
438 MachineBasicBlock::iterator IPt) {
439 if (Constant *C = dyn_cast<Constant>(V)) {
440 unsigned Reg = makeAnotherReg(V->getType());
441 copyConstantToRegister(MBB, IPt, C, Reg);
443 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
444 unsigned Reg = makeAnotherReg(V->getType());
445 unsigned FI = getFixedSizedAllocaFI(AI);
446 addFrameReference(BuildMI(*MBB, IPt, PPC::ADDI, 2, Reg), FI, 0, false);
450 unsigned &Reg = RegMap[V];
452 Reg = makeAnotherReg(V->getType());
459 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
460 /// is okay to use as an immediate argument to a certain binary operator.
462 /// Operator is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for Xor.
463 bool ISel::canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Operator) {
467 // ADDI, Compare, and non-indexed Load take SIMM
468 bool cond1 = (Operator == 0)
469 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
470 && (Op1Cs->getValue() <= 32767)
471 && (Op1Cs->getValue() >= -32768);
473 // SUBI takes -SIMM since it is a mnemonic for ADDI
474 bool cond2 = (Operator == 1)
475 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
476 && (Op1Cs->getValue() <= 32768)
477 && (Op1Cs->getValue() >= -32767);
479 // ANDIo, ORI, and XORI take unsigned values
480 bool cond3 = (Operator >= 2)
481 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
482 && (Op1Cs->getValue() >= 0)
483 && (Op1Cs->getValue() <= 32767);
485 // ADDI and SUBI take SIMMs, so we have to make sure the UInt would fit
486 bool cond4 = (Operator < 2)
487 && (Op1Cu = dyn_cast<ConstantUInt>(CI))
488 && (Op1Cu->getValue() <= 32767);
490 // ANDIo, ORI, and XORI take UIMMs, so they can be larger
491 bool cond5 = (Operator >= 2)
492 && (Op1Cu = dyn_cast<ConstantUInt>(CI))
493 && (Op1Cu->getValue() <= 65535);
495 if (cond1 || cond2 || cond3 || cond4 || cond5)
501 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
502 /// that is to be statically allocated with the initial stack frame
504 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
505 // Already computed this?
506 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
507 if (I != AllocaMap.end() && I->first == AI) return I->second;
509 const Type *Ty = AI->getAllocatedType();
510 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
511 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
512 TySize *= CUI->getValue(); // Get total allocated size...
513 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
515 // Create a new stack object using the frame manager...
516 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
517 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
522 /// copyGlobalBaseToRegister - Output the instructions required to put the
523 /// base address to use for accessing globals into a register.
525 void ISel::copyGlobalBaseToRegister(MachineBasicBlock *MBB,
526 MachineBasicBlock::iterator IP,
528 if (!GlobalBaseInitialized) {
529 // Insert the set of GlobalBaseReg into the first MBB of the function
530 MachineBasicBlock &FirstMBB = F->front();
531 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
532 GlobalBaseReg = makeAnotherReg(Type::IntTy);
533 BuildMI(FirstMBB, MBBI, PPC::IMPLICIT_DEF, 0, PPC::LR);
534 BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, GlobalBaseReg);
535 GlobalBaseInitialized = true;
537 // Emit our copy of GlobalBaseReg to the destination register in the
539 BuildMI(*MBB, IP, PPC::OR, 2, R).addReg(GlobalBaseReg)
540 .addReg(GlobalBaseReg);
543 /// copyConstantToRegister - Output the instructions required to put the
544 /// specified constant into the specified register.
546 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
547 MachineBasicBlock::iterator IP,
548 Constant *C, unsigned R) {
549 if (C->getType()->isIntegral()) {
550 unsigned Class = getClassB(C->getType());
552 if (Class == cLong) {
553 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
554 uint64_t uval = CUI->getValue();
555 unsigned hiUVal = uval >> 32;
556 unsigned loUVal = uval;
557 ConstantUInt *CUHi = ConstantUInt::get(Type::UIntTy, hiUVal);
558 ConstantUInt *CULo = ConstantUInt::get(Type::UIntTy, loUVal);
559 copyConstantToRegister(MBB, IP, CUHi, R);
560 copyConstantToRegister(MBB, IP, CULo, R+1);
562 } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
563 int64_t sval = CSI->getValue();
564 int hiSVal = sval >> 32;
566 ConstantSInt *CSHi = ConstantSInt::get(Type::IntTy, hiSVal);
567 ConstantSInt *CSLo = ConstantSInt::get(Type::IntTy, loSVal);
568 copyConstantToRegister(MBB, IP, CSHi, R);
569 copyConstantToRegister(MBB, IP, CSLo, R+1);
572 std::cerr << "Unhandled long constant type!\n";
577 assert(Class <= cInt && "Type not handled yet!");
580 if (C->getType() == Type::BoolTy) {
581 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(C == ConstantBool::True);
586 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
587 unsigned uval = CUI->getValue();
589 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(uval);
591 unsigned Temp = makeAnotherReg(Type::IntTy);
592 BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(uval >> 16);
593 BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(uval);
596 } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
597 int sval = CSI->getValue();
598 if (sval < 32768 && sval >= -32768) {
599 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(sval);
601 unsigned Temp = makeAnotherReg(Type::IntTy);
602 BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(sval >> 16);
603 BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(sval);
607 std::cerr << "Unhandled integer constant!\n";
609 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
610 // We need to spill the constant to memory...
611 MachineConstantPool *CP = F->getConstantPool();
612 unsigned CPI = CP->getConstantPoolIndex(CFP);
613 const Type *Ty = CFP->getType();
615 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
617 // Load addr of constant to reg; constant is located at base + distance
618 unsigned GlobalBase = makeAnotherReg(Type::IntTy);
619 unsigned Reg1 = makeAnotherReg(Type::IntTy);
620 unsigned Reg2 = makeAnotherReg(Type::IntTy);
621 // Move value at base + distance into return reg
622 copyGlobalBaseToRegister(MBB, IP, GlobalBase);
623 BuildMI(*MBB, IP, PPC::LOADHiAddr, 2, Reg1).addReg(GlobalBase)
624 .addConstantPoolIndex(CPI);
625 BuildMI(*MBB, IP, PPC::LOADLoDirect, 2, Reg2).addReg(Reg1)
626 .addConstantPoolIndex(CPI);
627 BuildMI(*MBB, IP, PPC::LFD, 2, R).addSImm(0).addReg(Reg2);
628 } else if (isa<ConstantPointerNull>(C)) {
629 // Copy zero (null pointer) to the register.
630 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(0);
631 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
632 // GV is located at base + distance
633 unsigned GlobalBase = makeAnotherReg(Type::IntTy);
634 unsigned TmpReg = makeAnotherReg(GV->getType());
635 unsigned Opcode = (GV->hasWeakLinkage() || GV->isExternal()
636 || dyn_cast<Function>(GV)) ?
637 PPC::LOADLoIndirect : PPC::LOADLoDirect;
639 // Move value at base + distance into return reg
640 copyGlobalBaseToRegister(MBB, IP, GlobalBase);
641 BuildMI(*MBB, IP, PPC::LOADHiAddr, 2, TmpReg).addReg(GlobalBase)
642 .addGlobalAddress(GV);
643 BuildMI(*MBB, IP, Opcode, 2, R).addReg(TmpReg).addGlobalAddress(GV);
645 // Add the GV to the list of things whose addresses have been taken.
646 TM.AddressTaken.insert(GV);
648 std::cerr << "Offending constant: " << *C << "\n";
649 assert(0 && "Type not handled yet!");
653 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
654 /// the stack into virtual registers.
655 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
656 unsigned ArgOffset = 24;
657 unsigned GPR_remaining = 8;
658 unsigned FPR_remaining = 13;
659 unsigned GPR_idx = 0, FPR_idx = 0;
660 static const unsigned GPR[] = {
661 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
662 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
664 static const unsigned FPR[] = {
665 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
666 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
669 MachineFrameInfo *MFI = F->getFrameInfo();
671 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
672 bool ArgLive = !I->use_empty();
673 unsigned Reg = ArgLive ? getReg(*I) : 0;
674 int FI; // Frame object index
676 switch (getClassB(I->getType())) {
679 FI = MFI->CreateFixedObject(4, ArgOffset);
680 if (GPR_remaining > 0) {
681 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
682 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
683 .addReg(GPR[GPR_idx]);
685 addFrameReference(BuildMI(BB, PPC::LBZ, 2, Reg), FI);
691 FI = MFI->CreateFixedObject(4, ArgOffset);
692 if (GPR_remaining > 0) {
693 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
694 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
695 .addReg(GPR[GPR_idx]);
697 addFrameReference(BuildMI(BB, PPC::LHZ, 2, Reg), FI);
703 FI = MFI->CreateFixedObject(4, ArgOffset);
704 if (GPR_remaining > 0) {
705 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
706 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
707 .addReg(GPR[GPR_idx]);
709 addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg), FI);
715 FI = MFI->CreateFixedObject(8, ArgOffset);
716 if (GPR_remaining > 1) {
717 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
718 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx+1]);
719 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
720 .addReg(GPR[GPR_idx]);
721 BuildMI(BB, PPC::OR, 2, Reg+1).addReg(GPR[GPR_idx+1])
722 .addReg(GPR[GPR_idx+1]);
724 addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg), FI);
725 addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg+1), FI, 4);
728 // longs require 4 additional bytes and use 2 GPRs
730 if (GPR_remaining > 1) {
737 FI = MFI->CreateFixedObject(4, ArgOffset);
739 if (FPR_remaining > 0) {
740 BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
741 BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
745 addFrameReference(BuildMI(BB, PPC::LFS, 2, Reg), FI);
751 FI = MFI->CreateFixedObject(8, ArgOffset);
753 if (FPR_remaining > 0) {
754 BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
755 BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
759 addFrameReference(BuildMI(BB, PPC::LFD, 2, Reg), FI);
763 // doubles require 4 additional bytes and use 2 GPRs of param space
765 if (GPR_remaining > 0) {
771 assert(0 && "Unhandled argument type!");
773 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
774 if (GPR_remaining > 0) {
775 GPR_remaining--; // uses up 2 GPRs
780 // If the function takes variable number of arguments, add a frame offset for
781 // the start of the first vararg value... this is used to expand
783 if (Fn.getFunctionType()->isVarArg())
784 VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
788 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
789 /// because we have to generate our sources into the source basic blocks, not
792 void ISel::SelectPHINodes() {
793 const TargetInstrInfo &TII = *TM.getInstrInfo();
794 const Function &LF = *F->getFunction(); // The LLVM function...
795 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
796 const BasicBlock *BB = I;
797 MachineBasicBlock &MBB = *MBBMap[I];
799 // Loop over all of the PHI nodes in the LLVM basic block...
800 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
801 for (BasicBlock::const_iterator I = BB->begin();
802 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
804 // Create a new machine instr PHI node, and insert it.
805 unsigned PHIReg = getReg(*PN);
806 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
807 PPC::PHI, PN->getNumOperands(), PHIReg);
809 MachineInstr *LongPhiMI = 0;
810 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
811 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
812 PPC::PHI, PN->getNumOperands(), PHIReg+1);
814 // PHIValues - Map of blocks to incoming virtual registers. We use this
815 // so that we only initialize one incoming value for a particular block,
816 // even if the block has multiple entries in the PHI node.
818 std::map<MachineBasicBlock*, unsigned> PHIValues;
820 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
821 MachineBasicBlock *PredMBB = 0;
822 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
823 PE = MBB.pred_end (); PI != PE; ++PI)
824 if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
828 assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
831 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
832 PHIValues.lower_bound(PredMBB);
834 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
835 // We already inserted an initialization of the register for this
836 // predecessor. Recycle it.
837 ValReg = EntryIt->second;
839 // Get the incoming value into a virtual register.
841 Value *Val = PN->getIncomingValue(i);
843 // If this is a constant or GlobalValue, we may have to insert code
844 // into the basic block to compute it into a virtual register.
845 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
846 isa<GlobalValue>(Val)) {
847 // Simple constants get emitted at the end of the basic block,
848 // before any terminator instructions. We "know" that the code to
849 // move a constant into a register will never clobber any flags.
850 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
852 // Because we don't want to clobber any values which might be in
853 // physical registers with the computation of this constant (which
854 // might be arbitrarily complex if it is a constant expression),
855 // just insert the computation at the top of the basic block.
856 MachineBasicBlock::iterator PI = PredMBB->begin();
858 // Skip over any PHI nodes though!
859 while (PI != PredMBB->end() && PI->getOpcode() == PPC::PHI)
862 ValReg = getReg(Val, PredMBB, PI);
865 // Remember that we inserted a value for this PHI for this predecessor
866 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
869 PhiMI->addRegOperand(ValReg);
870 PhiMI->addMachineBasicBlockOperand(PredMBB);
872 LongPhiMI->addRegOperand(ValReg+1);
873 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
877 // Now that we emitted all of the incoming values for the PHI node, make
878 // sure to reposition the InsertPoint after the PHI that we just added.
879 // This is needed because we might have inserted a constant into this
880 // block, right after the PHI's which is before the old insert point!
881 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
888 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
889 // it into the conditional branch or select instruction which is the only user
890 // of the cc instruction. This is the case if the conditional branch is the
891 // only user of the setcc, and if the setcc is in the same basic block as the
892 // conditional branch.
894 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
895 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
896 if (SCI->hasOneUse()) {
897 Instruction *User = cast<Instruction>(SCI->use_back());
898 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
899 SCI->getParent() == User->getParent())
906 // canFoldGEPIntoLoadOrStore - Return the GEP instruction if we can fold it into
907 // the load or store instruction that is the only user of the GEP.
909 static GetElementPtrInst *canFoldGEPIntoLoadOrStore(Value *V) {
910 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V))
911 if (GEPI->hasOneUse()) {
912 Instruction *User = cast<Instruction>(GEPI->use_back());
913 if (isa<StoreInst>(User) &&
914 GEPI->getParent() == User->getParent() &&
915 User->getOperand(0) != GEPI &&
916 User->getOperand(1) == GEPI) {
920 if (isa<LoadInst>(User) &&
921 GEPI->getParent() == User->getParent() &&
922 User->getOperand(0) == GEPI) {
931 // Return a fixed numbering for setcc instructions which does not depend on the
932 // order of the opcodes.
934 static unsigned getSetCCNumber(unsigned Opcode) {
936 default: assert(0 && "Unknown setcc instruction!");
937 case Instruction::SetEQ: return 0;
938 case Instruction::SetNE: return 1;
939 case Instruction::SetLT: return 2;
940 case Instruction::SetGE: return 3;
941 case Instruction::SetGT: return 4;
942 case Instruction::SetLE: return 5;
946 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
948 default: assert(0 && "Unknown setcc instruction!");
949 case Instruction::SetEQ: return PPC::BEQ;
950 case Instruction::SetNE: return PPC::BNE;
951 case Instruction::SetLT: return PPC::BLT;
952 case Instruction::SetGE: return PPC::BGE;
953 case Instruction::SetGT: return PPC::BGT;
954 case Instruction::SetLE: return PPC::BLE;
958 /// emitUCOM - emits an unordered FP compare.
959 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
960 unsigned LHS, unsigned RHS) {
961 BuildMI(*MBB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(LHS).addReg(RHS);
964 /// EmitComparison - emits a comparison of the two operands, returning the
965 /// extended setcc code to use. The result is in CR0.
967 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
968 MachineBasicBlock *MBB,
969 MachineBasicBlock::iterator IP) {
970 // The arguments are already supposed to be of the same type.
971 const Type *CompTy = Op0->getType();
972 unsigned Class = getClassB(CompTy);
973 unsigned Op0r = getReg(Op0, MBB, IP);
975 // Before we do a comparison, we have to make sure that we're truncating our
976 // registers appropriately.
977 if (Class == cByte) {
978 unsigned TmpReg = makeAnotherReg(CompTy);
979 if (CompTy->isSigned())
980 BuildMI(*MBB, IP, PPC::EXTSB, 1, TmpReg).addReg(Op0r);
982 BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Op0r).addImm(0)
983 .addImm(24).addImm(31);
985 } else if (Class == cShort) {
986 unsigned TmpReg = makeAnotherReg(CompTy);
987 if (CompTy->isSigned())
988 BuildMI(*MBB, IP, PPC::EXTSH, 1, TmpReg).addReg(Op0r);
990 BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Op0r).addImm(0)
991 .addImm(16).addImm(31);
995 // Use crand for lt, gt and crandc for le, ge
996 unsigned CROpcode = (OpNum == 2 || OpNum == 4) ? PPC::CRAND : PPC::CRANDC;
997 // ? cr1[lt] : cr1[gt]
998 unsigned CR1field = (OpNum == 2 || OpNum == 3) ? 4 : 5;
999 // ? cr0[lt] : cr0[gt]
1000 unsigned CR0field = (OpNum == 2 || OpNum == 5) ? 0 : 1;
1001 unsigned Opcode = CompTy->isSigned() ? PPC::CMPW : PPC::CMPLW;
1002 unsigned OpcodeImm = CompTy->isSigned() ? PPC::CMPWI : PPC::CMPLWI;
1004 // Special case handling of: cmp R, i
1005 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1006 if (Class == cByte || Class == cShort || Class == cInt) {
1007 unsigned Op1v = CI->getRawValue() & 0xFFFF;
1008 unsigned OpClass = (CompTy->isSigned()) ? 0 : 2;
1010 // Treat compare like ADDI for the purposes of immediate suitability
1011 if (canUseAsImmediateForOpcode(CI, OpClass)) {
1012 BuildMI(*MBB, IP, OpcodeImm, 2, PPC::CR0).addReg(Op0r).addSImm(Op1v);
1014 unsigned Op1r = getReg(Op1, MBB, IP);
1015 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1019 assert(Class == cLong && "Unknown integer class!");
1020 unsigned LowCst = CI->getRawValue();
1021 unsigned HiCst = CI->getRawValue() >> 32;
1022 if (OpNum < 2) { // seteq, setne
1023 unsigned LoLow = makeAnotherReg(Type::IntTy);
1024 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1025 unsigned HiLow = makeAnotherReg(Type::IntTy);
1026 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1027 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1029 BuildMI(*MBB, IP, PPC::XORI, 2, LoLow).addReg(Op0r+1)
1030 .addImm(LowCst & 0xFFFF);
1031 BuildMI(*MBB, IP, PPC::XORIS, 2, LoTmp).addReg(LoLow)
1032 .addImm(LowCst >> 16);
1033 BuildMI(*MBB, IP, PPC::XORI, 2, HiLow).addReg(Op0r)
1034 .addImm(HiCst & 0xFFFF);
1035 BuildMI(*MBB, IP, PPC::XORIS, 2, HiTmp).addReg(HiLow)
1036 .addImm(HiCst >> 16);
1037 BuildMI(*MBB, IP, PPC::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1040 unsigned ConstReg = makeAnotherReg(CompTy);
1041 copyConstantToRegister(MBB, IP, CI, ConstReg);
1043 // cr0 = r3 ccOpcode r5 or (r3 == r5 AND r4 ccOpcode r6)
1044 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r)
1046 BuildMI(*MBB, IP, Opcode, 2, PPC::CR1).addReg(Op0r+1)
1047 .addReg(ConstReg+1);
1048 BuildMI(*MBB, IP, PPC::CRAND, 3).addImm(2).addImm(2).addImm(CR1field);
1049 BuildMI(*MBB, IP, PPC::CROR, 3).addImm(CR0field).addImm(CR0field)
1056 unsigned Op1r = getReg(Op1, MBB, IP);
1059 default: assert(0 && "Unknown type class!");
1063 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1068 emitUCOM(MBB, IP, Op0r, Op1r);
1072 if (OpNum < 2) { // seteq, setne
1073 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1074 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1075 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1076 BuildMI(*MBB, IP, PPC::XOR, 2, HiTmp).addReg(Op0r).addReg(Op1r);
1077 BuildMI(*MBB, IP, PPC::XOR, 2, LoTmp).addReg(Op0r+1).addReg(Op1r+1);
1078 BuildMI(*MBB, IP, PPC::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1079 break; // Allow the sete or setne to be generated from flags set by OR
1081 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
1082 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1084 // cr0 = r3 ccOpcode r5 or (r3 == r5 AND r4 ccOpcode r6)
1085 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1086 BuildMI(*MBB, IP, Opcode, 2, PPC::CR1).addReg(Op0r+1).addReg(Op1r+1);
1087 BuildMI(*MBB, IP, PPC::CRAND, 3).addImm(2).addImm(2).addImm(CR1field);
1088 BuildMI(*MBB, IP, PPC::CROR, 3).addImm(CR0field).addImm(CR0field)
1096 /// visitSetCondInst - emit code to calculate the condition via
1097 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
1099 void ISel::visitSetCondInst(SetCondInst &I) {
1100 if (canFoldSetCCIntoBranchOrSelect(&I))
1103 unsigned DestReg = getReg(I);
1104 unsigned OpNum = I.getOpcode();
1105 const Type *Ty = I.getOperand (0)->getType();
1107 EmitComparison(OpNum, I.getOperand(0), I.getOperand(1), BB, BB->end());
1109 unsigned Opcode = getPPCOpcodeForSetCCNumber(OpNum);
1110 MachineBasicBlock *thisMBB = BB;
1111 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1112 ilist<MachineBasicBlock>::iterator It = BB;
1117 // cmpTY cr0, r1, r2
1121 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1122 // if we could insert other, non-terminator instructions after the
1123 // bCC. But MBB->getFirstTerminator() can't understand this.
1124 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1125 F->getBasicBlockList().insert(It, copy1MBB);
1126 BuildMI(BB, Opcode, 2).addReg(PPC::CR0).addMBB(copy1MBB);
1127 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1128 F->getBasicBlockList().insert(It, copy0MBB);
1129 BuildMI(BB, PPC::B, 1).addMBB(copy0MBB);
1130 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1131 F->getBasicBlockList().insert(It, sinkMBB);
1132 // Update machine-CFG edges
1133 BB->addSuccessor(copy1MBB);
1134 BB->addSuccessor(copy0MBB);
1137 // %TrueValue = li 1
1140 unsigned TrueValue = makeAnotherReg(I.getType());
1141 BuildMI(BB, PPC::LI, 1, TrueValue).addSImm(1);
1142 BuildMI(BB, PPC::B, 1).addMBB(sinkMBB);
1143 // Update machine-CFG edges
1144 BB->addSuccessor(sinkMBB);
1147 // %FalseValue = li 0
1150 unsigned FalseValue = makeAnotherReg(I.getType());
1151 BuildMI(BB, PPC::LI, 1, FalseValue).addSImm(0);
1152 // Update machine-CFG edges
1153 BB->addSuccessor(sinkMBB);
1156 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1159 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1160 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1163 void ISel::visitSelectInst(SelectInst &SI) {
1164 unsigned DestReg = getReg(SI);
1165 MachineBasicBlock::iterator MII = BB->end();
1166 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1167 SI.getFalseValue(), DestReg);
1170 /// emitSelect - Common code shared between visitSelectInst and the constant
1171 /// expression support.
1172 /// FIXME: this is most likely broken in one or more ways. Namely, PowerPC has
1173 /// no select instruction. FSEL only works for comparisons against zero.
1174 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1175 MachineBasicBlock::iterator IP,
1176 Value *Cond, Value *TrueVal, Value *FalseVal,
1178 unsigned SelectClass = getClassB(TrueVal->getType());
1181 // See if we can fold the setcc into the select instruction, or if we have
1182 // to get the register of the Cond value
1183 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1184 // We successfully folded the setcc into the select instruction.
1185 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1186 OpNum = EmitComparison(OpNum, SCI->getOperand(0),SCI->getOperand(1),MBB,IP);
1187 Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1189 unsigned CondReg = getReg(Cond, MBB, IP);
1190 BuildMI(*MBB, IP, PPC::CMPI, 2, PPC::CR0).addReg(CondReg).addSImm(0);
1191 Opcode = getPPCOpcodeForSetCCNumber(Instruction::SetNE);
1196 // cmpTY cr0, r1, r2
1200 MachineBasicBlock *thisMBB = BB;
1201 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1202 ilist<MachineBasicBlock>::iterator It = BB;
1205 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1206 // if we could insert other, non-terminator instructions after the
1207 // bCC. But MBB->getFirstTerminator() can't understand this.
1208 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1209 F->getBasicBlockList().insert(It, copy1MBB);
1210 BuildMI(BB, Opcode, 2).addReg(PPC::CR0).addMBB(copy1MBB);
1211 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1212 F->getBasicBlockList().insert(It, copy0MBB);
1213 BuildMI(BB, PPC::B, 1).addMBB(copy0MBB);
1214 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1215 F->getBasicBlockList().insert(It, sinkMBB);
1216 // Update machine-CFG edges
1217 BB->addSuccessor(copy1MBB);
1218 BB->addSuccessor(copy0MBB);
1224 unsigned TrueValue = getReg(TrueVal, BB, BB->begin());
1225 BuildMI(BB, PPC::B, 1).addMBB(sinkMBB);
1226 // Update machine-CFG edges
1227 BB->addSuccessor(sinkMBB);
1230 // %FalseValue = ...
1233 unsigned FalseValue = getReg(FalseVal, BB, BB->begin());
1234 // Update machine-CFG edges
1235 BB->addSuccessor(sinkMBB);
1238 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1241 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1242 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1243 // For a register pair representing a long value, define the second reg
1244 if (getClassB(TrueVal->getType()) == cLong)
1245 BuildMI(BB, PPC::LI, 1, DestReg+1).addImm(0);
1251 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1252 /// operand, in the specified target register.
1254 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1255 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1257 Value *Val = VR.Val;
1258 const Type *Ty = VR.Ty;
1260 if (Constant *C = dyn_cast<Constant>(Val)) {
1261 Val = ConstantExpr::getCast(C, Type::IntTy);
1262 if (isa<ConstantExpr>(Val)) // Could not fold
1265 Ty = Type::IntTy; // Folded!
1268 // If this is a simple constant, just emit a load directly to avoid the copy
1269 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1270 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1272 if (TheVal < 32768 && TheVal >= -32768) {
1273 BuildMI(BB, PPC::LI, 1, targetReg).addSImm(TheVal);
1275 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1276 BuildMI(BB, PPC::LIS, 1, TmpReg).addSImm(TheVal >> 16);
1277 BuildMI(BB, PPC::ORI, 2, targetReg).addReg(TmpReg)
1278 .addImm(TheVal & 0xFFFF);
1284 // Make sure we have the register number for this value...
1285 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1286 switch (getClassB(Ty)) {
1288 // Extend value into target register (8->32)
1290 BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1291 .addZImm(24).addZImm(31);
1293 BuildMI(BB, PPC::EXTSB, 1, targetReg).addReg(Reg);
1296 // Extend value into target register (16->32)
1298 BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1299 .addZImm(16).addZImm(31);
1301 BuildMI(BB, PPC::EXTSH, 1, targetReg).addReg(Reg);
1304 // Move value into target register (32->32)
1305 BuildMI(BB, PPC::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1308 assert(0 && "Unpromotable operand class in promote32");
1312 /// visitReturnInst - implemented with BLR
1314 void ISel::visitReturnInst(ReturnInst &I) {
1315 // Only do the processing if this is a non-void return
1316 if (I.getNumOperands() > 0) {
1317 Value *RetVal = I.getOperand(0);
1318 switch (getClassB(RetVal->getType())) {
1319 case cByte: // integral return values: extend or move into r3 and return
1322 promote32(PPC::R3, ValueRecord(RetVal));
1325 case cFP64: { // Floats & Doubles: Return in f1
1326 unsigned RetReg = getReg(RetVal);
1327 BuildMI(BB, PPC::FMR, 1, PPC::F1).addReg(RetReg);
1331 unsigned RetReg = getReg(RetVal);
1332 BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(RetReg).addReg(RetReg);
1333 BuildMI(BB, PPC::OR, 2, PPC::R4).addReg(RetReg+1).addReg(RetReg+1);
1337 visitInstruction(I);
1340 BuildMI(BB, PPC::BLR, 1).addImm(0);
1343 // getBlockAfter - Return the basic block which occurs lexically after the
1345 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1346 Function::iterator I = BB; ++I; // Get iterator to next block
1347 return I != BB->getParent()->end() ? &*I : 0;
1350 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1351 /// that since code layout is frozen at this point, that if we are trying to
1352 /// jump to a block that is the immediate successor of the current block, we can
1353 /// just make a fall-through (but we don't currently).
1355 void ISel::visitBranchInst(BranchInst &BI) {
1356 // Update machine-CFG edges
1357 BB->addSuccessor(MBBMap[BI.getSuccessor(0)]);
1358 if (BI.isConditional())
1359 BB->addSuccessor(MBBMap[BI.getSuccessor(1)]);
1361 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1363 if (!BI.isConditional()) { // Unconditional branch?
1364 if (BI.getSuccessor(0) != NextBB)
1365 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1369 // See if we can fold the setcc into the branch itself...
1370 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1372 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1373 // computed some other way...
1374 unsigned condReg = getReg(BI.getCondition());
1375 BuildMI(BB, PPC::CMPLI, 3, PPC::CR0).addImm(0).addReg(condReg)
1377 if (BI.getSuccessor(1) == NextBB) {
1378 if (BI.getSuccessor(0) != NextBB)
1379 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BNE)
1380 .addMBB(MBBMap[BI.getSuccessor(0)])
1381 .addMBB(MBBMap[BI.getSuccessor(1)]);
1383 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BEQ)
1384 .addMBB(MBBMap[BI.getSuccessor(1)])
1385 .addMBB(MBBMap[BI.getSuccessor(0)]);
1386 if (BI.getSuccessor(0) != NextBB)
1387 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1392 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1393 unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1394 MachineBasicBlock::iterator MII = BB->end();
1395 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1397 if (BI.getSuccessor(0) != NextBB) {
1398 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1399 .addMBB(MBBMap[BI.getSuccessor(0)])
1400 .addMBB(MBBMap[BI.getSuccessor(1)]);
1401 if (BI.getSuccessor(1) != NextBB)
1402 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1404 // Change to the inverse condition...
1405 if (BI.getSuccessor(1) != NextBB) {
1406 Opcode = PowerPCInstrInfo::invertPPCBranchOpcode(Opcode);
1407 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1408 .addMBB(MBBMap[BI.getSuccessor(1)])
1409 .addMBB(MBBMap[BI.getSuccessor(0)]);
1414 /// doCall - This emits an abstract call instruction, setting up the arguments
1415 /// and the return value as appropriate. For the actual function call itself,
1416 /// it inserts the specified CallMI instruction into the stream.
1418 /// FIXME: See Documentation at the following URL for "correct" behavior
1419 /// <http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html>
1420 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1421 const std::vector<ValueRecord> &Args, bool isVarArg) {
1422 // Count how many bytes are to be pushed on the stack, including the linkage
1423 // area, and parameter passing area.
1424 unsigned NumBytes = 24;
1425 unsigned ArgOffset = 24;
1427 if (!Args.empty()) {
1428 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1429 switch (getClassB(Args[i].Ty)) {
1430 case cByte: case cShort: case cInt:
1431 NumBytes += 4; break;
1433 NumBytes += 8; break;
1435 NumBytes += 4; break;
1437 NumBytes += 8; break;
1439 default: assert(0 && "Unknown class!");
1442 // Just to be safe, we'll always reserve the full 24 bytes of linkage area
1443 // plus 32 bytes of argument space in case any called code gets funky on us.
1444 if (NumBytes < 56) NumBytes = 56;
1446 // Adjust the stack pointer for the new arguments...
1447 // These functions are automatically eliminated by the prolog/epilog pass
1448 BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1450 // Arguments go on the stack in reverse order, as specified by the ABI.
1451 // Offset to the paramater area on the stack is 24.
1452 int GPR_remaining = 8, FPR_remaining = 13;
1453 unsigned GPR_idx = 0, FPR_idx = 0;
1454 static const unsigned GPR[] = {
1455 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1456 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1458 static const unsigned FPR[] = {
1459 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6,
1460 PPC::F7, PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12,
1464 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1466 switch (getClassB(Args[i].Ty)) {
1469 // Promote arg to 32 bits wide into a temporary register...
1470 ArgReg = makeAnotherReg(Type::UIntTy);
1471 promote32(ArgReg, Args[i]);
1474 if (GPR_remaining > 0) {
1475 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1477 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1479 if (GPR_remaining <= 0 || isVarArg) {
1480 BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1485 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1488 if (GPR_remaining > 0) {
1489 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1491 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1493 if (GPR_remaining <= 0 || isVarArg) {
1494 BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1499 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1501 // Reg or stack? Note that PPC calling conventions state that long args
1502 // are passed rN = hi, rN+1 = lo, opposite of LLVM.
1503 if (GPR_remaining > 1) {
1504 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1506 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx+1]).addReg(ArgReg+1)
1508 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1509 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1511 if (GPR_remaining <= 1 || isVarArg) {
1512 BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1514 BuildMI(BB, PPC::STW, 3).addReg(ArgReg+1).addSImm(ArgOffset+4)
1518 ArgOffset += 4; // 8 byte entry, not 4.
1519 GPR_remaining -= 1; // uses up 2 GPRs
1523 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1525 if (FPR_remaining > 0) {
1526 BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1527 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1531 // If this is a vararg function, and there are GPRs left, also
1532 // pass the float in an int. Otherwise, put it on the stack.
1534 BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1536 if (GPR_remaining > 0) {
1537 BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx])
1538 .addSImm(ArgOffset).addReg(PPC::R1);
1539 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1543 BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1548 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1550 if (FPR_remaining > 0) {
1551 BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1552 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1555 // For vararg functions, must pass doubles via int regs as well
1557 BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1560 // Doubles can be split across reg + stack for varargs
1561 if (GPR_remaining > 0) {
1562 BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx]).addSImm(ArgOffset)
1564 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1566 if (GPR_remaining > 1) {
1567 BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx+1])
1568 .addSImm(ArgOffset+4).addReg(PPC::R1);
1569 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1573 BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1576 // Doubles use 8 bytes, and 2 GPRs worth of param space
1582 default: assert(0 && "Unknown class!");
1589 BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1592 BuildMI(BB, PPC::IMPLICIT_DEF, 0, PPC::LR);
1593 BB->push_back(CallMI);
1595 // These functions are automatically eliminated by the prolog/epilog pass
1596 BuildMI(BB, PPC::ADJCALLSTACKUP, 1).addImm(NumBytes);
1598 // If there is a return value, scavenge the result from the location the call
1601 if (Ret.Ty != Type::VoidTy) {
1602 unsigned DestClass = getClassB(Ret.Ty);
1603 switch (DestClass) {
1607 // Integral results are in r3
1608 BuildMI(BB, PPC::OR, 2, Ret.Reg).addReg(PPC::R3).addReg(PPC::R3);
1610 case cFP32: // Floating-point return values live in f1
1612 BuildMI(BB, PPC::FMR, 1, Ret.Reg).addReg(PPC::F1);
1614 case cLong: // Long values are in r3:r4
1615 BuildMI(BB, PPC::OR, 2, Ret.Reg).addReg(PPC::R3).addReg(PPC::R3);
1616 BuildMI(BB, PPC::OR, 2, Ret.Reg+1).addReg(PPC::R4).addReg(PPC::R4);
1618 default: assert(0 && "Unknown class!");
1624 /// visitCallInst - Push args on stack and do a procedure call instruction.
1625 void ISel::visitCallInst(CallInst &CI) {
1626 MachineInstr *TheCall;
1627 Function *F = CI.getCalledFunction();
1629 // Is it an intrinsic function call?
1630 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1631 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1634 // Emit a CALL instruction with PC-relative displacement.
1635 TheCall = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(F, true);
1636 // Add it to the set of functions called to be used by the Printer
1637 TM.CalledFunctions.insert(F);
1638 } else { // Emit an indirect call through the CTR
1639 unsigned Reg = getReg(CI.getCalledValue());
1640 BuildMI(BB, PPC::OR, 2, PPC::R12).addReg(Reg).addReg(Reg);
1641 BuildMI(BB, PPC::MTCTR, 1).addReg(PPC::R12);
1642 TheCall = BuildMI(PPC::CALLindirect, 2).addZImm(20).addZImm(0)
1646 std::vector<ValueRecord> Args;
1647 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1648 Args.push_back(ValueRecord(CI.getOperand(i)));
1650 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1651 bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1652 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1656 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1658 static Value *dyncastIsNan(Value *V) {
1659 if (CallInst *CI = dyn_cast<CallInst>(V))
1660 if (Function *F = CI->getCalledFunction())
1661 if (F->getIntrinsicID() == Intrinsic::isunordered)
1662 return CI->getOperand(1);
1666 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1667 /// or's whos operands are all calls to the isnan predicate.
1668 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1669 assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1671 // Check all uses, which will be or's of isnans if this predicate is true.
1672 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1673 Instruction *I = cast<Instruction>(*UI);
1674 if (I->getOpcode() != Instruction::Or) return false;
1675 if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1676 if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1682 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1683 /// function, lowering any calls to unknown intrinsic functions into the
1684 /// equivalent LLVM code.
1686 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1687 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1688 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1689 if (CallInst *CI = dyn_cast<CallInst>(I++))
1690 if (Function *F = CI->getCalledFunction())
1691 switch (F->getIntrinsicID()) {
1692 case Intrinsic::not_intrinsic:
1693 case Intrinsic::vastart:
1694 case Intrinsic::vacopy:
1695 case Intrinsic::vaend:
1696 case Intrinsic::returnaddress:
1697 case Intrinsic::frameaddress:
1698 // FIXME: should lower these ourselves
1699 // case Intrinsic::isunordered:
1700 // case Intrinsic::memcpy: -> doCall(). system memcpy almost
1701 // guaranteed to be faster than anything we generate ourselves
1702 // We directly implement these intrinsics
1704 case Intrinsic::readio: {
1705 // On PPC, memory operations are in-order. Lower this intrinsic
1706 // into a volatile load.
1707 Instruction *Before = CI->getPrev();
1708 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1709 CI->replaceAllUsesWith(LI);
1710 BB->getInstList().erase(CI);
1713 case Intrinsic::writeio: {
1714 // On PPC, memory operations are in-order. Lower this intrinsic
1715 // into a volatile store.
1716 Instruction *Before = CI->getPrev();
1717 StoreInst *SI = new StoreInst(CI->getOperand(1),
1718 CI->getOperand(2), true, CI);
1719 CI->replaceAllUsesWith(SI);
1720 BB->getInstList().erase(CI);
1724 // All other intrinsic calls we must lower.
1725 Instruction *Before = CI->getPrev();
1726 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1727 if (Before) { // Move iterator to instruction after call
1735 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1736 unsigned TmpReg1, TmpReg2, TmpReg3;
1738 case Intrinsic::vastart:
1739 // Get the address of the first vararg value...
1740 TmpReg1 = getReg(CI);
1741 addFrameReference(BuildMI(BB, PPC::ADDI, 2, TmpReg1), VarArgsFrameIndex,
1745 case Intrinsic::vacopy:
1746 TmpReg1 = getReg(CI);
1747 TmpReg2 = getReg(CI.getOperand(1));
1748 BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1750 case Intrinsic::vaend: return;
1752 case Intrinsic::returnaddress:
1753 TmpReg1 = getReg(CI);
1754 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1755 MachineFrameInfo *MFI = F->getFrameInfo();
1756 unsigned NumBytes = MFI->getStackSize();
1758 BuildMI(BB, PPC::LWZ, 2, TmpReg1).addSImm(NumBytes+8)
1761 // Values other than zero are not implemented yet.
1762 BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
1766 case Intrinsic::frameaddress:
1767 TmpReg1 = getReg(CI);
1768 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1769 BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(PPC::R1).addReg(PPC::R1);
1771 // Values other than zero are not implemented yet.
1772 BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
1777 // This may be useful for supporting isunordered
1778 case Intrinsic::isnan:
1779 // If this is only used by 'isunordered' style comparisons, don't emit it.
1780 if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1781 TmpReg1 = getReg(CI.getOperand(1));
1782 emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1783 TmpReg2 = makeAnotherReg(Type::IntTy);
1784 BuildMI(BB, PPC::MFCR, TmpReg2);
1785 TmpReg3 = getReg(CI);
1786 BuildMI(BB, PPC::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1790 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1794 /// visitSimpleBinary - Implement simple binary operators for integral types...
1795 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1798 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1799 unsigned DestReg = getReg(B);
1800 MachineBasicBlock::iterator MI = BB->end();
1801 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1802 unsigned Class = getClassB(B.getType());
1804 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1807 /// emitBinaryFPOperation - This method handles emission of floating point
1808 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1809 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1810 MachineBasicBlock::iterator IP,
1811 Value *Op0, Value *Op1,
1812 unsigned OperatorClass, unsigned DestReg) {
1814 static const unsigned OpcodeTab[][4] = {
1815 { PPC::FADDS, PPC::FSUBS, PPC::FMULS, PPC::FDIVS }, // Float
1816 { PPC::FADD, PPC::FSUB, PPC::FMUL, PPC::FDIV }, // Double
1819 // Special case: op Reg, <const fp>
1820 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1821 // Create a constant pool entry for this constant.
1822 MachineConstantPool *CP = F->getConstantPool();
1823 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1824 const Type *Ty = Op1->getType();
1825 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1827 unsigned Opcode = OpcodeTab[1][OperatorClass];
1828 unsigned Op1Reg = getReg(Op1C, BB, IP);
1829 unsigned Op0Reg = getReg(Op0, BB, IP);
1830 if (Ty == Type::DoubleTy) {
1831 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1833 unsigned TmpReg = makeAnotherReg(Type::DoubleTy);
1834 BuildMI(*BB, IP, Opcode, 2, TmpReg).addReg(Op0Reg).addReg(Op1Reg);
1835 BuildMI(*BB, IP, PPC::FRSP, 1, DestReg).addReg(TmpReg);
1840 // Special case: R1 = op <const fp>, R2
1841 if (ConstantFP *Op0C = dyn_cast<ConstantFP>(Op0))
1842 if (Op0C->isExactlyValue(-0.0) && OperatorClass == 1) {
1844 unsigned op1Reg = getReg(Op1, BB, IP);
1845 BuildMI(*BB, IP, PPC::FNEG, 1, DestReg).addReg(op1Reg);
1848 // Create a constant pool entry for this constant.
1849 MachineConstantPool *CP = F->getConstantPool();
1850 unsigned CPI = CP->getConstantPoolIndex(Op0C);
1851 const Type *Ty = Op0C->getType();
1852 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1854 unsigned Opcode = OpcodeTab[1][OperatorClass];
1855 unsigned Op0Reg = getReg(Op0C, BB, IP);
1856 unsigned Op1Reg = getReg(Op1, BB, IP);
1857 if (Ty == Type::DoubleTy) {
1858 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1860 unsigned TmpReg = makeAnotherReg(Type::DoubleTy);
1861 BuildMI(*BB, IP, Opcode, 2, TmpReg).addReg(Op0Reg).addReg(Op1Reg);
1862 BuildMI(*BB, IP, PPC::FRSP, 1, DestReg).addReg(TmpReg);
1867 unsigned Opcode = OpcodeTab[Op0->getType() != Type::FloatTy][OperatorClass];
1868 //unsigned Opcode = OpcodeTab[OperatorClass];
1869 unsigned Op0r = getReg(Op0, BB, IP);
1870 unsigned Op1r = getReg(Op1, BB, IP);
1871 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1874 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1875 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1878 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1879 /// and constant expression support.
1881 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1882 MachineBasicBlock::iterator IP,
1883 Value *Op0, Value *Op1,
1884 unsigned OperatorClass, unsigned DestReg) {
1885 unsigned Class = getClassB(Op0->getType());
1887 // Arithmetic and Bitwise operators
1888 static const unsigned OpcodeTab[] = {
1889 PPC::ADD, PPC::SUB, PPC::AND, PPC::OR, PPC::XOR
1891 static const unsigned ImmOpcodeTab[] = {
1892 PPC::ADDI, PPC::SUBI, PPC::ANDIo, PPC::ORI, PPC::XORI
1894 static const unsigned RImmOpcodeTab[] = {
1895 PPC::ADDI, PPC::SUBFIC, PPC::ANDIo, PPC::ORI, PPC::XORI
1898 // Otherwise, code generate the full operation with a constant.
1899 static const unsigned BottomTab[] = {
1900 PPC::ADDC, PPC::SUBC, PPC::AND, PPC::OR, PPC::XOR
1902 static const unsigned TopTab[] = {
1903 PPC::ADDE, PPC::SUBFE, PPC::AND, PPC::OR, PPC::XOR
1906 if (Class == cFP32 || Class == cFP64) {
1907 assert(OperatorClass < 2 && "No logical ops for FP!");
1908 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1912 if (Op0->getType() == Type::BoolTy) {
1913 if (OperatorClass == 3)
1914 // If this is an or of two isnan's, emit an FP comparison directly instead
1915 // of or'ing two isnan's together.
1916 if (Value *LHS = dyncastIsNan(Op0))
1917 if (Value *RHS = dyncastIsNan(Op1)) {
1918 unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1919 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1920 emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1921 BuildMI(*MBB, IP, PPC::MFCR, TmpReg);
1922 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1923 .addImm(31).addImm(31);
1928 // Special case: op <const int>, Reg
1929 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1930 // sub 0, X -> subfic
1931 if (OperatorClass == 1 && canUseAsImmediateForOpcode(CI, 0)) {
1932 unsigned Op1r = getReg(Op1, MBB, IP);
1933 int imm = CI->getRawValue() & 0xFFFF;
1935 if (Class == cLong) {
1936 BuildMI(*MBB, IP, PPC::SUBFIC, 2, DestReg+1).addReg(Op1r+1)
1938 BuildMI(*MBB, IP, PPC::SUBFZE, 1, DestReg).addReg(Op1r);
1940 BuildMI(*MBB, IP, PPC::SUBFIC, 2, DestReg).addReg(Op1r).addSImm(imm);
1945 // If it is easy to do, swap the operands and emit an immediate op
1946 if (Class != cLong && OperatorClass != 1 &&
1947 canUseAsImmediateForOpcode(CI, OperatorClass)) {
1948 unsigned Op1r = getReg(Op1, MBB, IP);
1949 int imm = CI->getRawValue() & 0xFFFF;
1951 if (OperatorClass < 2)
1952 BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1955 BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1961 // Special case: op Reg, <const int>
1962 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1963 unsigned Op0r = getReg(Op0, MBB, IP);
1965 // xor X, -1 -> not X
1966 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1967 BuildMI(*MBB, IP, PPC::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1968 if (Class == cLong) // Invert the low part too
1969 BuildMI(*MBB, IP, PPC::NOR, 2, DestReg+1).addReg(Op0r+1)
1974 if (Class != cLong) {
1975 if (canUseAsImmediateForOpcode(Op1C, OperatorClass)) {
1976 int immediate = Op1C->getRawValue() & 0xFFFF;
1978 if (OperatorClass < 2)
1979 BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1980 .addSImm(immediate);
1982 BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1983 .addZImm(immediate);
1985 unsigned Op1r = getReg(Op1, MBB, IP);
1986 BuildMI(*MBB, IP, OpcodeTab[OperatorClass], 2, DestReg).addReg(Op0r)
1992 unsigned Op1r = getReg(Op1, MBB, IP);
1994 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1996 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg).addReg(Op0r)
2001 // We couldn't generate an immediate variant of the op, load both halves into
2002 // registers and emit the appropriate opcode.
2003 unsigned Op0r = getReg(Op0, MBB, IP);
2004 unsigned Op1r = getReg(Op1, MBB, IP);
2006 if (Class != cLong) {
2007 unsigned Opcode = OpcodeTab[OperatorClass];
2008 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2010 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
2012 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg).addReg(Op0r)
2018 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2019 // returns zero when the input is not exactly a power of two.
2020 static unsigned ExactLog2(unsigned Val) {
2021 if (Val == 0 || (Val & (Val-1))) return 0;
2030 /// doMultiply - Emit appropriate instructions to multiply together the
2031 /// Values Op0 and Op1, and put the result in DestReg.
2033 void ISel::doMultiply(MachineBasicBlock *MBB,
2034 MachineBasicBlock::iterator IP,
2035 unsigned DestReg, Value *Op0, Value *Op1) {
2036 unsigned Class0 = getClass(Op0->getType());
2037 unsigned Class1 = getClass(Op1->getType());
2039 unsigned Op0r = getReg(Op0, MBB, IP);
2040 unsigned Op1r = getReg(Op1, MBB, IP);
2043 if (Class0 == cLong && Class1 == cLong) {
2044 unsigned Tmp1 = makeAnotherReg(Type::IntTy);
2045 unsigned Tmp2 = makeAnotherReg(Type::IntTy);
2046 unsigned Tmp3 = makeAnotherReg(Type::IntTy);
2047 unsigned Tmp4 = makeAnotherReg(Type::IntTy);
2048 BuildMI(*MBB, IP, PPC::MULHWU, 2, Tmp1).addReg(Op0r+1).addReg(Op1r+1);
2049 BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2050 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp2).addReg(Op0r+1).addReg(Op1r);
2051 BuildMI(*MBB, IP, PPC::ADD, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
2052 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp4).addReg(Op0r).addReg(Op1r+1);
2053 BuildMI(*MBB, IP, PPC::ADD, 2, DestReg).addReg(Tmp3).addReg(Tmp4);
2057 // 64 x 32 or less, promote 32 to 64 and do a 64 x 64
2058 if (Class0 == cLong && Class1 <= cInt) {
2059 unsigned Tmp0 = makeAnotherReg(Type::IntTy);
2060 unsigned Tmp1 = makeAnotherReg(Type::IntTy);
2061 unsigned Tmp2 = makeAnotherReg(Type::IntTy);
2062 unsigned Tmp3 = makeAnotherReg(Type::IntTy);
2063 unsigned Tmp4 = makeAnotherReg(Type::IntTy);
2064 if (Op1->getType()->isSigned())
2065 BuildMI(*MBB, IP, PPC::SRAWI, 2, Tmp0).addReg(Op1r).addImm(31);
2067 BuildMI(*MBB, IP, PPC::LI, 2, Tmp0).addSImm(0);
2068 BuildMI(*MBB, IP, PPC::MULHWU, 2, Tmp1).addReg(Op0r+1).addReg(Op1r);
2069 BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r);
2070 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp2).addReg(Op0r+1).addReg(Tmp0);
2071 BuildMI(*MBB, IP, PPC::ADD, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
2072 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp4).addReg(Op0r).addReg(Op1r);
2073 BuildMI(*MBB, IP, PPC::ADD, 2, DestReg).addReg(Tmp3).addReg(Tmp4);
2078 if (Class0 <= cInt && Class1 <= cInt) {
2079 BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg).addReg(Op0r).addReg(Op1r);
2083 assert(0 && "doMultiply cannot operate on unknown type!");
2086 /// doMultiplyConst - This method will multiply the value in Op0 by the
2087 /// value of the ContantInt *CI
2088 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
2089 MachineBasicBlock::iterator IP,
2090 unsigned DestReg, Value *Op0, ConstantInt *CI) {
2091 unsigned Class = getClass(Op0->getType());
2094 if (CI->isNullValue()) {
2095 BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
2097 BuildMI(*MBB, IP, PPC::LI, 1, DestReg+1).addSImm(0);
2101 // Mul op0, 1 ==> op0
2102 if (CI->equalsInt(1)) {
2103 unsigned Op0r = getReg(Op0, MBB, IP);
2104 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
2106 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
2110 // If the element size is exactly a power of 2, use a shift to get it.
2111 if (unsigned Shift = ExactLog2(CI->getRawValue())) {
2112 ConstantUInt *ShiftCI = ConstantUInt::get(Type::UByteTy, Shift);
2113 emitShiftOperation(MBB, IP, Op0, ShiftCI, true, Op0->getType(), DestReg);
2117 // If 32 bits or less and immediate is in right range, emit mul by immediate
2118 if (Class == cByte || Class == cShort || Class == cInt) {
2119 if (canUseAsImmediateForOpcode(CI, 0)) {
2120 unsigned Op0r = getReg(Op0, MBB, IP);
2121 unsigned imm = CI->getRawValue() & 0xFFFF;
2122 BuildMI(*MBB, IP, PPC::MULLI, 2, DestReg).addReg(Op0r).addSImm(imm);
2127 doMultiply(MBB, IP, DestReg, Op0, CI);
2130 void ISel::visitMul(BinaryOperator &I) {
2131 unsigned ResultReg = getReg(I);
2133 Value *Op0 = I.getOperand(0);
2134 Value *Op1 = I.getOperand(1);
2136 MachineBasicBlock::iterator IP = BB->end();
2137 emitMultiply(BB, IP, Op0, Op1, ResultReg);
2140 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2141 Value *Op0, Value *Op1, unsigned DestReg) {
2142 TypeClass Class = getClass(Op0->getType());
2149 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2150 doMultiplyConst(MBB, IP, DestReg, Op0, CI);
2152 doMultiply(MBB, IP, DestReg, Op0, Op1);
2157 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2164 /// visitDivRem - Handle division and remainder instructions... these
2165 /// instruction both require the same instructions to be generated, they just
2166 /// select the result from a different register. Note that both of these
2167 /// instructions work differently for signed and unsigned operands.
2169 void ISel::visitDivRem(BinaryOperator &I) {
2170 unsigned ResultReg = getReg(I);
2171 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2173 MachineBasicBlock::iterator IP = BB->end();
2174 emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
2178 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2179 MachineBasicBlock::iterator IP,
2180 Value *Op0, Value *Op1, bool isDiv,
2181 unsigned ResultReg) {
2182 const Type *Ty = Op0->getType();
2183 unsigned Class = getClass(Ty);
2187 // Floating point divide...
2188 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2191 // Floating point remainder via fmodf(float x, float y);
2192 unsigned Op0Reg = getReg(Op0, BB, IP);
2193 unsigned Op1Reg = getReg(Op1, BB, IP);
2194 MachineInstr *TheCall =
2195 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodfFn, true);
2196 std::vector<ValueRecord> Args;
2197 Args.push_back(ValueRecord(Op0Reg, Type::FloatTy));
2198 Args.push_back(ValueRecord(Op1Reg, Type::FloatTy));
2199 doCall(ValueRecord(ResultReg, Type::FloatTy), TheCall, Args, false);
2200 TM.CalledFunctions.insert(fmodfFn);
2205 // Floating point divide...
2206 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2209 // Floating point remainder via fmod(double x, double y);
2210 unsigned Op0Reg = getReg(Op0, BB, IP);
2211 unsigned Op1Reg = getReg(Op1, BB, IP);
2212 MachineInstr *TheCall =
2213 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2214 std::vector<ValueRecord> Args;
2215 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2216 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2217 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2218 TM.CalledFunctions.insert(fmodFn);
2222 static Function* const Funcs[] =
2223 { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2224 unsigned Op0Reg = getReg(Op0, BB, IP);
2225 unsigned Op1Reg = getReg(Op1, BB, IP);
2226 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2227 MachineInstr *TheCall =
2228 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2230 std::vector<ValueRecord> Args;
2231 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2232 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2233 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2234 TM.CalledFunctions.insert(Funcs[NameIdx]);
2237 case cByte: case cShort: case cInt:
2238 break; // Small integrals, handled below...
2239 default: assert(0 && "Unknown class!");
2242 // Special case signed division by power of 2.
2244 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2245 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2246 int V = CI->getValue();
2248 if (V == 1) { // X /s 1 => X
2249 unsigned Op0Reg = getReg(Op0, BB, IP);
2250 BuildMI(*BB, IP, PPC::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2254 if (V == -1) { // X /s -1 => -X
2255 unsigned Op0Reg = getReg(Op0, BB, IP);
2256 BuildMI(*BB, IP, PPC::NEG, 1, ResultReg).addReg(Op0Reg);
2260 unsigned log2V = ExactLog2(V);
2261 if (log2V != 0 && Ty->isSigned()) {
2262 unsigned Op0Reg = getReg(Op0, BB, IP);
2263 unsigned TmpReg = makeAnotherReg(Op0->getType());
2265 BuildMI(*BB, IP, PPC::SRAWI, 2, TmpReg).addReg(Op0Reg).addImm(log2V);
2266 BuildMI(*BB, IP, PPC::ADDZE, 1, ResultReg).addReg(TmpReg);
2271 unsigned Op0Reg = getReg(Op0, BB, IP);
2272 unsigned Op1Reg = getReg(Op1, BB, IP);
2273 unsigned Opcode = Ty->isSigned() ? PPC::DIVW : PPC::DIVWU;
2276 BuildMI(*BB, IP, Opcode, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2277 } else { // Remainder
2278 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2279 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2281 BuildMI(*BB, IP, Opcode, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2282 BuildMI(*BB, IP, PPC::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2283 BuildMI(*BB, IP, PPC::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2288 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2289 /// for constant immediate shift values, and for constant immediate
2290 /// shift values equal to 1. Even the general case is sort of special,
2291 /// because the shift amount has to be in CL, not just any old register.
2293 void ISel::visitShiftInst(ShiftInst &I) {
2294 MachineBasicBlock::iterator IP = BB->end();
2295 emitShiftOperation(BB, IP, I.getOperand(0), I.getOperand(1),
2296 I.getOpcode() == Instruction::Shl, I.getType(),
2300 /// emitShiftOperation - Common code shared between visitShiftInst and
2301 /// constant expression support.
2303 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2304 MachineBasicBlock::iterator IP,
2305 Value *Op, Value *ShiftAmount, bool isLeftShift,
2306 const Type *ResultTy, unsigned DestReg) {
2307 unsigned SrcReg = getReg (Op, MBB, IP);
2308 bool isSigned = ResultTy->isSigned ();
2309 unsigned Class = getClass (ResultTy);
2311 // Longs, as usual, are handled specially...
2312 if (Class == cLong) {
2313 // If we have a constant shift, we can generate much more efficient code
2314 // than otherwise...
2316 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2317 unsigned Amount = CUI->getValue();
2320 // FIXME: RLWIMI is a use-and-def of DestReg+1, but that violates SSA
2321 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2322 .addImm(Amount).addImm(0).addImm(31-Amount);
2323 BuildMI(*MBB, IP, PPC::RLWIMI, 5).addReg(DestReg).addReg(SrcReg+1)
2324 .addImm(Amount).addImm(32-Amount).addImm(31);
2325 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2326 .addImm(Amount).addImm(0).addImm(31-Amount);
2328 // FIXME: RLWIMI is a use-and-def of DestReg, but that violates SSA
2329 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2330 .addImm(32-Amount).addImm(Amount).addImm(31);
2331 BuildMI(*MBB, IP, PPC::RLWIMI, 5).addReg(DestReg+1).addReg(SrcReg)
2332 .addImm(32-Amount).addImm(0).addImm(Amount-1);
2333 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2334 .addImm(32-Amount).addImm(Amount).addImm(31);
2336 } else { // Shifting more than 32 bits
2340 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg+1)
2341 .addImm(Amount).addImm(0).addImm(31-Amount);
2343 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg+1)
2346 BuildMI(*MBB, IP, PPC::LI, 1, DestReg+1).addSImm(0);
2350 BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg+1).addReg(SrcReg)
2353 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg+1).addReg(SrcReg)
2354 .addImm(32-Amount).addImm(Amount).addImm(31);
2356 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
2359 BuildMI(*MBB, IP,PPC::LI, 1, DestReg).addSImm(0);
2363 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2364 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2365 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2366 unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2367 unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2368 unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2369 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2372 BuildMI(*MBB, IP, PPC::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2374 BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg2).addReg(SrcReg)
2375 .addReg(ShiftAmountReg);
2376 BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg3).addReg(SrcReg+1)
2378 BuildMI(*MBB, IP, PPC::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2379 BuildMI(*MBB, IP, PPC::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2381 BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg6).addReg(SrcReg+1)
2383 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(TmpReg4)
2385 BuildMI(*MBB, IP, PPC::SLW, 2, DestReg+1).addReg(SrcReg+1)
2386 .addReg(ShiftAmountReg);
2389 // FIXME: Unimplemented
2390 // Page C-3 of the PowerPC 32bit Programming Environments Manual
2391 std::cerr << "ERROR: Unimplemented: signed right shift of long\n";
2394 BuildMI(*MBB, IP, PPC::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2396 BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg2).addReg(SrcReg+1)
2397 .addReg(ShiftAmountReg);
2398 BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg3).addReg(SrcReg)
2400 BuildMI(*MBB, IP, PPC::OR, 2, TmpReg4).addReg(TmpReg2)
2402 BuildMI(*MBB, IP, PPC::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2404 BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg6).addReg(SrcReg)
2406 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(TmpReg4)
2408 BuildMI(*MBB, IP, PPC::SRW, 2, DestReg).addReg(SrcReg)
2409 .addReg(ShiftAmountReg);
2416 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2417 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2418 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2419 unsigned Amount = CUI->getValue();
2422 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2423 .addImm(Amount).addImm(0).addImm(31-Amount);
2426 BuildMI(*MBB, IP, PPC::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2428 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2429 .addImm(32-Amount).addImm(Amount).addImm(31);
2432 } else { // The shift amount is non-constant.
2433 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2436 BuildMI(*MBB, IP, PPC::SLW, 2, DestReg).addReg(SrcReg)
2437 .addReg(ShiftAmountReg);
2439 BuildMI(*MBB, IP, isSigned ? PPC::SRAW : PPC::SRW, 2, DestReg)
2440 .addReg(SrcReg).addReg(ShiftAmountReg);
2446 /// visitLoadInst - Implement LLVM load instructions. Pretty straightforward
2447 /// mapping of LLVM classes to PPC load instructions, with the exception of
2448 /// signed byte loads, which need a sign extension following them.
2450 void ISel::visitLoadInst(LoadInst &I) {
2451 // Immediate opcodes, for reg+imm addressing
2452 static const unsigned ImmOpcodes[] = {
2453 PPC::LBZ, PPC::LHZ, PPC::LWZ,
2454 PPC::LFS, PPC::LFD, PPC::LWZ
2456 // Indexed opcodes, for reg+reg addressing
2457 static const unsigned IdxOpcodes[] = {
2458 PPC::LBZX, PPC::LHZX, PPC::LWZX,
2459 PPC::LFSX, PPC::LFDX, PPC::LWZX
2462 unsigned Class = getClassB(I.getType());
2463 unsigned ImmOpcode = ImmOpcodes[Class];
2464 unsigned IdxOpcode = IdxOpcodes[Class];
2465 unsigned DestReg = getReg(I);
2466 Value *SourceAddr = I.getOperand(0);
2468 if (Class == cShort && I.getType()->isSigned()) ImmOpcode = PPC::LHA;
2469 if (Class == cShort && I.getType()->isSigned()) IdxOpcode = PPC::LHAX;
2471 if (AllocaInst *AI = dyn_castFixedAlloca(SourceAddr)) {
2472 unsigned FI = getFixedSizedAllocaFI(AI);
2473 if (Class == cLong) {
2474 addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg), FI);
2475 addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg+1), FI, 4);
2476 } else if (Class == cByte && I.getType()->isSigned()) {
2477 unsigned TmpReg = makeAnotherReg(I.getType());
2478 addFrameReference(BuildMI(BB, ImmOpcode, 2, TmpReg), FI);
2479 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2481 addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg), FI);
2486 // If this load is the only use of the GEP instruction that is its address,
2487 // then we can fold the GEP directly into the load instruction.
2488 // emitGEPOperation with a second to last arg of 'true' will place the
2489 // base register for the GEP into baseReg, and the constant offset from that
2490 // into offset. If the offset fits in 16 bits, we can emit a reg+imm store
2491 // otherwise, we copy the offset into another reg, and use reg+reg addressing.
2492 if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
2493 unsigned baseReg = getReg(GEPI);
2494 unsigned pendingAdd;
2495 ConstantSInt *offset;
2497 emitGEPOperation(BB, BB->end(), GEPI->getOperand(0), GEPI->op_begin()+1,
2498 GEPI->op_end(), baseReg, true, &offset, &pendingAdd);
2500 if (pendingAdd == 0 && Class != cLong &&
2501 canUseAsImmediateForOpcode(offset, 0)) {
2502 if (Class == cByte && I.getType()->isSigned()) {
2503 unsigned TmpReg = makeAnotherReg(I.getType());
2504 BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(offset->getValue())
2506 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2508 BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(offset->getValue())
2514 unsigned indexReg = (pendingAdd != 0) ? pendingAdd : getReg(offset);
2516 if (Class == cLong) {
2517 unsigned indexPlus4 = makeAnotherReg(Type::IntTy);
2518 BuildMI(BB, PPC::ADDI, 2, indexPlus4).addReg(indexReg).addSImm(4);
2519 BuildMI(BB, IdxOpcode, 2, DestReg).addReg(indexReg).addReg(baseReg);
2520 BuildMI(BB, IdxOpcode, 2, DestReg+1).addReg(indexPlus4).addReg(baseReg);
2521 } else if (Class == cByte && I.getType()->isSigned()) {
2522 unsigned TmpReg = makeAnotherReg(I.getType());
2523 BuildMI(BB, IdxOpcode, 2, TmpReg).addReg(indexReg).addReg(baseReg);
2524 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2526 BuildMI(BB, IdxOpcode, 2, DestReg).addReg(indexReg).addReg(baseReg);
2531 // The fallback case, where the load was from a source that could not be
2532 // folded into the load instruction.
2533 unsigned SrcAddrReg = getReg(SourceAddr);
2535 if (Class == cLong) {
2536 BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
2537 BuildMI(BB, ImmOpcode, 2, DestReg+1).addSImm(4).addReg(SrcAddrReg);
2538 } else if (Class == cByte && I.getType()->isSigned()) {
2539 unsigned TmpReg = makeAnotherReg(I.getType());
2540 BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(0).addReg(SrcAddrReg);
2541 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2543 BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
2547 /// visitStoreInst - Implement LLVM store instructions
2549 void ISel::visitStoreInst(StoreInst &I) {
2550 // Immediate opcodes, for reg+imm addressing
2551 static const unsigned ImmOpcodes[] = {
2552 PPC::STB, PPC::STH, PPC::STW,
2553 PPC::STFS, PPC::STFD, PPC::STW
2555 // Indexed opcodes, for reg+reg addressing
2556 static const unsigned IdxOpcodes[] = {
2557 PPC::STBX, PPC::STHX, PPC::STWX,
2558 PPC::STFSX, PPC::STFDX, PPC::STWX
2561 Value *SourceAddr = I.getOperand(1);
2562 const Type *ValTy = I.getOperand(0)->getType();
2563 unsigned Class = getClassB(ValTy);
2564 unsigned ImmOpcode = ImmOpcodes[Class];
2565 unsigned IdxOpcode = IdxOpcodes[Class];
2566 unsigned ValReg = getReg(I.getOperand(0));
2568 // If this store is the only use of the GEP instruction that is its address,
2569 // then we can fold the GEP directly into the store instruction.
2570 // emitGEPOperation with a second to last arg of 'true' will place the
2571 // base register for the GEP into baseReg, and the constant offset from that
2572 // into offset. If the offset fits in 16 bits, we can emit a reg+imm store
2573 // otherwise, we copy the offset into another reg, and use reg+reg addressing.
2574 if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
2575 unsigned baseReg = getReg(GEPI);
2576 unsigned pendingAdd;
2577 ConstantSInt *offset;
2579 emitGEPOperation(BB, BB->end(), GEPI->getOperand(0), GEPI->op_begin()+1,
2580 GEPI->op_end(), baseReg, true, &offset, &pendingAdd);
2582 if (0 == pendingAdd && Class != cLong &&
2583 canUseAsImmediateForOpcode(offset, 0)) {
2584 BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(offset->getValue())
2589 unsigned indexReg = (pendingAdd != 0) ? pendingAdd : getReg(offset);
2591 if (Class == cLong) {
2592 unsigned indexPlus4 = makeAnotherReg(Type::IntTy);
2593 BuildMI(BB, PPC::ADDI, 2, indexPlus4).addReg(indexReg).addSImm(4);
2594 BuildMI(BB, IdxOpcode, 3).addReg(ValReg).addReg(indexReg).addReg(baseReg);
2595 BuildMI(BB, IdxOpcode, 3).addReg(ValReg+1).addReg(indexPlus4)
2599 BuildMI(BB, IdxOpcode, 3).addReg(ValReg).addReg(indexReg).addReg(baseReg);
2603 // If the store address wasn't the only use of a GEP, we fall back to the
2604 // standard path: store the ValReg at the value in AddressReg.
2605 unsigned AddressReg = getReg(I.getOperand(1));
2606 if (Class == cLong) {
2607 BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
2608 BuildMI(BB, ImmOpcode, 3).addReg(ValReg+1).addSImm(4).addReg(AddressReg);
2611 BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
2615 /// visitCastInst - Here we have various kinds of copying with or without sign
2616 /// extension going on.
2618 void ISel::visitCastInst(CastInst &CI) {
2619 Value *Op = CI.getOperand(0);
2621 unsigned SrcClass = getClassB(Op->getType());
2622 unsigned DestClass = getClassB(CI.getType());
2624 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2625 // of the case are GEP instructions, then the cast does not need to be
2626 // generated explicitly, it will be folded into the GEP.
2627 if (DestClass == cLong && SrcClass == cInt) {
2628 bool AllUsesAreGEPs = true;
2629 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2630 if (!isa<GetElementPtrInst>(*I)) {
2631 AllUsesAreGEPs = false;
2635 // No need to codegen this cast if all users are getelementptr instrs...
2636 if (AllUsesAreGEPs) return;
2639 unsigned DestReg = getReg(CI);
2640 MachineBasicBlock::iterator MI = BB->end();
2641 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2644 /// emitCastOperation - Common code shared between visitCastInst and constant
2645 /// expression cast support.
2647 void ISel::emitCastOperation(MachineBasicBlock *MBB,
2648 MachineBasicBlock::iterator IP,
2649 Value *Src, const Type *DestTy,
2651 const Type *SrcTy = Src->getType();
2652 unsigned SrcClass = getClassB(SrcTy);
2653 unsigned DestClass = getClassB(DestTy);
2654 unsigned SrcReg = getReg(Src, MBB, IP);
2656 // Implement casts to bool by using compare on the operand followed by set if
2657 // not zero on the result.
2658 if (DestTy == Type::BoolTy) {
2663 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2664 BuildMI(*MBB, IP, PPC::ADDIC, 2, TmpReg).addReg(SrcReg).addSImm(-1);
2665 BuildMI(*MBB, IP, PPC::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2669 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2670 unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
2671 BuildMI(*MBB, IP, PPC::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
2672 BuildMI(*MBB, IP, PPC::ADDIC, 2, TmpReg).addReg(SrcReg2).addSImm(-1);
2673 BuildMI(*MBB, IP, PPC::SUBFE, 2, DestReg).addReg(TmpReg)
2680 std::cerr << "ERROR: Cast fp-to-bool not implemented!\n";
2686 // Handle cast of Float -> Double
2687 if (SrcClass == cFP32 && DestClass == cFP64) {
2688 BuildMI(*MBB, IP, PPC::FMR, 1, DestReg).addReg(SrcReg);
2692 // Handle cast of Double -> Float
2693 if (SrcClass == cFP64 && DestClass == cFP32) {
2694 BuildMI(*MBB, IP, PPC::FRSP, 1, DestReg).addReg(SrcReg);
2698 // Handle casts from integer to floating point now...
2699 if (DestClass == cFP32 || DestClass == cFP64) {
2701 // Emit a library call for long to float conversion
2702 if (SrcClass == cLong) {
2703 std::vector<ValueRecord> Args;
2704 Args.push_back(ValueRecord(SrcReg, SrcTy));
2705 Function *floatFn = (DestClass == cFP32) ? __floatdisfFn : __floatdidfFn;
2706 MachineInstr *TheCall =
2707 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2708 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2709 TM.CalledFunctions.insert(floatFn);
2713 // Make sure we're dealing with a full 32 bits
2714 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2715 promote32(TmpReg, ValueRecord(SrcReg, SrcTy));
2719 // Spill the integer to memory and reload it from there.
2720 // Also spill room for a special conversion constant
2721 int ConstantFrameIndex =
2722 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2724 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2726 unsigned constantHi = makeAnotherReg(Type::IntTy);
2727 unsigned constantLo = makeAnotherReg(Type::IntTy);
2728 unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2729 unsigned TempF = makeAnotherReg(Type::DoubleTy);
2731 if (!SrcTy->isSigned()) {
2732 BuildMI(*BB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
2733 BuildMI(*BB, IP, PPC::LI, 1, constantLo).addSImm(0);
2734 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi),
2735 ConstantFrameIndex);
2736 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantLo),
2737 ConstantFrameIndex, 4);
2738 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi),
2740 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(SrcReg),
2742 addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, ConstF),
2743 ConstantFrameIndex);
2744 addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
2745 BuildMI(*BB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2747 unsigned TempLo = makeAnotherReg(Type::IntTy);
2748 BuildMI(*BB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
2749 BuildMI(*BB, IP, PPC::LIS, 1, constantLo).addSImm(0x8000);
2750 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi),
2751 ConstantFrameIndex);
2752 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantLo),
2753 ConstantFrameIndex, 4);
2754 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi),
2756 BuildMI(*BB, IP, PPC::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2757 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(TempLo),
2759 addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, ConstF),
2760 ConstantFrameIndex);
2761 addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
2762 BuildMI(*BB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2767 // Handle casts from floating point to integer now...
2768 if (SrcClass == cFP32 || SrcClass == cFP64) {
2769 static Function* const Funcs[] =
2770 { __fixsfdiFn, __fixdfdiFn, __fixunssfdiFn, __fixunsdfdiFn };
2771 // emit library call
2772 if (DestClass == cLong) {
2773 bool isDouble = SrcClass == cFP64;
2774 unsigned nameIndex = 2 * DestTy->isSigned() + isDouble;
2775 std::vector<ValueRecord> Args;
2776 Args.push_back(ValueRecord(SrcReg, SrcTy));
2777 Function *floatFn = Funcs[nameIndex];
2778 MachineInstr *TheCall =
2779 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2780 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2781 TM.CalledFunctions.insert(floatFn);
2786 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2788 if (DestTy->isSigned()) {
2789 unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2791 // Convert to integer in the FP reg and store it to a stack slot
2792 BuildMI(*BB, IP, PPC::FCTIWZ, 1, TempReg).addReg(SrcReg);
2793 addFrameReference(BuildMI(*BB, IP, PPC::STFD, 3)
2794 .addReg(TempReg), ValueFrameIdx);
2796 // There is no load signed byte opcode, so we must emit a sign extend for
2797 // that particular size. Make sure to source the new integer from the
2799 if (DestClass == cByte) {
2800 unsigned TempReg2 = makeAnotherReg(DestTy);
2801 addFrameReference(BuildMI(*BB, IP, PPC::LBZ, 2, TempReg2),
2803 BuildMI(*BB, IP, PPC::EXTSB, 1, DestReg).addReg(TempReg2);
2805 int offset = (DestClass == cShort) ? 6 : 4;
2806 unsigned LoadOp = (DestClass == cShort) ? PPC::LHA : PPC::LWZ;
2807 addFrameReference(BuildMI(*BB, IP, LoadOp, 2, DestReg),
2808 ValueFrameIdx, offset);
2811 unsigned Zero = getReg(ConstantFP::get(Type::DoubleTy, 0.0f));
2812 double maxInt = (1LL << 32) - 1;
2813 unsigned MaxInt = getReg(ConstantFP::get(Type::DoubleTy, maxInt));
2814 double border = 1LL << 31;
2815 unsigned Border = getReg(ConstantFP::get(Type::DoubleTy, border));
2816 unsigned UseZero = makeAnotherReg(Type::DoubleTy);
2817 unsigned UseMaxInt = makeAnotherReg(Type::DoubleTy);
2818 unsigned UseChoice = makeAnotherReg(Type::DoubleTy);
2819 unsigned TmpReg = makeAnotherReg(Type::DoubleTy);
2820 unsigned TmpReg2 = makeAnotherReg(Type::DoubleTy);
2821 unsigned ConvReg = makeAnotherReg(Type::DoubleTy);
2822 unsigned IntTmp = makeAnotherReg(Type::IntTy);
2823 unsigned XorReg = makeAnotherReg(Type::IntTy);
2825 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2826 // Update machine-CFG edges
2827 MachineBasicBlock *XorMBB = new MachineBasicBlock(BB->getBasicBlock());
2828 MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
2829 MachineBasicBlock *OldMBB = BB;
2830 ilist<MachineBasicBlock>::iterator It = BB; ++It;
2831 F->getBasicBlockList().insert(It, XorMBB);
2832 F->getBasicBlockList().insert(It, PhiMBB);
2833 BB->addSuccessor(XorMBB);
2834 BB->addSuccessor(PhiMBB);
2836 // Convert from floating point to unsigned 32-bit value
2837 // Use 0 if incoming value is < 0.0
2838 BuildMI(*BB, IP, PPC::FSEL, 3, UseZero).addReg(SrcReg).addReg(SrcReg)
2840 // Use 2**32 - 1 if incoming value is >= 2**32
2841 BuildMI(*BB, IP, PPC::FSUB, 2, UseMaxInt).addReg(MaxInt).addReg(SrcReg);
2842 BuildMI(*BB, IP, PPC::FSEL, 3, UseChoice).addReg(UseMaxInt)
2843 .addReg(UseZero).addReg(MaxInt);
2845 BuildMI(*BB, IP, PPC::FSUB, 2, TmpReg).addReg(UseChoice).addReg(Border);
2846 // Use difference if >= 2**31
2847 BuildMI(*BB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(UseChoice)
2849 BuildMI(*BB, IP, PPC::FSEL, 3, TmpReg2).addReg(TmpReg).addReg(TmpReg)
2851 // Convert to integer
2852 BuildMI(*BB, IP, PPC::FCTIWZ, 1, ConvReg).addReg(TmpReg2);
2853 addFrameReference(BuildMI(*BB, IP, PPC::STFD, 3).addReg(ConvReg),
2855 if (DestClass == cByte) {
2856 addFrameReference(BuildMI(*BB, IP, PPC::LBZ, 2, DestReg),
2858 } else if (DestClass == cShort) {
2859 addFrameReference(BuildMI(*BB, IP, PPC::LHZ, 2, DestReg),
2861 } if (DestClass == cInt) {
2862 addFrameReference(BuildMI(*BB, IP, PPC::LWZ, 2, IntTmp),
2864 BuildMI(*BB, IP, PPC::BLT, 2).addReg(PPC::CR0).addMBB(PhiMBB);
2865 BuildMI(*BB, IP, PPC::B, 1).addMBB(XorMBB);
2868 // add 2**31 if input was >= 2**31
2870 BuildMI(BB, PPC::XORIS, 2, XorReg).addReg(IntTmp).addImm(0x8000);
2871 XorMBB->addSuccessor(PhiMBB);
2874 // DestReg = phi [ IntTmp, OldMBB ], [ XorReg, XorMBB ]
2876 BuildMI(BB, PPC::PHI, 2, DestReg).addReg(IntTmp).addMBB(OldMBB)
2877 .addReg(XorReg).addMBB(XorMBB);
2883 // Check our invariants
2884 assert((SrcClass <= cInt || SrcClass == cLong) &&
2885 "Unhandled source class for cast operation!");
2886 assert((DestClass <= cInt || DestClass == cLong) &&
2887 "Unhandled destination class for cast operation!");
2889 bool sourceUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2890 bool destUnsigned = DestTy->isUnsigned();
2892 // Unsigned -> Unsigned, clear if larger,
2893 if (sourceUnsigned && destUnsigned) {
2894 // handle long dest class now to keep switch clean
2895 if (DestClass == cLong) {
2896 if (SrcClass == cLong) {
2897 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2898 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1)
2901 BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
2902 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
2908 // handle u{ byte, short, int } x u{ byte, short, int }
2909 unsigned clearBits = (SrcClass == cByte || DestClass == cByte) ? 24 : 16;
2913 if (SrcClass == DestClass)
2914 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2916 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2917 .addImm(0).addImm(clearBits).addImm(31);
2923 if (DestClass == cInt)
2924 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2926 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2927 .addImm(0).addImm(clearBits).addImm(31);
2934 if (!sourceUnsigned && !destUnsigned) {
2935 // handle long dest class now to keep switch clean
2936 if (DestClass == cLong) {
2937 if (SrcClass == cLong) {
2938 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2939 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1)
2942 BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg).addReg(SrcReg).addImm(31);
2943 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
2949 // handle { byte, short, int } x { byte, short, int }
2952 if (DestClass == cByte)
2953 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2955 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2958 if (DestClass == cByte)
2959 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2960 else if (DestClass == cShort)
2961 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2963 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2969 if (DestClass == cByte)
2970 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2971 else if (DestClass == cShort)
2972 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2974 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2980 // Unsigned -> Signed
2981 if (sourceUnsigned && !destUnsigned) {
2982 // handle long dest class now to keep switch clean
2983 if (DestClass == cLong) {
2984 if (SrcClass == cLong) {
2985 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2986 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1).
2989 BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
2990 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
2996 // handle u{ byte, short, int } -> { byte, short, int }
2999 if (DestClass == cByte)
3000 // uByte 255 -> signed byte == -1
3001 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3003 // uByte 255 -> signed short/int == 255
3004 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
3005 .addImm(24).addImm(31);
3008 if (DestClass == cByte)
3009 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3010 else if (DestClass == cShort)
3011 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3013 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
3014 .addImm(16).addImm(31);
3020 if (DestClass == cByte)
3021 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3022 else if (DestClass == cShort)
3023 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3025 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3031 // Signed -> Unsigned
3032 if (!sourceUnsigned && destUnsigned) {
3033 // handle long dest class now to keep switch clean
3034 if (DestClass == cLong) {
3035 if (SrcClass == cLong) {
3036 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3037 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1)
3040 BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg).addReg(SrcReg).addImm(31);
3041 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
3047 // handle { byte, short, int } -> u{ byte, short, int }
3048 unsigned clearBits = (DestClass == cByte) ? 24 : 16;
3052 if (DestClass == cByte || DestClass == cShort)
3053 // sbyte -1 -> ubyte 0x000000FF
3054 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
3055 .addImm(0).addImm(clearBits).addImm(31);
3057 // sbyte -1 -> ubyte 0xFFFFFFFF
3058 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3064 if (DestClass == cInt)
3065 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3067 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
3068 .addImm(0).addImm(clearBits).addImm(31);
3074 // Anything we haven't handled already, we can't (yet) handle at all.
3075 std::cerr << "Unhandled cast from " << SrcTy->getDescription()
3076 << "to " << DestTy->getDescription() << '\n';
3080 /// visitVANextInst - Implement the va_next instruction...
3082 void ISel::visitVANextInst(VANextInst &I) {
3083 unsigned VAList = getReg(I.getOperand(0));
3084 unsigned DestReg = getReg(I);
3087 switch (I.getArgType()->getTypeID()) {
3090 assert(0 && "Error: bad type for va_next instruction!");
3092 case Type::PointerTyID:
3093 case Type::UIntTyID:
3097 case Type::ULongTyID:
3098 case Type::LongTyID:
3099 case Type::DoubleTyID:
3104 // Increment the VAList pointer...
3105 BuildMI(BB, PPC::ADDI, 2, DestReg).addReg(VAList).addSImm(Size);
3108 void ISel::visitVAArgInst(VAArgInst &I) {
3109 unsigned VAList = getReg(I.getOperand(0));
3110 unsigned DestReg = getReg(I);
3112 switch (I.getType()->getTypeID()) {
3115 assert(0 && "Error: bad type for va_next instruction!");
3117 case Type::PointerTyID:
3118 case Type::UIntTyID:
3120 BuildMI(BB, PPC::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
3122 case Type::ULongTyID:
3123 case Type::LongTyID:
3124 BuildMI(BB, PPC::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
3125 BuildMI(BB, PPC::LWZ, 2, DestReg+1).addSImm(4).addReg(VAList);
3127 case Type::FloatTyID:
3128 BuildMI(BB, PPC::LFS, 2, DestReg).addSImm(0).addReg(VAList);
3130 case Type::DoubleTyID:
3131 BuildMI(BB, PPC::LFD, 2, DestReg).addSImm(0).addReg(VAList);
3136 /// visitGetElementPtrInst - instruction-select GEP instructions
3138 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
3139 if (canFoldGEPIntoLoadOrStore(&I))
3142 unsigned outputReg = getReg(I);
3143 emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(),
3144 outputReg, false, 0, 0);
3147 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
3148 /// constant expression GEP support.
3150 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
3151 MachineBasicBlock::iterator IP,
3152 Value *Src, User::op_iterator IdxBegin,
3153 User::op_iterator IdxEnd, unsigned TargetReg,
3154 bool GEPIsFolded, ConstantSInt **RemainderPtr,
3155 unsigned *PendingAddReg) {
3156 const TargetData &TD = TM.getTargetData();
3157 const Type *Ty = Src->getType();
3158 unsigned basePtrReg = getReg(Src, MBB, IP);
3159 int64_t constValue = 0;
3161 // Record the operations to emit the GEP in a vector so that we can emit them
3162 // after having analyzed the entire instruction.
3163 std::vector<CollapsedGepOp> ops;
3165 // GEPs have zero or more indices; we must perform a struct access
3166 // or array access for each one.
3167 for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
3170 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3171 // It's a struct access. idx is the index into the structure,
3172 // which names the field. Use the TargetData structure to
3173 // pick out what the layout of the structure is in memory.
3174 // Use the (constant) structure index's value to find the
3175 // right byte offset from the StructLayout class's list of
3176 // structure member offsets.
3177 unsigned fieldIndex = cast<ConstantUInt>(idx)->getValue();
3178 unsigned memberOffset =
3179 TD.getStructLayout(StTy)->MemberOffsets[fieldIndex];
3181 // StructType member offsets are always constant values. Add it to the
3183 constValue += memberOffset;
3185 // The next type is the member of the structure selected by the
3187 Ty = StTy->getElementType (fieldIndex);
3188 } else if (const SequentialType *SqTy = dyn_cast<SequentialType> (Ty)) {
3189 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
3190 // operand. Handle this case directly now...
3191 if (CastInst *CI = dyn_cast<CastInst>(idx))
3192 if (CI->getOperand(0)->getType() == Type::IntTy ||
3193 CI->getOperand(0)->getType() == Type::UIntTy)
3194 idx = CI->getOperand(0);
3196 // It's an array or pointer access: [ArraySize x ElementType].
3197 // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
3198 // must find the size of the pointed-to type (Not coincidentally, the next
3199 // type is the type of the elements in the array).
3200 Ty = SqTy->getElementType();
3201 unsigned elementSize = TD.getTypeSize(Ty);
3203 if (ConstantInt *C = dyn_cast<ConstantInt>(idx)) {
3204 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(C))
3205 constValue += CS->getValue() * elementSize;
3206 else if (ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
3207 constValue += CU->getValue() * elementSize;
3209 assert(0 && "Invalid ConstantInt GEP index type!");
3211 // Push current gep state to this point as an add
3212 ops.push_back(CollapsedGepOp(false, 0,
3213 ConstantSInt::get(Type::IntTy,constValue)));
3215 // Push multiply gep op and reset constant value
3216 ops.push_back(CollapsedGepOp(true, idx,
3217 ConstantSInt::get(Type::IntTy, elementSize)));
3223 // Emit instructions for all the collapsed ops
3224 bool pendingAdd = false;
3225 unsigned pendingAddReg = 0;
3227 for(std::vector<CollapsedGepOp>::iterator cgo_i = ops.begin(),
3228 cgo_e = ops.end(); cgo_i != cgo_e; ++cgo_i) {
3229 CollapsedGepOp& cgo = *cgo_i;
3230 unsigned nextBasePtrReg = makeAnotherReg(Type::IntTy);
3232 // If we didn't emit an add last time through the loop, we need to now so
3233 // that the base reg is updated appropriately.
3235 assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
3236 BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
3237 .addReg(pendingAddReg);
3238 basePtrReg = nextBasePtrReg;
3239 nextBasePtrReg = makeAnotherReg(Type::IntTy);
3245 // We know the elementSize is a constant, so we can emit a constant mul
3246 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3247 doMultiplyConst(MBB, IP, nextBasePtrReg, cgo.index, cgo.size);
3248 pendingAddReg = basePtrReg;
3251 // Try and generate an immediate addition if possible
3252 if (cgo.size->isNullValue()) {
3253 BuildMI(*MBB, IP, PPC::OR, 2, nextBasePtrReg).addReg(basePtrReg)
3254 .addReg(basePtrReg);
3255 } else if (canUseAsImmediateForOpcode(cgo.size, 0)) {
3256 BuildMI(*MBB, IP, PPC::ADDI, 2, nextBasePtrReg).addReg(basePtrReg)
3257 .addSImm(cgo.size->getValue());
3259 unsigned Op1r = getReg(cgo.size, MBB, IP);
3260 BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
3265 basePtrReg = nextBasePtrReg;
3267 // Add the current base register plus any accumulated constant value
3268 ConstantSInt *remainder = ConstantSInt::get(Type::IntTy, constValue);
3270 // If we are emitting this during a fold, copy the current base register to
3271 // the target, and save the current constant offset so the folding load or
3272 // store can try and use it as an immediate.
3274 // If this is a folded GEP and the last element was an index, then we need
3275 // to do some extra work to turn a shift/add/stw into a shift/stwx
3276 if (pendingAdd && 0 == remainder->getValue()) {
3277 assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
3278 *PendingAddReg = pendingAddReg;
3282 unsigned nextBasePtrReg = makeAnotherReg(Type::IntTy);
3283 assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
3284 BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
3285 .addReg(pendingAddReg);
3286 basePtrReg = nextBasePtrReg;
3289 BuildMI (*MBB, IP, PPC::OR, 2, TargetReg).addReg(basePtrReg)
3290 .addReg(basePtrReg);
3291 *RemainderPtr = remainder;
3295 // If we still have a pending add at this point, emit it now
3297 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3298 BuildMI(*MBB, IP, PPC::ADD, 2, TmpReg).addReg(pendingAddReg)
3299 .addReg(basePtrReg);
3300 basePtrReg = TmpReg;
3303 // After we have processed all the indices, the result is left in
3304 // basePtrReg. Move it to the register where we were expected to
3306 if (remainder->isNullValue()) {
3307 BuildMI (*MBB, IP, PPC::OR, 2, TargetReg).addReg(basePtrReg)
3308 .addReg(basePtrReg);
3309 } else if (canUseAsImmediateForOpcode(remainder, 0)) {
3310 BuildMI(*MBB, IP, PPC::ADDI, 2, TargetReg).addReg(basePtrReg)
3311 .addSImm(remainder->getValue());
3313 unsigned Op1r = getReg(remainder, MBB, IP);
3314 BuildMI(*MBB, IP, PPC::ADD, 2, TargetReg).addReg(basePtrReg).addReg(Op1r);
3318 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3319 /// frame manager, otherwise do it the hard way.
3321 void ISel::visitAllocaInst(AllocaInst &I) {
3322 // If this is a fixed size alloca in the entry block for the function, we
3323 // statically stack allocate the space, so we don't need to do anything here.
3325 if (dyn_castFixedAlloca(&I)) return;
3327 // Find the data size of the alloca inst's getAllocatedType.
3328 const Type *Ty = I.getAllocatedType();
3329 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3331 // Create a register to hold the temporary result of multiplying the type size
3332 // constant by the variable amount.
3333 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3335 // TotalSizeReg = mul <numelements>, <TypeSize>
3336 MachineBasicBlock::iterator MBBI = BB->end();
3337 ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, TySize);
3338 doMultiplyConst(BB, MBBI, TotalSizeReg, I.getArraySize(), CUI);
3340 // AddedSize = add <TotalSizeReg>, 15
3341 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
3342 BuildMI(BB, PPC::ADDI, 2, AddedSizeReg).addReg(TotalSizeReg).addSImm(15);
3344 // AlignedSize = and <AddedSize>, ~15
3345 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
3346 BuildMI(BB, PPC::RLWINM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
3347 .addImm(0).addImm(27);
3349 // Subtract size from stack pointer, thereby allocating some space.
3350 BuildMI(BB, PPC::SUB, 2, PPC::R1).addReg(PPC::R1).addReg(AlignedSize);
3352 // Put a pointer to the space into the result register, by copying
3353 // the stack pointer.
3354 BuildMI(BB, PPC::OR, 2, getReg(I)).addReg(PPC::R1).addReg(PPC::R1);
3356 // Inform the Frame Information that we have just allocated a variable-sized
3358 F->getFrameInfo()->CreateVariableSizedObject();
3361 /// visitMallocInst - Malloc instructions are code generated into direct calls
3362 /// to the library malloc.
3364 void ISel::visitMallocInst(MallocInst &I) {
3365 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3368 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3369 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3371 Arg = makeAnotherReg(Type::UIntTy);
3372 MachineBasicBlock::iterator MBBI = BB->end();
3373 ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, AllocSize);
3374 doMultiplyConst(BB, MBBI, Arg, I.getOperand(0), CUI);
3377 std::vector<ValueRecord> Args;
3378 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3379 MachineInstr *TheCall =
3380 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
3381 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
3382 TM.CalledFunctions.insert(mallocFn);
3386 /// visitFreeInst - Free instructions are code gen'd to call the free libc
3389 void ISel::visitFreeInst(FreeInst &I) {
3390 std::vector<ValueRecord> Args;
3391 Args.push_back(ValueRecord(I.getOperand(0)));
3392 MachineInstr *TheCall =
3393 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(freeFn, true);
3394 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
3395 TM.CalledFunctions.insert(freeFn);
3398 /// createPPC32ISelSimple - This pass converts an LLVM function into a machine
3399 /// code representation is a very simple peep-hole fashion.
3401 FunctionPass *llvm::createPPC32ISelSimple(TargetMachine &TM) {
3402 return new ISel(TM);