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 "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Pass.h"
19 #include "llvm/CodeGen/IntrinsicLowering.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "Support/Debug.h"
34 /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
35 /// PPC Representation.
38 cByte, cShort, cInt, cFP32, cFP64, cLong
42 /// getClass - Turn a primitive type into a "class" number which is based on the
43 /// size of the type, and whether or not it is floating point.
45 static inline TypeClass getClass(const Type *Ty) {
46 switch (Ty->getTypeID()) {
48 case Type::UByteTyID: return cByte; // Byte operands are class #0
50 case Type::UShortTyID: return cShort; // Short operands are class #1
53 case Type::PointerTyID: return cInt; // Ints and pointers are class #2
55 case Type::FloatTyID: return cFP32; // Single float is #3
56 case Type::DoubleTyID: return cFP64; // Double Point is #4
59 case Type::ULongTyID: return cLong; // Longs are class #5
61 assert(0 && "Invalid type to getClass!");
62 return cByte; // not reached
66 // getClassB - Just like getClass, but treat boolean values as ints.
67 static inline TypeClass getClassB(const Type *Ty) {
68 if (Ty == Type::BoolTy) return cInt;
73 struct ISel : public FunctionPass, InstVisitor<ISel> {
75 MachineFunction *F; // The function we are compiling into
76 MachineBasicBlock *BB; // The current MBB we are compiling
77 int VarArgsFrameIndex; // FrameIndex for start of varargs area
79 std::map<Value*, unsigned> RegMap; // Mapping between Values and SSA Regs
81 // External functions used in the Module
82 Function *fmodfFn, *fmodFn, *__moddi3Fn, *__divdi3Fn, *__umoddi3Fn,
83 *__udivdi3Fn, *__fixsfdiFn, *__fixdfdiFn, *__floatdisfFn, *__floatdidfFn,
86 // MBBMap - Mapping between LLVM BB -> Machine BB
87 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
89 // AllocaMap - Mapping from fixed sized alloca instructions to the
90 // FrameIndex for the alloca.
91 std::map<AllocaInst*, unsigned> AllocaMap;
93 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
95 bool doInitialization(Module &M) {
96 // Add external functions that we may call
97 Type *d = Type::DoubleTy;
98 Type *f = Type::FloatTy;
99 Type *l = Type::LongTy;
100 Type *ul = Type::ULongTy;
101 Type *voidPtr = PointerType::get(Type::SByteTy);
102 // float fmodf(float, float);
103 fmodfFn = M.getOrInsertFunction("fmodf", f, f, f, 0);
104 // double fmod(double, double);
105 fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
106 // long __moddi3(long, long);
107 __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
108 // long __divdi3(long, long);
109 __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
110 // unsigned long __umoddi3(unsigned long, unsigned long);
111 __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
112 // unsigned long __udivdi3(unsigned long, unsigned long);
113 __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
114 // long __fixsfdi(float)
115 __fixdfdiFn = M.getOrInsertFunction("__fixsfdi", l, f, 0);
116 // long __fixdfdi(double)
117 __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
118 // float __floatdisf(long)
119 __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
120 // double __floatdidf(long)
121 __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
122 // void* malloc(size_t)
123 mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
125 freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
129 /// runOnFunction - Top level implementation of instruction selection for
130 /// the entire function.
132 bool runOnFunction(Function &Fn) {
133 // First pass over the function, lower any unknown intrinsic functions
134 // with the IntrinsicLowering class.
135 LowerUnknownIntrinsicFunctionCalls(Fn);
137 F = &MachineFunction::construct(&Fn, TM);
139 // Create all of the machine basic blocks for the function...
140 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
141 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
145 // Copy incoming arguments off of the stack...
146 LoadArgumentsToVirtualRegs(Fn);
148 // Instruction select everything except PHI nodes
151 // Select the PHI nodes
158 // We always build a machine code representation for the function
162 virtual const char *getPassName() const {
163 return "PowerPC Simple Instruction Selection";
166 /// visitBasicBlock - This method is called when we are visiting a new basic
167 /// block. This simply creates a new MachineBasicBlock to emit code into
168 /// and adds it to the current MachineFunction. Subsequent visit* for
169 /// instructions will be invoked for all instructions in the basic block.
171 void visitBasicBlock(BasicBlock &LLVM_BB) {
172 BB = MBBMap[&LLVM_BB];
175 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
176 /// function, lowering any calls to unknown intrinsic functions into the
177 /// equivalent LLVM code.
179 void LowerUnknownIntrinsicFunctionCalls(Function &F);
181 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
182 /// from the stack into virtual registers.
184 void LoadArgumentsToVirtualRegs(Function &F);
186 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
187 /// because we have to generate our sources into the source basic blocks,
188 /// not the current one.
190 void SelectPHINodes();
192 // Visitation methods for various instructions. These methods simply emit
193 // fixed PowerPC code for each instruction.
195 // Control flow operators
196 void visitReturnInst(ReturnInst &RI);
197 void visitBranchInst(BranchInst &BI);
203 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
204 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
206 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
207 const std::vector<ValueRecord> &Args, bool isVarArg);
208 void visitCallInst(CallInst &I);
209 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
211 // Arithmetic operators
212 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
213 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
214 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
215 void visitMul(BinaryOperator &B);
217 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
218 void visitRem(BinaryOperator &B) { visitDivRem(B); }
219 void visitDivRem(BinaryOperator &B);
222 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
223 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
224 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
226 // Comparison operators...
227 void visitSetCondInst(SetCondInst &I);
228 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
229 MachineBasicBlock *MBB,
230 MachineBasicBlock::iterator MBBI);
231 void visitSelectInst(SelectInst &SI);
234 // Memory Instructions
235 void visitLoadInst(LoadInst &I);
236 void visitStoreInst(StoreInst &I);
237 void visitGetElementPtrInst(GetElementPtrInst &I);
238 void visitAllocaInst(AllocaInst &I);
239 void visitMallocInst(MallocInst &I);
240 void visitFreeInst(FreeInst &I);
243 void visitShiftInst(ShiftInst &I);
244 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
245 void visitCastInst(CastInst &I);
246 void visitVANextInst(VANextInst &I);
247 void visitVAArgInst(VAArgInst &I);
249 void visitInstruction(Instruction &I) {
250 std::cerr << "Cannot instruction select: " << I;
254 /// promote32 - Make a value 32-bits wide, and put it somewhere.
256 void promote32(unsigned targetReg, const ValueRecord &VR);
258 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
259 /// constant expression GEP support.
261 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
262 Value *Src, User::op_iterator IdxBegin,
263 User::op_iterator IdxEnd, unsigned TargetReg);
265 /// emitCastOperation - Common code shared between visitCastInst and
266 /// constant expression cast support.
268 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
269 Value *Src, const Type *DestTy, unsigned TargetReg);
271 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
272 /// and constant expression support.
274 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
275 MachineBasicBlock::iterator IP,
276 Value *Op0, Value *Op1,
277 unsigned OperatorClass, unsigned TargetReg);
279 /// emitBinaryFPOperation - This method handles emission of floating point
280 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
281 void emitBinaryFPOperation(MachineBasicBlock *BB,
282 MachineBasicBlock::iterator IP,
283 Value *Op0, Value *Op1,
284 unsigned OperatorClass, unsigned TargetReg);
286 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
287 Value *Op0, Value *Op1, unsigned TargetReg);
289 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
290 unsigned DestReg, const Type *DestTy,
291 unsigned Op0Reg, unsigned Op1Reg);
292 void doMultiplyConst(MachineBasicBlock *MBB,
293 MachineBasicBlock::iterator MBBI,
294 unsigned DestReg, const Type *DestTy,
295 unsigned Op0Reg, unsigned Op1Val);
297 void emitDivRemOperation(MachineBasicBlock *BB,
298 MachineBasicBlock::iterator IP,
299 Value *Op0, Value *Op1, bool isDiv,
302 /// emitSetCCOperation - Common code shared between visitSetCondInst and
303 /// constant expression support.
305 void emitSetCCOperation(MachineBasicBlock *BB,
306 MachineBasicBlock::iterator IP,
307 Value *Op0, Value *Op1, unsigned Opcode,
310 /// emitShiftOperation - Common code shared between visitShiftInst and
311 /// constant expression support.
313 void emitShiftOperation(MachineBasicBlock *MBB,
314 MachineBasicBlock::iterator IP,
315 Value *Op, Value *ShiftAmount, bool isLeftShift,
316 const Type *ResultTy, unsigned DestReg);
318 /// emitSelectOperation - Common code shared between visitSelectInst and the
319 /// constant expression support.
320 void emitSelectOperation(MachineBasicBlock *MBB,
321 MachineBasicBlock::iterator IP,
322 Value *Cond, Value *TrueVal, Value *FalseVal,
325 /// copyConstantToRegister - Output the instructions required to put the
326 /// specified constant into the specified register.
328 void copyConstantToRegister(MachineBasicBlock *MBB,
329 MachineBasicBlock::iterator MBBI,
330 Constant *C, unsigned Reg);
332 void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
333 unsigned LHS, unsigned RHS);
335 /// makeAnotherReg - This method returns the next register number we haven't
338 /// Long values are handled somewhat specially. They are always allocated
339 /// as pairs of 32 bit integer values. The register number returned is the
340 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
341 /// of the long value.
343 unsigned makeAnotherReg(const Type *Ty) {
344 assert(dynamic_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo()) &&
345 "Current target doesn't have PPC reg info??");
346 const PowerPCRegisterInfo *MRI =
347 static_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo());
348 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
349 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
350 // Create the lower part
351 F->getSSARegMap()->createVirtualRegister(RC);
352 // Create the upper part.
353 return F->getSSARegMap()->createVirtualRegister(RC)-1;
356 // Add the mapping of regnumber => reg class to MachineFunction
357 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
358 return F->getSSARegMap()->createVirtualRegister(RC);
361 /// getReg - This method turns an LLVM value into a register number.
363 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
364 unsigned getReg(Value *V) {
365 // Just append to the end of the current bb.
366 MachineBasicBlock::iterator It = BB->end();
367 return getReg(V, BB, It);
369 unsigned getReg(Value *V, MachineBasicBlock *MBB,
370 MachineBasicBlock::iterator IPt);
372 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
373 /// that is to be statically allocated with the initial stack frame
375 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
379 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
380 /// instruction in the entry block, return it. Otherwise, return a null
382 static AllocaInst *dyn_castFixedAlloca(Value *V) {
383 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
384 BasicBlock *BB = AI->getParent();
385 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
391 /// getReg - This method turns an LLVM value into a register number.
393 unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
394 MachineBasicBlock::iterator IPt) {
395 if (Constant *C = dyn_cast<Constant>(V)) {
396 unsigned Reg = makeAnotherReg(V->getType());
397 copyConstantToRegister(MBB, IPt, C, Reg);
399 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
400 // Do not emit noop casts at all.
401 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
402 return getReg(CI->getOperand(0), MBB, IPt);
403 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
404 unsigned Reg = makeAnotherReg(V->getType());
405 unsigned FI = getFixedSizedAllocaFI(AI);
406 addFrameReference(BuildMI(*MBB, IPt, PPC32::ADDI, 2, Reg), FI, 0, false);
410 unsigned &Reg = RegMap[V];
412 Reg = makeAnotherReg(V->getType());
419 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
420 /// that is to be statically allocated with the initial stack frame
422 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
423 // Already computed this?
424 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
425 if (I != AllocaMap.end() && I->first == AI) return I->second;
427 const Type *Ty = AI->getAllocatedType();
428 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
429 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
430 TySize *= CUI->getValue(); // Get total allocated size...
431 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
433 // Create a new stack object using the frame manager...
434 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
435 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
440 /// copyConstantToRegister - Output the instructions required to put the
441 /// specified constant into the specified register.
443 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
444 MachineBasicBlock::iterator IP,
445 Constant *C, unsigned R) {
446 if (C->getType()->isIntegral()) {
447 unsigned Class = getClassB(C->getType());
449 if (Class == cLong) {
450 // Copy the value into the register pair.
451 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
453 if (Val < (1ULL << 16)) {
454 BuildMI(*MBB, IP, PPC32::LI, 1, R).addImm(Val & 0xFFFF);
455 BuildMI(*MBB, IP, PPC32::LI, 1, R+1).addImm(0);
456 } else if (Val < (1ULL << 32)) {
457 unsigned Temp = makeAnotherReg(Type::IntTy);
458 BuildMI(*MBB, IP, PPC32::LIS, 1, Temp).addImm((Val >> 16) & 0xFFFF);
459 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(Temp).addImm(Val & 0xFFFF);
460 BuildMI(*MBB, IP, PPC32::LI, 1, R+1).addImm(0);
461 } else if (Val < (1ULL << 48)) {
462 unsigned Temp = makeAnotherReg(Type::IntTy);
463 BuildMI(*MBB, IP, PPC32::LIS, 1, Temp).addImm((Val >> 16) & 0xFFFF);
464 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(Temp).addImm(Val & 0xFFFF);
465 BuildMI(*MBB, IP, PPC32::LI, 1, R+1).addImm((Val >> 32) & 0xFFFF);
467 unsigned TempLo = makeAnotherReg(Type::IntTy);
468 unsigned TempHi = makeAnotherReg(Type::IntTy);
469 BuildMI(*MBB, IP, PPC32::LIS, 1, TempLo).addImm((Val >> 16) & 0xFFFF);
470 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(TempLo).addImm(Val & 0xFFFF);
471 BuildMI(*MBB, IP, PPC32::LIS, 1, TempHi).addImm((Val >> 48) & 0xFFFF);
472 BuildMI(*MBB, IP, PPC32::ORI, 2, R+1).addReg(TempHi)
473 .addImm((Val >> 32) & 0xFFFF);
478 assert(Class <= cInt && "Type not handled yet!");
480 if (C->getType() == Type::BoolTy) {
481 BuildMI(*MBB, IP, PPC32::LI, 1, R).addImm(C == ConstantBool::True);
482 } else if (Class == cByte || Class == cShort) {
483 ConstantInt *CI = cast<ConstantInt>(C);
484 BuildMI(*MBB, IP, PPC32::LI, 1, R).addImm(CI->getRawValue());
486 ConstantInt *CI = cast<ConstantInt>(C);
487 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
488 if (TheVal < 32768 && TheVal >= -32768) {
489 BuildMI(*MBB, IP, PPC32::LI, 1, R).addImm(CI->getRawValue());
491 unsigned TmpReg = makeAnotherReg(Type::IntTy);
492 BuildMI(*MBB, IP, PPC32::LIS, 1, TmpReg)
493 .addImm(CI->getRawValue() >> 16);
494 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(TmpReg)
495 .addImm(CI->getRawValue() & 0xFFFF);
498 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
499 // We need to spill the constant to memory...
500 MachineConstantPool *CP = F->getConstantPool();
501 unsigned CPI = CP->getConstantPoolIndex(CFP);
502 const Type *Ty = CFP->getType();
504 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
506 // Load addr of constant to reg; constant is located at PC + distance
507 unsigned CurPC = makeAnotherReg(Type::IntTy);
508 unsigned Reg1 = makeAnotherReg(Type::IntTy);
509 unsigned Reg2 = makeAnotherReg(Type::IntTy);
510 // Move PC to destination reg
511 BuildMI(*MBB, IP, PPC32::MovePCtoLR, 0, CurPC);
512 // Move value at PC + distance into return reg
513 BuildMI(*MBB, IP, PPC32::LOADHiAddr, 2, Reg1).addReg(CurPC)
514 .addConstantPoolIndex(CPI);
515 BuildMI(*MBB, IP, PPC32::LOADLoDirect, 2, Reg2).addReg(Reg1)
516 .addConstantPoolIndex(CPI);
518 unsigned LoadOpcode = (Ty == Type::FloatTy) ? PPC32::LFS : PPC32::LFD;
519 BuildMI(*MBB, IP, LoadOpcode, 2, R).addImm(0).addReg(Reg2);
520 } else if (isa<ConstantPointerNull>(C)) {
521 // Copy zero (null pointer) to the register.
522 BuildMI(*MBB, IP, PPC32::LI, 1, R).addImm(0);
523 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
524 // GV is located at PC + distance
525 unsigned CurPC = makeAnotherReg(Type::IntTy);
526 unsigned TmpReg = makeAnotherReg(GV->getType());
527 unsigned Opcode = (GV->hasWeakLinkage() || GV->isExternal()) ?
528 PPC32::LOADLoIndirect : PPC32::LOADLoDirect;
530 // Move PC to destination reg
531 BuildMI(*MBB, IP, PPC32::MovePCtoLR, 0, CurPC);
532 // Move value at PC + distance into return reg
533 BuildMI(*MBB, IP, PPC32::LOADHiAddr, 2, TmpReg).addReg(CurPC)
534 .addGlobalAddress(GV);
535 BuildMI(*MBB, IP, Opcode, 2, R).addReg(TmpReg).addGlobalAddress(GV);
537 std::cerr << "Offending constant: " << *C << "\n";
538 assert(0 && "Type not handled yet!");
542 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
543 /// the stack into virtual registers.
545 /// FIXME: When we can calculate which args are coming in via registers
546 /// source them from there instead.
547 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
548 unsigned ArgOffset = 20; // FIXME why is this not 24?
549 unsigned GPR_remaining = 8;
550 unsigned FPR_remaining = 13;
551 unsigned GPR_idx = 0, FPR_idx = 0;
552 static const unsigned GPR[] = {
553 PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
554 PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
556 static const unsigned FPR[] = {
557 PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6, PPC32::F7,
558 PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12, PPC32::F13
561 MachineFrameInfo *MFI = F->getFrameInfo();
563 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
564 bool ArgLive = !I->use_empty();
565 unsigned Reg = ArgLive ? getReg(*I) : 0;
566 int FI; // Frame object index
568 switch (getClassB(I->getType())) {
571 FI = MFI->CreateFixedObject(4, ArgOffset);
572 if (GPR_remaining > 0) {
573 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
574 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
575 .addReg(GPR[GPR_idx]);
577 addFrameReference(BuildMI(BB, PPC32::LBZ, 2, Reg), FI);
583 FI = MFI->CreateFixedObject(4, ArgOffset);
584 if (GPR_remaining > 0) {
585 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
586 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
587 .addReg(GPR[GPR_idx]);
589 addFrameReference(BuildMI(BB, PPC32::LHZ, 2, Reg), FI);
595 FI = MFI->CreateFixedObject(4, ArgOffset);
596 if (GPR_remaining > 0) {
597 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
598 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
599 .addReg(GPR[GPR_idx]);
601 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
607 FI = MFI->CreateFixedObject(8, ArgOffset);
608 if (GPR_remaining > 1) {
609 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
610 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx+1]);
611 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
612 .addReg(GPR[GPR_idx]);
613 BuildMI(BB, PPC32::OR, 2, Reg+1).addReg(GPR[GPR_idx+1])
614 .addReg(GPR[GPR_idx+1]);
616 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
617 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg+1), FI, 4);
620 ArgOffset += 4; // longs require 4 additional bytes
621 if (GPR_remaining > 1) {
622 GPR_remaining--; // uses up 2 GPRs
628 FI = MFI->CreateFixedObject(4, ArgOffset);
630 if (FPR_remaining > 0) {
631 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, FPR[FPR_idx]);
632 BuildMI(BB, PPC32::FMR, 1, Reg).addReg(FPR[FPR_idx]);
636 addFrameReference(BuildMI(BB, PPC32::LFS, 2, Reg), FI);
642 FI = MFI->CreateFixedObject(8, ArgOffset);
644 if (FPR_remaining > 0) {
645 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, FPR[FPR_idx]);
646 BuildMI(BB, PPC32::FMR, 1, Reg).addReg(FPR[FPR_idx]);
650 addFrameReference(BuildMI(BB, PPC32::LFD, 2, Reg), FI);
654 // doubles require 4 additional bytes and use 2 GPRs of param space
656 if (GPR_remaining > 0) {
662 assert(0 && "Unhandled argument type!");
664 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
665 if (GPR_remaining > 0) {
666 GPR_remaining--; // uses up 2 GPRs
671 // If the function takes variable number of arguments, add a frame offset for
672 // the start of the first vararg value... this is used to expand
674 if (Fn.getFunctionType()->isVarArg())
675 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
679 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
680 /// because we have to generate our sources into the source basic blocks, not
683 void ISel::SelectPHINodes() {
684 const TargetInstrInfo &TII = *TM.getInstrInfo();
685 const Function &LF = *F->getFunction(); // The LLVM function...
686 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
687 const BasicBlock *BB = I;
688 MachineBasicBlock &MBB = *MBBMap[I];
690 // Loop over all of the PHI nodes in the LLVM basic block...
691 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
692 for (BasicBlock::const_iterator I = BB->begin();
693 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
695 // Create a new machine instr PHI node, and insert it.
696 unsigned PHIReg = getReg(*PN);
697 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
698 PPC32::PHI, PN->getNumOperands(), PHIReg);
700 MachineInstr *LongPhiMI = 0;
701 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
702 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
703 PPC32::PHI, PN->getNumOperands(), PHIReg+1);
705 // PHIValues - Map of blocks to incoming virtual registers. We use this
706 // so that we only initialize one incoming value for a particular block,
707 // even if the block has multiple entries in the PHI node.
709 std::map<MachineBasicBlock*, unsigned> PHIValues;
711 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
712 MachineBasicBlock *PredMBB = 0;
713 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
714 PE = MBB.pred_end (); PI != PE; ++PI)
715 if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
719 assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
722 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
723 PHIValues.lower_bound(PredMBB);
725 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
726 // We already inserted an initialization of the register for this
727 // predecessor. Recycle it.
728 ValReg = EntryIt->second;
731 // Get the incoming value into a virtual register.
733 Value *Val = PN->getIncomingValue(i);
735 // If this is a constant or GlobalValue, we may have to insert code
736 // into the basic block to compute it into a virtual register.
737 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
738 isa<GlobalValue>(Val)) {
739 // Simple constants get emitted at the end of the basic block,
740 // before any terminator instructions. We "know" that the code to
741 // move a constant into a register will never clobber any flags.
742 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
744 // Because we don't want to clobber any values which might be in
745 // physical registers with the computation of this constant (which
746 // might be arbitrarily complex if it is a constant expression),
747 // just insert the computation at the top of the basic block.
748 MachineBasicBlock::iterator PI = PredMBB->begin();
750 // Skip over any PHI nodes though!
751 while (PI != PredMBB->end() && PI->getOpcode() == PPC32::PHI)
754 ValReg = getReg(Val, PredMBB, PI);
757 // Remember that we inserted a value for this PHI for this predecessor
758 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
761 PhiMI->addRegOperand(ValReg);
762 PhiMI->addMachineBasicBlockOperand(PredMBB);
764 LongPhiMI->addRegOperand(ValReg+1);
765 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
769 // Now that we emitted all of the incoming values for the PHI node, make
770 // sure to reposition the InsertPoint after the PHI that we just added.
771 // This is needed because we might have inserted a constant into this
772 // block, right after the PHI's which is before the old insert point!
773 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
780 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
781 // it into the conditional branch or select instruction which is the only user
782 // of the cc instruction. This is the case if the conditional branch is the
783 // only user of the setcc, and if the setcc is in the same basic block as the
784 // conditional branch. We also don't handle long arguments below, so we reject
785 // them here as well.
787 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
788 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
789 if (SCI->hasOneUse()) {
790 Instruction *User = cast<Instruction>(SCI->use_back());
791 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
792 SCI->getParent() == User->getParent())
798 // Return a fixed numbering for setcc instructions which does not depend on the
799 // order of the opcodes.
801 static unsigned getSetCCNumber(unsigned Opcode) {
803 default: assert(0 && "Unknown setcc instruction!");
804 case Instruction::SetEQ: return 0;
805 case Instruction::SetNE: return 1;
806 case Instruction::SetLT: return 2;
807 case Instruction::SetGE: return 3;
808 case Instruction::SetGT: return 4;
809 case Instruction::SetLE: return 5;
813 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
815 default: assert(0 && "Unknown setcc instruction!");
816 case Instruction::SetEQ: return PPC32::BEQ;
817 case Instruction::SetNE: return PPC32::BNE;
818 case Instruction::SetLT: return PPC32::BLT;
819 case Instruction::SetGE: return PPC32::BGE;
820 case Instruction::SetGT: return PPC32::BGT;
821 case Instruction::SetLE: return PPC32::BLE;
825 static unsigned invertPPCBranchOpcode(unsigned Opcode) {
827 default: assert(0 && "Unknown PPC32 branch opcode!");
828 case PPC32::BEQ: return PPC32::BNE;
829 case PPC32::BNE: return PPC32::BEQ;
830 case PPC32::BLT: return PPC32::BGE;
831 case PPC32::BGE: return PPC32::BLT;
832 case PPC32::BGT: return PPC32::BLE;
833 case PPC32::BLE: return PPC32::BGT;
837 /// emitUCOM - emits an unordered FP compare.
838 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
839 unsigned LHS, unsigned RHS) {
840 BuildMI(*MBB, IP, PPC32::FCMPU, 2, PPC32::CR0).addReg(LHS).addReg(RHS);
843 /// EmitComparison - emits a comparison of the two operands, returning the
844 /// extended setcc code to use. The result is in CR0.
846 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
847 MachineBasicBlock *MBB,
848 MachineBasicBlock::iterator IP) {
849 // The arguments are already supposed to be of the same type.
850 const Type *CompTy = Op0->getType();
851 unsigned Class = getClassB(CompTy);
852 unsigned Op0r = getReg(Op0, MBB, IP);
854 // Special case handling of: cmp R, i
855 if (isa<ConstantPointerNull>(Op1)) {
856 BuildMI(*MBB, IP, PPC32::CMPI, 2, PPC32::CR0).addReg(Op0r).addImm(0);
857 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
858 if (Class == cByte || Class == cShort || Class == cInt) {
859 unsigned Op1v = CI->getRawValue();
861 // Mask off any upper bits of the constant, if there are any...
862 Op1v &= (1ULL << (8 << Class)) - 1;
864 // Compare immediate or promote to reg?
866 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMPI : PPC32::CMPLI, 3,
867 PPC32::CR0).addImm(0).addReg(Op0r).addImm(Op1v);
869 unsigned Op1r = getReg(Op1, MBB, IP);
870 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 3,
871 PPC32::CR0).addImm(0).addReg(Op0r).addReg(Op1r);
875 assert(Class == cLong && "Unknown integer class!");
876 unsigned LowCst = CI->getRawValue();
877 unsigned HiCst = CI->getRawValue() >> 32;
878 if (OpNum < 2) { // seteq, setne
879 unsigned LoTmp = Op0r;
881 unsigned LoLow = makeAnotherReg(Type::IntTy);
882 unsigned LoTmp = makeAnotherReg(Type::IntTy);
883 BuildMI(*MBB, IP, PPC32::XORI, 2, LoLow).addReg(Op0r).addImm(LowCst);
884 BuildMI(*MBB, IP, PPC32::XORIS, 2, LoTmp).addReg(LoLow)
885 .addImm(LowCst >> 16);
887 unsigned HiTmp = Op0r+1;
889 unsigned HiLow = makeAnotherReg(Type::IntTy);
890 unsigned HiTmp = makeAnotherReg(Type::IntTy);
891 BuildMI(*MBB, IP, PPC32::XORI, 2, HiLow).addReg(Op0r+1).addImm(HiCst);
892 BuildMI(*MBB, IP, PPC32::XORIS, 2, HiTmp).addReg(HiLow)
893 .addImm(HiCst >> 16);
895 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
896 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
899 unsigned ConstReg = makeAnotherReg(CompTy);
900 unsigned CondReg = makeAnotherReg(Type::IntTy);
901 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
902 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
903 copyConstantToRegister(MBB, IP, CI, ConstReg);
905 // FIXME: this is inefficient, but avoids branches
907 // compare hi word -> cr0
908 // compare lo word -> cr1
909 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMPI : PPC32::CMPLI, 3,
910 PPC32::CR0).addImm(0).addReg(Op0r+1).addReg(ConstReg+1);
911 BuildMI(*MBB, IP, PPC32::CMPLI, 3, PPC32::CR1).addImm(0).addReg(Op0r)
913 BuildMI(*MBB, IP, PPC32::MFCR, 0, CondReg);
914 // shift amount = 4 * CR0[EQ]
915 BuildMI(*MBB, IP, PPC32::RLWINM, 4, TmpReg1).addReg(CondReg).addImm(5)
916 .addImm(29).addImm(29);
917 // shift cr1 into cr0 position if op0.hi and const.hi were equal
918 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(CondReg)
920 // cr0 == ( op0.hi != const.hi ) ? cr0 : cr1
921 BuildMI(*MBB, IP, PPC32::MTCRF, 2).addImm(1).addReg(TmpReg2);
928 unsigned Op1r = getReg(Op1, MBB, IP);
930 default: assert(0 && "Unknown type class!");
934 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 2,
935 PPC32::CR0).addReg(Op0r).addReg(Op1r);
940 emitUCOM(MBB, IP, Op0r, Op1r);
944 if (OpNum < 2) { // seteq, setne
945 unsigned LoTmp = makeAnotherReg(Type::IntTy);
946 unsigned HiTmp = makeAnotherReg(Type::IntTy);
947 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
948 BuildMI(*MBB, IP, PPC32::XOR, 2, LoTmp).addReg(Op0r).addReg(Op1r);
949 BuildMI(*MBB, IP, PPC32::XOR, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
950 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
951 break; // Allow the sete or setne to be generated from flags set by OR
953 unsigned CondReg = makeAnotherReg(Type::IntTy);
954 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
955 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
957 // FIXME: this is inefficient, but avoids branches
959 // compare hi word -> cr0
960 // compare lo word -> cr1
961 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMPI : PPC32::CMPLI, 3,
962 PPC32::CR0).addImm(0).addReg(Op0r+1).addReg(Op1r+1);
963 BuildMI(*MBB, IP, PPC32::CMPLI, 3, PPC32::CR1).addImm(0).addReg(Op0r)
965 BuildMI(*MBB, IP, PPC32::MFCR, 0, CondReg);
966 // shift amount = 4 * CR0[EQ]
967 BuildMI(*MBB, IP, PPC32::RLWINM, 4, TmpReg1).addReg(CondReg).addImm(5)
968 .addImm(29).addImm(29);
969 // shift cr1 into cr0 position if op0.hi and op1.hi were equal
970 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(CondReg)
972 // cr0 == ( op0.hi != op1.hi ) ? cr0 : cr1
973 BuildMI(*MBB, IP, PPC32::MTCRF, 2).addImm(1).addReg(TmpReg2);
981 /// visitSetCondInst - emit code to calculate the condition via
982 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
984 void ISel::visitSetCondInst(SetCondInst &I) {
985 if (canFoldSetCCIntoBranchOrSelect(&I))
988 unsigned DestReg = getReg(I);
989 unsigned OpNum = I.getOpcode();
990 const Type *Ty = I.getOperand (0)->getType();
992 EmitComparison(OpNum, I.getOperand(0), I.getOperand(1), BB, BB->end());
994 unsigned Opcode = getPPCOpcodeForSetCCNumber(OpNum);
995 MachineBasicBlock *thisMBB = BB;
996 const BasicBlock *LLVM_BB = BB->getBasicBlock();
997 ilist<MachineBasicBlock>::iterator It = BB;
1002 // cmpTY cr0, r1, r2
1006 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1007 // if we could insert other, non-terminator instructions after the
1008 // bCC. But MBB->getFirstTerminator() can't understand this.
1009 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1010 F->getBasicBlockList().insert(It, copy1MBB);
1011 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0).addMBB(copy1MBB);
1012 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1013 F->getBasicBlockList().insert(It, copy0MBB);
1014 BuildMI(BB, PPC32::B, 1).addMBB(copy0MBB);
1015 // Update machine-CFG edges
1016 BB->addSuccessor(copy1MBB);
1017 BB->addSuccessor(copy0MBB);
1020 // %FalseValue = li 0
1023 unsigned FalseValue = makeAnotherReg(I.getType());
1024 BuildMI(BB, PPC32::LI, 1, FalseValue).addImm(0);
1025 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1026 F->getBasicBlockList().insert(It, sinkMBB);
1027 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
1028 // Update machine-CFG edges
1029 BB->addSuccessor(sinkMBB);
1031 DEBUG(std::cerr << "thisMBB is at " << (void*)thisMBB << "\n");
1032 DEBUG(std::cerr << "copy1MBB is at " << (void*)copy1MBB << "\n");
1033 DEBUG(std::cerr << "copy0MBB is at " << (void*)copy0MBB << "\n");
1034 DEBUG(std::cerr << "sinkMBB is at " << (void*)sinkMBB << "\n");
1037 // %TrueValue = li 1
1040 unsigned TrueValue = makeAnotherReg (I.getType ());
1041 BuildMI(BB, PPC32::LI, 1, TrueValue).addImm(1);
1042 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
1043 // Update machine-CFG edges
1044 BB->addSuccessor(sinkMBB);
1047 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1050 BuildMI(BB, PPC32::PHI, 4, DestReg).addReg(FalseValue)
1051 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1054 void ISel::visitSelectInst(SelectInst &SI) {
1055 unsigned DestReg = getReg(SI);
1056 MachineBasicBlock::iterator MII = BB->end();
1057 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1058 SI.getFalseValue(), DestReg);
1061 /// emitSelect - Common code shared between visitSelectInst and the constant
1062 /// expression support.
1063 /// FIXME: this is most likely broken in one or more ways. Namely, PowerPC has
1064 /// no select instruction. FSEL only works for comparisons against zero.
1065 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1066 MachineBasicBlock::iterator IP,
1067 Value *Cond, Value *TrueVal, Value *FalseVal,
1069 unsigned SelectClass = getClassB(TrueVal->getType());
1072 // See if we can fold the setcc into the select instruction, or if we have
1073 // to get the register of the Cond value
1074 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1075 // We successfully folded the setcc into the select instruction.
1077 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1078 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1080 Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1082 unsigned CondReg = getReg(Cond, MBB, IP);
1084 BuildMI(*MBB, IP, PPC32::CMPI, 2, PPC32::CR0).addReg(CondReg).addImm(0);
1085 Opcode = getPPCOpcodeForSetCCNumber(Instruction::SetNE);
1090 // cmpTY cr0, r1, r2
1094 MachineBasicBlock *thisMBB = BB;
1095 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1096 ilist<MachineBasicBlock>::iterator It = BB;
1099 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1100 // if we could insert other, non-terminator instructions after the
1101 // bCC. But MBB->getFirstTerminator() can't understand this.
1102 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1103 F->getBasicBlockList().insert(It, copy1MBB);
1104 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0).addMBB(copy1MBB);
1105 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1106 F->getBasicBlockList().insert(It, copy0MBB);
1107 BuildMI(BB, PPC32::B, 1).addMBB(copy0MBB);
1108 // Update machine-CFG edges
1109 BB->addSuccessor(copy1MBB);
1110 BB->addSuccessor(copy0MBB);
1112 // FIXME: spill code is being generated after the branch and before copy1MBB
1113 // this is bad, since it will never be run
1116 // %FalseValue = ...
1119 unsigned FalseValue = getReg(FalseVal, BB, BB->begin());
1120 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1121 F->getBasicBlockList().insert(It, sinkMBB);
1122 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
1123 // Update machine-CFG edges
1124 BB->addSuccessor(sinkMBB);
1130 unsigned TrueValue = getReg(TrueVal, BB, BB->begin());
1131 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
1132 // Update machine-CFG edges
1133 BB->addSuccessor(sinkMBB);
1136 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1139 BuildMI(BB, PPC32::PHI, 4, DestReg).addReg(FalseValue)
1140 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1146 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1147 /// operand, in the specified target register.
1149 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1150 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1152 Value *Val = VR.Val;
1153 const Type *Ty = VR.Ty;
1155 if (Constant *C = dyn_cast<Constant>(Val)) {
1156 Val = ConstantExpr::getCast(C, Type::IntTy);
1160 // If this is a simple constant, just emit a load directly to avoid the copy
1161 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1162 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1164 if (TheVal < 32768 && TheVal >= -32768) {
1165 BuildMI(BB, PPC32::LI, 1, targetReg).addImm(TheVal);
1167 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1168 BuildMI(BB, PPC32::LIS, 1, TmpReg).addImm(TheVal >> 16);
1169 BuildMI(BB, PPC32::ORI, 2, targetReg).addReg(TmpReg)
1170 .addImm(TheVal & 0xFFFF);
1176 // Make sure we have the register number for this value...
1177 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1179 switch (getClassB(Ty)) {
1181 // Extend value into target register (8->32)
1183 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1184 .addZImm(24).addZImm(31);
1186 BuildMI(BB, PPC32::EXTSB, 1, targetReg).addReg(Reg);
1189 // Extend value into target register (16->32)
1191 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1192 .addZImm(16).addZImm(31);
1194 BuildMI(BB, PPC32::EXTSH, 1, targetReg).addReg(Reg);
1197 // Move value into target register (32->32)
1198 BuildMI(BB, PPC32::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1201 assert(0 && "Unpromotable operand class in promote32");
1205 /// visitReturnInst - implemented with BLR
1207 void ISel::visitReturnInst(ReturnInst &I) {
1208 // Only do the processing if this is a non-void return
1209 if (I.getNumOperands() > 0) {
1210 Value *RetVal = I.getOperand(0);
1211 switch (getClassB(RetVal->getType())) {
1212 case cByte: // integral return values: extend or move into r3 and return
1215 promote32(PPC32::R3, ValueRecord(RetVal));
1218 case cFP64: { // Floats & Doubles: Return in f1
1219 unsigned RetReg = getReg(RetVal);
1220 BuildMI(BB, PPC32::FMR, 1, PPC32::F1).addReg(RetReg);
1224 unsigned RetReg = getReg(RetVal);
1225 BuildMI(BB, PPC32::OR, 2, PPC32::R3).addReg(RetReg).addReg(RetReg);
1226 BuildMI(BB, PPC32::OR, 2, PPC32::R4).addReg(RetReg+1).addReg(RetReg+1);
1230 visitInstruction(I);
1233 BuildMI(BB, PPC32::BLR, 1).addImm(0);
1236 // getBlockAfter - Return the basic block which occurs lexically after the
1238 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1239 Function::iterator I = BB; ++I; // Get iterator to next block
1240 return I != BB->getParent()->end() ? &*I : 0;
1243 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1244 /// that since code layout is frozen at this point, that if we are trying to
1245 /// jump to a block that is the immediate successor of the current block, we can
1246 /// just make a fall-through (but we don't currently).
1248 void ISel::visitBranchInst(BranchInst &BI) {
1249 // Update machine-CFG edges
1250 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1251 if (BI.isConditional())
1252 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1254 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1256 if (!BI.isConditional()) { // Unconditional branch?
1257 if (BI.getSuccessor(0) != NextBB)
1258 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1262 // See if we can fold the setcc into the branch itself...
1263 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1265 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1266 // computed some other way...
1267 unsigned condReg = getReg(BI.getCondition());
1268 BuildMI(BB, PPC32::CMPLI, 3, PPC32::CR1).addImm(0).addReg(condReg)
1270 if (BI.getSuccessor(1) == NextBB) {
1271 if (BI.getSuccessor(0) != NextBB)
1272 BuildMI(BB, PPC32::BNE, 2).addReg(PPC32::CR1)
1273 .addMBB(MBBMap[BI.getSuccessor(0)]);
1275 BuildMI(BB, PPC32::BEQ, 2).addReg(PPC32::CR1)
1276 .addMBB(MBBMap[BI.getSuccessor(1)]);
1278 if (BI.getSuccessor(0) != NextBB)
1279 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1284 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1285 unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1286 MachineBasicBlock::iterator MII = BB->end();
1287 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1289 if (BI.getSuccessor(0) != NextBB) {
1290 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1291 .addMBB(MBBMap[BI.getSuccessor(0)]);
1292 if (BI.getSuccessor(1) != NextBB)
1293 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1295 // Change to the inverse condition...
1296 if (BI.getSuccessor(1) != NextBB) {
1297 Opcode = invertPPCBranchOpcode(Opcode);
1298 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1299 .addMBB(MBBMap[BI.getSuccessor(1)]);
1304 static Constant* minUConstantForValue(uint64_t val) {
1306 return ConstantBool::get(val);
1307 else if (ConstantUInt::isValueValidForType(Type::UShortTy, val))
1308 return ConstantUInt::get(Type::UShortTy, val);
1309 else if (ConstantUInt::isValueValidForType(Type::UIntTy, val))
1310 return ConstantUInt::get(Type::UIntTy, val);
1311 else if (ConstantUInt::isValueValidForType(Type::ULongTy, val))
1312 return ConstantUInt::get(Type::ULongTy, val);
1314 std::cerr << "Value: " << val << " not accepted for any integral type!\n";
1318 /// doCall - This emits an abstract call instruction, setting up the arguments
1319 /// and the return value as appropriate. For the actual function call itself,
1320 /// it inserts the specified CallMI instruction into the stream.
1322 /// FIXME: See Documentation at the following URL for "correct" behavior
1323 /// <http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html>
1324 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1325 const std::vector<ValueRecord> &Args, bool isVarArg) {
1326 // Count how many bytes are to be pushed on the stack...
1327 unsigned NumBytes = 0;
1329 if (!Args.empty()) {
1330 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1331 switch (getClassB(Args[i].Ty)) {
1332 case cByte: case cShort: case cInt:
1333 NumBytes += 4; break;
1335 NumBytes += 8; break;
1337 NumBytes += 4; break;
1339 NumBytes += 8; break;
1341 default: assert(0 && "Unknown class!");
1344 // Adjust the stack pointer for the new arguments...
1345 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1347 // Arguments go on the stack in reverse order, as specified by the ABI.
1348 // Offset to the paramater area on the stack is 24.
1349 unsigned ArgOffset = 24;
1350 int GPR_remaining = 8, FPR_remaining = 13;
1351 unsigned GPR_idx = 0, FPR_idx = 0;
1352 static const unsigned GPR[] = {
1353 PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
1354 PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
1356 static const unsigned FPR[] = {
1357 PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6,
1358 PPC32::F7, PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12,
1362 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1364 switch (getClassB(Args[i].Ty)) {
1367 // Promote arg to 32 bits wide into a temporary register...
1368 ArgReg = makeAnotherReg(Type::UIntTy);
1369 promote32(ArgReg, Args[i]);
1372 if (GPR_remaining > 0) {
1373 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1375 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1377 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1382 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1385 if (GPR_remaining > 0) {
1386 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1388 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1390 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1395 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1397 // Reg or stack? Note that PPC calling conventions state that long args
1398 // are passed rN = hi, rN+1 = lo, opposite of LLVM.
1399 if (GPR_remaining > 1) {
1400 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg+1)
1402 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx+1]).addReg(ArgReg)
1404 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1405 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1407 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1409 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg+1).addImm(ArgOffset+4)
1413 ArgOffset += 4; // 8 byte entry, not 4.
1414 GPR_remaining -= 1; // uses up 2 GPRs
1418 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1420 if (FPR_remaining > 0) {
1421 BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1422 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1426 // If this is a vararg function, and there are GPRs left, also
1427 // pass the float in an int. Otherwise, put it on the stack.
1429 BuildMI(BB, PPC32::STFS, 3).addReg(ArgReg).addImm(ArgOffset)
1431 if (GPR_remaining > 0) {
1432 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx])
1433 .addImm(ArgOffset).addReg(ArgReg);
1434 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1438 BuildMI(BB, PPC32::STFS, 3).addReg(ArgReg).addImm(ArgOffset)
1443 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1445 if (FPR_remaining > 0) {
1446 BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1447 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1450 // For vararg functions, must pass doubles via int regs as well
1452 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addImm(ArgOffset)
1455 if (GPR_remaining > 1) {
1456 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx]).addImm(ArgOffset)
1458 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx+1])
1459 .addImm(ArgOffset+4).addReg(PPC32::R1);
1460 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1461 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1465 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addImm(ArgOffset)
1468 // Doubles use 8 bytes, and 2 GPRs worth of param space
1474 default: assert(0 && "Unknown class!");
1481 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(0);
1484 BB->push_back(CallMI);
1485 BuildMI(BB, PPC32::ADJCALLSTACKUP, 1).addImm(NumBytes);
1487 // If there is a return value, scavenge the result from the location the call
1490 if (Ret.Ty != Type::VoidTy) {
1491 unsigned DestClass = getClassB(Ret.Ty);
1492 switch (DestClass) {
1496 // Integral results are in r3
1497 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1499 case cFP32: // Floating-point return values live in f1
1501 BuildMI(BB, PPC32::FMR, 1, Ret.Reg).addReg(PPC32::F1);
1503 case cLong: // Long values are in r3 hi:r4 lo
1504 BuildMI(BB, PPC32::OR, 2, Ret.Reg+1).addReg(PPC32::R3).addReg(PPC32::R3);
1505 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R4).addReg(PPC32::R4);
1507 default: assert(0 && "Unknown class!");
1513 /// visitCallInst - Push args on stack and do a procedure call instruction.
1514 void ISel::visitCallInst(CallInst &CI) {
1515 MachineInstr *TheCall;
1516 Function *F = CI.getCalledFunction();
1518 // Is it an intrinsic function call?
1519 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1520 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1524 // Emit a CALL instruction with PC-relative displacement.
1525 TheCall = BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(F, true);
1526 } else { // Emit an indirect call through the CTR
1527 unsigned Reg = getReg(CI.getCalledValue());
1528 BuildMI(BB, PPC32::MTCTR, 1).addReg(Reg);
1529 TheCall = BuildMI(PPC32::CALLindirect, 2).addZImm(20).addZImm(0);
1532 std::vector<ValueRecord> Args;
1533 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1534 Args.push_back(ValueRecord(CI.getOperand(i)));
1536 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1537 bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1538 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1542 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1544 static Value *dyncastIsNan(Value *V) {
1545 if (CallInst *CI = dyn_cast<CallInst>(V))
1546 if (Function *F = CI->getCalledFunction())
1547 if (F->getIntrinsicID() == Intrinsic::isunordered)
1548 return CI->getOperand(1);
1552 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1553 /// or's whos operands are all calls to the isnan predicate.
1554 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1555 assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1557 // Check all uses, which will be or's of isnans if this predicate is true.
1558 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1559 Instruction *I = cast<Instruction>(*UI);
1560 if (I->getOpcode() != Instruction::Or) return false;
1561 if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1562 if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1568 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1569 /// function, lowering any calls to unknown intrinsic functions into the
1570 /// equivalent LLVM code.
1572 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1573 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1574 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1575 if (CallInst *CI = dyn_cast<CallInst>(I++))
1576 if (Function *F = CI->getCalledFunction())
1577 switch (F->getIntrinsicID()) {
1578 case Intrinsic::not_intrinsic:
1579 case Intrinsic::vastart:
1580 case Intrinsic::vacopy:
1581 case Intrinsic::vaend:
1582 case Intrinsic::returnaddress:
1583 case Intrinsic::frameaddress:
1584 // FIXME: should lower this ourselves
1585 // case Intrinsic::isunordered:
1586 // We directly implement these intrinsics
1588 case Intrinsic::readio: {
1589 // On PPC, memory operations are in-order. Lower this intrinsic
1590 // into a volatile load.
1591 Instruction *Before = CI->getPrev();
1592 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1593 CI->replaceAllUsesWith(LI);
1594 BB->getInstList().erase(CI);
1597 case Intrinsic::writeio: {
1598 // On PPC, memory operations are in-order. Lower this intrinsic
1599 // into a volatile store.
1600 Instruction *Before = CI->getPrev();
1601 StoreInst *SI = new StoreInst(CI->getOperand(1),
1602 CI->getOperand(2), true, CI);
1603 CI->replaceAllUsesWith(SI);
1604 BB->getInstList().erase(CI);
1608 // All other intrinsic calls we must lower.
1609 Instruction *Before = CI->getPrev();
1610 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1611 if (Before) { // Move iterator to instruction after call
1619 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1620 unsigned TmpReg1, TmpReg2, TmpReg3;
1622 case Intrinsic::vastart:
1623 // Get the address of the first vararg value...
1624 TmpReg1 = getReg(CI);
1625 addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1), VarArgsFrameIndex,
1629 case Intrinsic::vacopy:
1630 TmpReg1 = getReg(CI);
1631 TmpReg2 = getReg(CI.getOperand(1));
1632 BuildMI(BB, PPC32::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1634 case Intrinsic::vaend: return;
1636 case Intrinsic::returnaddress:
1637 TmpReg1 = getReg(CI);
1638 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1639 MachineFrameInfo *MFI = F->getFrameInfo();
1640 unsigned NumBytes = MFI->getStackSize();
1642 BuildMI(BB, PPC32::LWZ, 2, TmpReg1).addImm(NumBytes+8)
1645 // Values other than zero are not implemented yet.
1646 BuildMI(BB, PPC32::LI, 1, TmpReg1).addImm(0);
1650 case Intrinsic::frameaddress:
1651 TmpReg1 = getReg(CI);
1652 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1653 BuildMI(BB, PPC32::OR, 2, TmpReg1).addReg(PPC32::R1).addReg(PPC32::R1);
1655 // Values other than zero are not implemented yet.
1656 BuildMI(BB, PPC32::LI, 1, TmpReg1).addImm(0);
1661 // This may be useful for supporting isunordered
1662 case Intrinsic::isnan:
1663 // If this is only used by 'isunordered' style comparisons, don't emit it.
1664 if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1665 TmpReg1 = getReg(CI.getOperand(1));
1666 emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1667 TmpReg2 = makeAnotherReg(Type::IntTy);
1668 BuildMI(BB, PPC32::MFCR, TmpReg2);
1669 TmpReg3 = getReg(CI);
1670 BuildMI(BB, PPC32::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1674 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1678 /// visitSimpleBinary - Implement simple binary operators for integral types...
1679 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1682 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1683 unsigned DestReg = getReg(B);
1684 MachineBasicBlock::iterator MI = BB->end();
1685 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1686 unsigned Class = getClassB(B.getType());
1688 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1691 /// emitBinaryFPOperation - This method handles emission of floating point
1692 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1693 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1694 MachineBasicBlock::iterator IP,
1695 Value *Op0, Value *Op1,
1696 unsigned OperatorClass, unsigned DestReg) {
1698 // Special case: op Reg, <const fp>
1699 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1700 // Create a constant pool entry for this constant.
1701 MachineConstantPool *CP = F->getConstantPool();
1702 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1703 const Type *Ty = Op1->getType();
1704 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1706 static const unsigned OpcodeTab[][4] = {
1707 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1708 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1711 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1712 unsigned Op1Reg = getReg(Op1C, BB, IP);
1713 unsigned Op0r = getReg(Op0, BB, IP);
1714 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1Reg);
1718 // Special case: R1 = op <const fp>, R2
1719 if (ConstantFP *Op0C = dyn_cast<ConstantFP>(Op0))
1720 if (Op0C->isExactlyValue(-0.0) && OperatorClass == 1) {
1722 unsigned op1Reg = getReg(Op1, BB, IP);
1723 BuildMI(*BB, IP, PPC32::FNEG, 1, DestReg).addReg(op1Reg);
1726 // R1 = op CST, R2 --> R1 = opr R2, CST
1728 // Create a constant pool entry for this constant.
1729 MachineConstantPool *CP = F->getConstantPool();
1730 unsigned CPI = CP->getConstantPoolIndex(Op0C);
1731 const Type *Ty = Op0C->getType();
1732 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1734 static const unsigned OpcodeTab[][4] = {
1735 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1736 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1739 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1740 unsigned Op0Reg = getReg(Op0C, BB, IP);
1741 unsigned Op1Reg = getReg(Op1, BB, IP);
1742 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1747 static const unsigned OpcodeTab[] = {
1748 PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV
1751 unsigned Opcode = OpcodeTab[OperatorClass];
1752 unsigned Op0r = getReg(Op0, BB, IP);
1753 unsigned Op1r = getReg(Op1, BB, IP);
1754 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1757 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1758 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1761 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1762 /// and constant expression support.
1764 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1765 MachineBasicBlock::iterator IP,
1766 Value *Op0, Value *Op1,
1767 unsigned OperatorClass, unsigned DestReg) {
1768 unsigned Class = getClassB(Op0->getType());
1770 // Arithmetic and Bitwise operators
1771 static const unsigned OpcodeTab[] = {
1772 PPC32::ADD, PPC32::SUB, PPC32::AND, PPC32::OR, PPC32::XOR
1774 // Otherwise, code generate the full operation with a constant.
1775 static const unsigned BottomTab[] = {
1776 PPC32::ADDC, PPC32::SUBC, PPC32::AND, PPC32::OR, PPC32::XOR
1778 static const unsigned TopTab[] = {
1779 PPC32::ADDE, PPC32::SUBFE, PPC32::AND, PPC32::OR, PPC32::XOR
1782 if (Class == cFP32 || Class == cFP64) {
1783 assert(OperatorClass < 2 && "No logical ops for FP!");
1784 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1788 if (Op0->getType() == Type::BoolTy) {
1789 if (OperatorClass == 3)
1790 // If this is an or of two isnan's, emit an FP comparison directly instead
1791 // of or'ing two isnan's together.
1792 if (Value *LHS = dyncastIsNan(Op0))
1793 if (Value *RHS = dyncastIsNan(Op1)) {
1794 unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1795 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1796 emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1797 BuildMI(*MBB, IP, PPC32::MFCR, TmpReg);
1798 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1799 .addImm(31).addImm(31);
1804 // sub 0, X -> neg X
1805 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
1806 if (OperatorClass == 1 && CI->isNullValue()) {
1807 unsigned op1Reg = getReg(Op1, MBB, IP);
1808 BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg).addReg(op1Reg);
1810 if (Class == cLong) {
1811 unsigned zeroes = makeAnotherReg(Type::IntTy);
1812 unsigned overflow = makeAnotherReg(Type::IntTy);
1813 unsigned T = makeAnotherReg(Type::IntTy);
1814 BuildMI(*MBB, IP, PPC32::CNTLZW, 1, zeroes).addReg(op1Reg);
1815 BuildMI(*MBB, IP, PPC32::RLWINM, 4, overflow).addReg(zeroes).addImm(27)
1816 .addImm(5).addImm(31);
1817 BuildMI(*MBB, IP, PPC32::ADD, 2, T).addReg(op1Reg+1).addReg(overflow);
1818 BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg+1).addReg(T);
1823 // Special case: op Reg, <const int>
1824 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1825 unsigned Op0r = getReg(Op0, MBB, IP);
1827 // xor X, -1 -> not X
1828 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1829 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1830 if (Class == cLong) // Invert the top part too
1831 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg+1).addReg(Op0r+1)
1836 unsigned Opcode = OpcodeTab[OperatorClass];
1837 unsigned Op1r = getReg(Op1, MBB, IP);
1839 if (Class != cLong) {
1840 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1844 // If the constant is zero in the low 32-bits, just copy the low part
1845 // across and apply the normal 32-bit operation to the high parts. There
1846 // will be no carry or borrow into the top.
1847 if (cast<ConstantInt>(Op1C)->getRawValue() == 0) {
1848 if (OperatorClass != 2) // All but and...
1849 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1851 BuildMI(*MBB, IP, PPC32::LI, 1, DestReg).addImm(0);
1852 BuildMI(*MBB, IP, Opcode, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1856 // If this is a long value and the high or low bits have a special
1857 // property, emit some special cases.
1858 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
1860 // If this is a logical operation and the top 32-bits are zero, just
1861 // operate on the lower 32.
1862 if (Op1h == 0 && OperatorClass > 1) {
1863 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1864 if (OperatorClass != 2) // All but and
1865 BuildMI(*MBB, IP, PPC32::OR, 2,DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
1867 BuildMI(*MBB, IP, PPC32::LI, 1,DestReg+1).addImm(0);
1871 // TODO: We could handle lots of other special cases here, such as AND'ing
1872 // with 0xFFFFFFFF00000000 -> noop, etc.
1874 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1876 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1881 unsigned Op0r = getReg(Op0, MBB, IP);
1882 unsigned Op1r = getReg(Op1, MBB, IP);
1884 if (Class != cLong) {
1885 unsigned Opcode = OpcodeTab[OperatorClass];
1886 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1888 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1890 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1896 /// doMultiply - Emit appropriate instructions to multiply together the
1897 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1898 /// result should be given as DestTy.
1900 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1901 unsigned DestReg, const Type *DestTy,
1902 unsigned op0Reg, unsigned op1Reg) {
1903 unsigned Class = getClass(DestTy);
1906 BuildMI(*MBB, MBBI, PPC32::MULHW, 2, DestReg+1).addReg(op0Reg+1)
1911 BuildMI(*MBB, MBBI, PPC32::MULLW, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1914 assert(0 && "doMultiply cannot operate on unknown type!");
1918 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1919 // returns zero when the input is not exactly a power of two.
1920 static unsigned ExactLog2(unsigned Val) {
1921 if (Val == 0 || (Val & (Val-1))) return 0;
1931 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
1932 /// 16, or 32-bit integer multiply by a constant.
1934 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1935 MachineBasicBlock::iterator IP,
1936 unsigned DestReg, const Type *DestTy,
1937 unsigned op0Reg, unsigned ConstRHS) {
1938 unsigned Class = getClass(DestTy);
1939 // Handle special cases here.
1942 BuildMI(*MBB, IP, PPC32::LI, 1, DestReg).addImm(0);
1945 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(op0Reg).addReg(op0Reg);
1948 BuildMI(*MBB, IP, PPC32::ADD, 2,DestReg).addReg(op0Reg).addReg(op0Reg);
1952 // If the element size is exactly a power of 2, use a shift to get it.
1953 if (unsigned Shift = ExactLog2(ConstRHS)) {
1955 default: assert(0 && "Unknown class for this function!");
1959 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(op0Reg)
1960 .addImm(Shift-1).addImm(0).addImm(31-Shift+1);
1965 // Most general case, emit a normal multiply...
1966 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1967 Constant *C = ConstantUInt::get(Type::UIntTy, ConstRHS);
1969 copyConstantToRegister(MBB, IP, C, TmpReg);
1970 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1973 void ISel::visitMul(BinaryOperator &I) {
1974 unsigned ResultReg = getReg(I);
1976 Value *Op0 = I.getOperand(0);
1977 Value *Op1 = I.getOperand(1);
1979 MachineBasicBlock::iterator IP = BB->end();
1980 emitMultiply(BB, IP, Op0, Op1, ResultReg);
1983 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
1984 Value *Op0, Value *Op1, unsigned DestReg) {
1985 MachineBasicBlock &BB = *MBB;
1986 TypeClass Class = getClass(Op0->getType());
1988 // Simple scalar multiply?
1989 unsigned Op0Reg = getReg(Op0, &BB, IP);
1994 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1995 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
1996 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
1998 unsigned Op1Reg = getReg(Op1, &BB, IP);
1999 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
2004 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2010 // Long value. We have to do things the hard way...
2011 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2012 unsigned CLow = CI->getRawValue();
2013 unsigned CHi = CI->getRawValue() >> 32;
2016 // If the low part of the constant is all zeros, things are simple.
2017 BuildMI(BB, IP, PPC32::LI, 1, DestReg).addImm(0);
2018 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2022 // Multiply the two low parts
2023 unsigned OverflowReg = 0;
2025 BuildMI(BB, IP, PPC32::OR, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
2027 unsigned TmpRegL = makeAnotherReg(Type::UIntTy);
2028 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2029 OverflowReg = makeAnotherReg(Type::UIntTy);
2030 BuildMI(BB, IP, PPC32::LIS, 1, TmpRegL).addImm(CLow >> 16);
2031 BuildMI(BB, IP, PPC32::ORI, 2, Op1RegL).addReg(TmpRegL).addImm(CLow);
2032 BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1RegL);
2033 BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg)
2037 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
2038 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2040 unsigned AHBLplusOverflowReg;
2042 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2043 BuildMI(BB, IP, PPC32::ADD, 2,
2044 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2046 AHBLplusOverflowReg = AHBLReg;
2050 BuildMI(BB, IP, PPC32::OR, 2, DestReg+1).addReg(AHBLplusOverflowReg)
2051 .addReg(AHBLplusOverflowReg);
2053 unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
2054 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
2056 BuildMI(BB, IP, PPC32::ADD, 2,
2057 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2062 // General 64x64 multiply
2064 unsigned Op1Reg = getReg(Op1, &BB, IP);
2066 // Multiply the two low parts...
2067 BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
2069 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2070 BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg).addReg(Op1Reg);
2072 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
2073 BuildMI(BB, IP, PPC32::MULLW, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2075 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2076 BuildMI(BB, IP, PPC32::ADD, 2, AHBLplusOverflowReg).addReg(AHBLReg)
2077 .addReg(OverflowReg);
2079 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2080 BuildMI(BB, IP, PPC32::MULLW, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2082 BuildMI(BB, IP, PPC32::ADD, 2,
2083 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2087 /// visitDivRem - Handle division and remainder instructions... these
2088 /// instruction both require the same instructions to be generated, they just
2089 /// select the result from a different register. Note that both of these
2090 /// instructions work differently for signed and unsigned operands.
2092 void ISel::visitDivRem(BinaryOperator &I) {
2093 unsigned ResultReg = getReg(I);
2094 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2096 MachineBasicBlock::iterator IP = BB->end();
2097 emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
2101 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2102 MachineBasicBlock::iterator IP,
2103 Value *Op0, Value *Op1, bool isDiv,
2104 unsigned ResultReg) {
2105 const Type *Ty = Op0->getType();
2106 unsigned Class = getClass(Ty);
2110 // Floating point divide...
2111 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2114 // Floating point remainder via fmodf(float x, float y);
2115 unsigned Op0Reg = getReg(Op0, BB, IP);
2116 unsigned Op1Reg = getReg(Op1, BB, IP);
2117 MachineInstr *TheCall =
2118 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(fmodfFn, true);
2119 std::vector<ValueRecord> Args;
2120 Args.push_back(ValueRecord(Op0Reg, Type::FloatTy));
2121 Args.push_back(ValueRecord(Op1Reg, Type::FloatTy));
2122 doCall(ValueRecord(ResultReg, Type::FloatTy), TheCall, Args, false);
2127 // Floating point divide...
2128 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2131 // Floating point remainder via fmod(double x, double y);
2132 unsigned Op0Reg = getReg(Op0, BB, IP);
2133 unsigned Op1Reg = getReg(Op1, BB, IP);
2134 MachineInstr *TheCall =
2135 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2136 std::vector<ValueRecord> Args;
2137 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2138 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2139 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2143 static Function* const Funcs[] =
2144 { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2145 unsigned Op0Reg = getReg(Op0, BB, IP);
2146 unsigned Op1Reg = getReg(Op1, BB, IP);
2147 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2148 MachineInstr *TheCall =
2149 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2151 std::vector<ValueRecord> Args;
2152 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2153 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2154 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2157 case cByte: case cShort: case cInt:
2158 break; // Small integrals, handled below...
2159 default: assert(0 && "Unknown class!");
2162 // Special case signed division by power of 2.
2164 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2165 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2166 int V = CI->getValue();
2168 if (V == 1) { // X /s 1 => X
2169 unsigned Op0Reg = getReg(Op0, BB, IP);
2170 BuildMI(*BB, IP, PPC32::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2174 if (V == -1) { // X /s -1 => -X
2175 unsigned Op0Reg = getReg(Op0, BB, IP);
2176 BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(Op0Reg);
2180 unsigned log2V = ExactLog2(V);
2181 if (log2V != 0 && Ty->isSigned()) {
2182 unsigned Op0Reg = getReg(Op0, BB, IP);
2183 unsigned TmpReg = makeAnotherReg(Op0->getType());
2185 BuildMI(*BB, IP, PPC32::SRAWI, 2, TmpReg).addReg(Op0Reg)
2187 BuildMI(*BB, IP, PPC32::ADDZE, 1, ResultReg).addReg(TmpReg);
2192 unsigned Op0Reg = getReg(Op0, BB, IP);
2193 unsigned Op1Reg = getReg(Op1, BB, IP);
2194 unsigned Opcode = Ty->isSigned() ? PPC32::DIVW : PPC32::DIVWU;
2197 BuildMI(*BB, IP, Opcode, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2198 } else { // Remainder
2199 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2200 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2202 BuildMI(*BB, IP, Opcode, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2203 BuildMI(*BB, IP, PPC32::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2204 BuildMI(*BB, IP, PPC32::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2209 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2210 /// for constant immediate shift values, and for constant immediate
2211 /// shift values equal to 1. Even the general case is sort of special,
2212 /// because the shift amount has to be in CL, not just any old register.
2214 void ISel::visitShiftInst(ShiftInst &I) {
2215 MachineBasicBlock::iterator IP = BB->end ();
2216 emitShiftOperation(BB, IP, I.getOperand (0), I.getOperand (1),
2217 I.getOpcode () == Instruction::Shl, I.getType (),
2221 /// emitShiftOperation - Common code shared between visitShiftInst and
2222 /// constant expression support.
2224 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2225 MachineBasicBlock::iterator IP,
2226 Value *Op, Value *ShiftAmount, bool isLeftShift,
2227 const Type *ResultTy, unsigned DestReg) {
2228 unsigned SrcReg = getReg (Op, MBB, IP);
2229 bool isSigned = ResultTy->isSigned ();
2230 unsigned Class = getClass (ResultTy);
2232 // Longs, as usual, are handled specially...
2233 if (Class == cLong) {
2234 // If we have a constant shift, we can generate much more efficient code
2235 // than otherwise...
2237 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2238 unsigned Amount = CUI->getValue();
2241 // FIXME: RLWIMI is a use-and-def of DestReg+1, but that violates SSA
2242 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2243 .addImm(Amount).addImm(0).addImm(31-Amount);
2244 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg+1).addReg(SrcReg)
2245 .addImm(Amount).addImm(32-Amount).addImm(31);
2246 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2247 .addImm(Amount).addImm(0).addImm(31-Amount);
2249 // FIXME: RLWIMI is a use-and-def of DestReg, but that violates SSA
2250 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2251 .addImm(32-Amount).addImm(Amount).addImm(31);
2252 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg).addReg(SrcReg+1)
2253 .addImm(32-Amount).addImm(0).addImm(Amount-1);
2254 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2255 .addImm(32-Amount).addImm(Amount).addImm(31);
2257 } else { // Shifting more than 32 bits
2261 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg)
2262 .addImm(Amount).addImm(0).addImm(31-Amount);
2264 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg)
2267 BuildMI(*MBB, IP, PPC32::LI, 1, DestReg).addImm(0);
2271 BuildMI(*MBB, IP, PPC32::SRAWI, 2, DestReg).addReg(SrcReg+1)
2274 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg+1)
2275 .addImm(32-Amount).addImm(Amount).addImm(31);
2277 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg+1)
2280 BuildMI(*MBB, IP,PPC32::LI,1,DestReg+1).addImm(0);
2284 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2285 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2286 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2287 unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2288 unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2289 unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2290 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2293 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2295 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(SrcReg+1)
2296 .addReg(ShiftAmountReg);
2297 BuildMI(*MBB, IP, PPC32::SRW, 2,TmpReg3).addReg(SrcReg).addReg(TmpReg1);
2298 BuildMI(*MBB, IP, PPC32::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2299 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2301 BuildMI(*MBB, IP, PPC32::SLW, 2,TmpReg6).addReg(SrcReg).addReg(TmpReg5);
2302 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TmpReg4)
2304 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2305 .addReg(ShiftAmountReg);
2308 // FIXME: Unimplemented
2309 // Page C-3 of the PowerPC 32bit Programming Environments Manual
2310 std::cerr << "Unimplemented: signed right shift\n";
2313 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2315 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg2).addReg(SrcReg)
2316 .addReg(ShiftAmountReg);
2317 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg3).addReg(SrcReg+1)
2319 BuildMI(*MBB, IP, PPC32::OR, 2, TmpReg4).addReg(TmpReg2)
2321 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2323 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg6).addReg(SrcReg+1)
2325 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TmpReg4)
2327 BuildMI(*MBB, IP, PPC32::SRW, 2, DestReg+1).addReg(SrcReg+1)
2328 .addReg(ShiftAmountReg);
2335 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2336 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2337 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2338 unsigned Amount = CUI->getValue();
2341 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2342 .addImm(Amount).addImm(0).addImm(31-Amount);
2345 BuildMI(*MBB, IP, PPC32::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2347 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2348 .addImm(32-Amount).addImm(Amount).addImm(31);
2351 } else { // The shift amount is non-constant.
2352 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2355 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2356 .addReg(ShiftAmountReg);
2358 BuildMI(*MBB, IP, isSigned ? PPC32::SRAW : PPC32::SRW, 2, DestReg)
2359 .addReg(SrcReg).addReg(ShiftAmountReg);
2365 /// visitLoadInst - Implement LLVM load instructions
2367 void ISel::visitLoadInst(LoadInst &I) {
2368 static const unsigned Opcodes[] = {
2369 PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS
2371 unsigned Class = getClassB(I.getType());
2372 unsigned Opcode = Opcodes[Class];
2373 if (I.getType() == Type::DoubleTy) Opcode = PPC32::LFD;
2375 unsigned DestReg = getReg(I);
2377 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
2378 unsigned FI = getFixedSizedAllocaFI(AI);
2379 if (Class == cLong) {
2380 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg), FI);
2381 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg+1), FI, 4);
2383 addFrameReference(BuildMI(BB, Opcode, 2, DestReg), FI);
2386 unsigned SrcAddrReg = getReg(I.getOperand(0));
2388 if (Class == cLong) {
2389 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2390 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(SrcAddrReg);
2392 BuildMI(BB, Opcode, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2397 /// visitStoreInst - Implement LLVM store instructions
2399 void ISel::visitStoreInst(StoreInst &I) {
2400 unsigned ValReg = getReg(I.getOperand(0));
2401 unsigned AddressReg = getReg(I.getOperand(1));
2403 const Type *ValTy = I.getOperand(0)->getType();
2404 unsigned Class = getClassB(ValTy);
2406 if (Class == cLong) {
2407 BuildMI(BB, PPC32::STW, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2408 BuildMI(BB, PPC32::STW, 3).addReg(ValReg+1).addImm(4).addReg(AddressReg);
2412 static const unsigned Opcodes[] = {
2413 PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS
2415 unsigned Opcode = Opcodes[Class];
2416 if (ValTy == Type::DoubleTy) Opcode = PPC32::STFD;
2417 BuildMI(BB, Opcode, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2421 /// visitCastInst - Here we have various kinds of copying with or without sign
2422 /// extension going on.
2424 void ISel::visitCastInst(CastInst &CI) {
2425 Value *Op = CI.getOperand(0);
2427 unsigned SrcClass = getClassB(Op->getType());
2428 unsigned DestClass = getClassB(CI.getType());
2429 // Noop casts are not emitted: getReg will return the source operand as the
2430 // register to use for any uses of the noop cast.
2431 if (DestClass == SrcClass)
2434 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2435 // of the case are GEP instructions, then the cast does not need to be
2436 // generated explicitly, it will be folded into the GEP.
2437 if (DestClass == cLong && SrcClass == cInt) {
2438 bool AllUsesAreGEPs = true;
2439 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2440 if (!isa<GetElementPtrInst>(*I)) {
2441 AllUsesAreGEPs = false;
2445 // No need to codegen this cast if all users are getelementptr instrs...
2446 if (AllUsesAreGEPs) return;
2449 unsigned DestReg = getReg(CI);
2450 MachineBasicBlock::iterator MI = BB->end();
2451 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2454 /// emitCastOperation - Common code shared between visitCastInst and constant
2455 /// expression cast support.
2457 void ISel::emitCastOperation(MachineBasicBlock *MBB,
2458 MachineBasicBlock::iterator IP,
2459 Value *Src, const Type *DestTy,
2461 const Type *SrcTy = Src->getType();
2462 unsigned SrcClass = getClassB(SrcTy);
2463 unsigned DestClass = getClassB(DestTy);
2464 unsigned SrcReg = getReg(Src, MBB, IP);
2466 // Implement casts to bool by using compare on the operand followed by set if
2467 // not zero on the result.
2468 if (DestTy == Type::BoolTy) {
2473 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2474 BuildMI(*MBB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg).addImm(-1);
2475 BuildMI(*MBB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2479 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2480 unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
2481 BuildMI(*MBB, IP, PPC32::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
2482 BuildMI(*MBB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg2).addImm(-1);
2483 BuildMI(*MBB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg)
2490 std::cerr << "Cast fp-to-bool not implemented!";
2496 // Implement casts between values of the same type class (as determined by
2497 // getClass) by using a register-to-register move.
2498 if (SrcClass == DestClass) {
2499 if (SrcClass <= cInt) {
2500 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2501 } else if (SrcClass == cFP32 || SrcClass == cFP64) {
2502 BuildMI(*MBB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2503 } else if (SrcClass == cLong) {
2504 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2505 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg+1)
2508 assert(0 && "Cannot handle this type of cast instruction!");
2514 // Handle cast of Float -> Double
2515 if (SrcClass == cFP32 && DestClass == cFP64) {
2516 BuildMI(*MBB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2520 // Handle cast of Double -> Float
2521 if (SrcClass == cFP64 && DestClass == cFP32) {
2522 BuildMI(*MBB, IP, PPC32::FRSP, 1, DestReg).addReg(SrcReg);
2526 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2527 // or zero extension, depending on whether the source type was signed.
2528 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2529 SrcClass < DestClass) {
2530 bool isLong = DestClass == cLong;
2531 if (isLong) DestClass = cInt;
2533 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2534 if (SrcClass < cInt) {
2536 unsigned shift = (SrcClass == cByte) ? 24 : 16;
2537 BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2538 .addImm(shift).addImm(31);
2540 BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH,
2541 1, DestReg).addReg(SrcReg);
2544 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2547 if (isLong) { // Handle upper 32 bits as appropriate...
2548 if (isUnsigned) // Zero out top bits...
2549 BuildMI(*BB, IP, PPC32::LI, 1, DestReg+1).addImm(0);
2550 else // Sign extend bottom half...
2551 BuildMI(*BB, IP, PPC32::SRAWI, 2, DestReg+1).addReg(DestReg).addImm(31);
2556 // Special case long -> int ...
2557 if (SrcClass == cLong && DestClass == cInt) {
2558 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2562 // Handle cast of LARGER int to SMALLER int with a clear or sign extend
2563 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2564 && SrcClass > DestClass) {
2565 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2567 unsigned shift = (SrcClass == cByte) ? 24 : 16;
2568 BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2569 .addImm(shift).addImm(31);
2571 BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH, 1,
2572 DestReg).addReg(SrcReg);
2577 // Handle casts from integer to floating point now...
2578 if (DestClass == cFP32 || DestClass == cFP64) {
2580 // Emit a library call for long to float conversion
2581 if (SrcClass == cLong) {
2582 std::vector<ValueRecord> Args;
2583 Args.push_back(ValueRecord(SrcReg, SrcTy));
2584 Function *floatFn = (DestClass == cFP32) ? __floatdisfFn : __floatdidfFn;
2585 MachineInstr *TheCall =
2586 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2587 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2591 // Make sure we're dealing with a full 32 bits
2592 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2593 promote32(TmpReg, ValueRecord(SrcReg, SrcTy));
2597 // Spill the integer to memory and reload it from there.
2598 // Also spill room for a special conversion constant
2599 int ConstantFrameIndex =
2600 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2602 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2604 unsigned constantHi = makeAnotherReg(Type::IntTy);
2605 unsigned constantLo = makeAnotherReg(Type::IntTy);
2606 unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2607 unsigned TempF = makeAnotherReg(Type::DoubleTy);
2609 if (!SrcTy->isSigned()) {
2610 BuildMI(*BB, IP, PPC32::LIS, 1, constantHi).addImm(0x4330);
2611 BuildMI(*BB, IP, PPC32::LI, 1, constantLo).addImm(0);
2612 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2613 ConstantFrameIndex);
2614 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2615 ConstantFrameIndex, 4);
2616 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2618 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(SrcReg),
2620 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF),
2621 ConstantFrameIndex);
2622 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2623 BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2625 unsigned TempLo = makeAnotherReg(Type::IntTy);
2626 BuildMI(*BB, IP, PPC32::LIS, 1, constantHi).addImm(0x4330);
2627 BuildMI(*BB, IP, PPC32::LIS, 1, constantLo).addImm(0x8000);
2628 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2629 ConstantFrameIndex);
2630 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2631 ConstantFrameIndex, 4);
2632 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2634 BuildMI(*BB, IP, PPC32::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2635 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(TempLo),
2637 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF),
2638 ConstantFrameIndex);
2639 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2640 BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF ).addReg(ConstF);
2645 // Handle casts from floating point to integer now...
2646 if (SrcClass == cFP32 || SrcClass == cFP64) {
2647 // emit library call
2648 if (DestClass == cLong) {
2649 std::vector<ValueRecord> Args;
2650 Args.push_back(ValueRecord(SrcReg, SrcTy));
2651 Function *floatFn = (DestClass == cFP32) ? __fixsfdiFn : __fixdfdiFn;
2652 MachineInstr *TheCall =
2653 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2654 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2659 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2661 if (DestTy->isSigned()) {
2662 unsigned LoadOp = (DestClass == cShort) ? PPC32::LHA : PPC32::LWZ;
2663 unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2665 // Convert to integer in the FP reg and store it to a stack slot
2666 BuildMI(*BB, IP, PPC32::FCTIWZ, 1, TempReg).addReg(SrcReg);
2667 addFrameReference(BuildMI(*BB, IP, PPC32::STFD, 3)
2668 .addReg(TempReg), ValueFrameIdx);
2670 // There is no load signed byte opcode, so we must emit a sign extend
2671 if (DestClass == cByte) {
2672 unsigned TempReg2 = makeAnotherReg(DestTy);
2673 addFrameReference(BuildMI(*BB, IP, LoadOp, 2, TempReg2),
2675 BuildMI(*MBB, IP, PPC32::EXTSB, DestReg).addReg(TempReg2);
2677 addFrameReference(BuildMI(*BB, IP, LoadOp, 2, DestReg),
2681 std::cerr << "Cast fp-to-unsigned not implemented!";
2687 // Anything we haven't handled already, we can't (yet) handle at all.
2688 assert(0 && "Unhandled cast instruction!");
2692 /// visitVANextInst - Implement the va_next instruction...
2694 void ISel::visitVANextInst(VANextInst &I) {
2695 unsigned VAList = getReg(I.getOperand(0));
2696 unsigned DestReg = getReg(I);
2699 switch (I.getArgType()->getTypeID()) {
2702 assert(0 && "Error: bad type for va_next instruction!");
2704 case Type::PointerTyID:
2705 case Type::UIntTyID:
2709 case Type::ULongTyID:
2710 case Type::LongTyID:
2711 case Type::DoubleTyID:
2716 // Increment the VAList pointer...
2717 BuildMI(BB, PPC32::ADDI, 2, DestReg).addReg(VAList).addImm(Size);
2720 void ISel::visitVAArgInst(VAArgInst &I) {
2721 unsigned VAList = getReg(I.getOperand(0));
2722 unsigned DestReg = getReg(I);
2724 switch (I.getType()->getTypeID()) {
2727 assert(0 && "Error: bad type for va_next instruction!");
2729 case Type::PointerTyID:
2730 case Type::UIntTyID:
2732 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2734 case Type::ULongTyID:
2735 case Type::LongTyID:
2736 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2737 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(VAList);
2739 case Type::DoubleTyID:
2740 BuildMI(BB, PPC32::LFD, 2, DestReg).addImm(0).addReg(VAList);
2745 /// visitGetElementPtrInst - instruction-select GEP instructions
2747 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2748 unsigned outputReg = getReg(I);
2749 emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(),
2753 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2754 MachineBasicBlock::iterator IP,
2755 Value *Src, User::op_iterator IdxBegin,
2756 User::op_iterator IdxEnd, unsigned TargetReg) {
2757 const TargetData &TD = TM.getTargetData();
2759 std::vector<Value*> GEPOps;
2760 GEPOps.resize(IdxEnd-IdxBegin+1);
2762 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2764 std::vector<const Type*> GEPTypes;
2765 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2766 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2768 // Keep emitting instructions until we consume the entire GEP instruction.
2769 while (!GEPOps.empty()) {
2770 if (GEPTypes.empty()) {
2771 // Load the base pointer into a register.
2772 unsigned Reg = getReg(Src, MBB, IP);
2773 BuildMI(*MBB, IP, PPC32::OR, 2, TargetReg).addReg(Reg).addReg(Reg);
2774 break; // we are now done
2776 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2777 // It's a struct access. CUI is the index into the structure,
2778 // which names the field. This index must have unsigned type.
2779 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2781 // Use the TargetData structure to pick out what the layout of the
2782 // structure is in memory. Since the structure index must be constant, we
2783 // can get its value and use it to find the right byte offset from the
2784 // StructLayout class's list of structure member offsets.
2785 unsigned Disp = TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2786 GEPOps.pop_back(); // Consume a GEP operand
2787 GEPTypes.pop_back();
2788 unsigned Reg = makeAnotherReg(Type::UIntTy);
2789 unsigned DispReg = makeAnotherReg(Type::UIntTy);
2790 BuildMI(*MBB, IP, PPC32::LI, 1, DispReg).addImm(Disp);
2791 BuildMI(*MBB, IP, PPC32::ADD, 2, TargetReg).addReg(Reg).addReg(DispReg);
2792 --IP; // Insert the next instruction before this one.
2793 TargetReg = Reg; // Codegen the rest of the GEP into this
2795 // It's an array or pointer access: [ArraySize x ElementType].
2796 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2797 Value *idx = GEPOps.back();
2798 GEPOps.pop_back(); // Consume a GEP operand
2799 GEPTypes.pop_back();
2801 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
2802 // operand. Handle this case directly now...
2803 if (CastInst *CI = dyn_cast<CastInst>(idx))
2804 if (CI->getOperand(0)->getType() == Type::IntTy ||
2805 CI->getOperand(0)->getType() == Type::UIntTy)
2806 idx = CI->getOperand(0);
2808 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2809 // must find the size of the pointed-to type (Not coincidentally, the next
2810 // type is the type of the elements in the array).
2811 const Type *ElTy = SqTy->getElementType();
2812 unsigned elementSize = TD.getTypeSize(ElTy);
2814 if (idx == Constant::getNullValue(idx->getType())) {
2815 // GEP with idx 0 is a no-op
2816 } else if (elementSize == 1) {
2817 // If the element size is 1, we don't have to multiply, just add
2818 unsigned idxReg = getReg(idx, MBB, IP);
2819 unsigned Reg = makeAnotherReg(Type::UIntTy);
2820 BuildMI(*MBB, IP, PPC32::ADD, 2,TargetReg).addReg(Reg).addReg(idxReg);
2821 --IP; // Insert the next instruction before this one.
2822 TargetReg = Reg; // Codegen the rest of the GEP into this
2824 unsigned idxReg = getReg(idx, MBB, IP);
2825 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2827 // Make sure we can back the iterator up to point to the first
2828 // instruction emitted.
2829 MachineBasicBlock::iterator BeforeIt = IP;
2830 if (IP == MBB->begin())
2831 BeforeIt = MBB->end();
2834 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2836 // Emit an ADD to add OffsetReg to the basePtr.
2837 unsigned Reg = makeAnotherReg(Type::UIntTy);
2838 BuildMI(*MBB, IP, PPC32::ADD,2,TargetReg).addReg(Reg).addReg(OffsetReg);
2840 // Step to the first instruction of the multiply.
2841 if (BeforeIt == MBB->end())
2846 TargetReg = Reg; // Codegen the rest of the GEP into this
2852 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2853 /// frame manager, otherwise do it the hard way.
2855 void ISel::visitAllocaInst(AllocaInst &I) {
2856 // If this is a fixed size alloca in the entry block for the function, we
2857 // statically stack allocate the space, so we don't need to do anything here.
2859 if (dyn_castFixedAlloca(&I)) return;
2861 // Find the data size of the alloca inst's getAllocatedType.
2862 const Type *Ty = I.getAllocatedType();
2863 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2865 // Create a register to hold the temporary result of multiplying the type size
2866 // constant by the variable amount.
2867 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2868 unsigned SrcReg1 = getReg(I.getArraySize());
2870 // TotalSizeReg = mul <numelements>, <TypeSize>
2871 MachineBasicBlock::iterator MBBI = BB->end();
2872 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2874 // AddedSize = add <TotalSizeReg>, 15
2875 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2876 BuildMI(BB, PPC32::ADD, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2878 // AlignedSize = and <AddedSize>, ~15
2879 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2880 BuildMI(BB, PPC32::RLWNM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
2881 .addImm(0).addImm(27);
2883 // Subtract size from stack pointer, thereby allocating some space.
2884 BuildMI(BB, PPC32::SUB, 2, PPC32::R1).addReg(PPC32::R1).addReg(AlignedSize);
2886 // Put a pointer to the space into the result register, by copying
2887 // the stack pointer.
2888 BuildMI(BB, PPC32::OR, 2, getReg(I)).addReg(PPC32::R1).addReg(PPC32::R1);
2890 // Inform the Frame Information that we have just allocated a variable-sized
2892 F->getFrameInfo()->CreateVariableSizedObject();
2895 /// visitMallocInst - Malloc instructions are code generated into direct calls
2896 /// to the library malloc.
2898 void ISel::visitMallocInst(MallocInst &I) {
2899 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2902 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2903 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2905 Arg = makeAnotherReg(Type::UIntTy);
2906 unsigned Op0Reg = getReg(I.getOperand(0));
2907 MachineBasicBlock::iterator MBBI = BB->end();
2908 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2911 std::vector<ValueRecord> Args;
2912 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2913 MachineInstr *TheCall =
2914 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
2915 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
2919 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2922 void ISel::visitFreeInst(FreeInst &I) {
2923 std::vector<ValueRecord> Args;
2924 Args.push_back(ValueRecord(I.getOperand(0)));
2925 MachineInstr *TheCall =
2926 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(freeFn, true);
2927 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
2930 /// createPPC32SimpleInstructionSelector - This pass converts an LLVM function
2931 /// into a machine code representation is a very simple peep-hole fashion. The
2932 /// generated code sucks but the implementation is nice and simple.
2934 FunctionPass *llvm::createPPCSimpleInstructionSelector(TargetMachine &TM) {
2935 return new ISel(TM);