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, cFP, 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
56 case Type::DoubleTyID: return cFP; // Floating Point is #3
59 case Type::ULongTyID: return cLong; // Longs are class #4
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
78 int ReturnAddressIndex; // FrameIndex for the return address
80 std::map<Value*, unsigned> RegMap; // Mapping between Values and SSA Regs
82 // External functions used in the Module
83 Function *fmodFn, *__moddi3Fn, *__divdi3Fn, *__umoddi3Fn, *__udivdi3Fn,
84 *__fixdfdiFn, *__floatdisfFn, *__floatdidfFn, *mallocFn, *freeFn;
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 // double fmod(double, double);
103 fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
104 // long __moddi3(long, long);
105 __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
106 // long __divdi3(long, long);
107 __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
108 // unsigned long __umoddi3(unsigned long, unsigned long);
109 __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
110 // unsigned long __udivdi3(unsigned long, unsigned long);
111 __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
112 // long __fixdfdi(double)
113 __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
114 // float __floatdisf(long)
115 __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
116 // double __floatdidf(long)
117 __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
118 // void* malloc(size_t)
119 mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
121 freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
125 /// runOnFunction - Top level implementation of instruction selection for
126 /// the entire function.
128 bool runOnFunction(Function &Fn) {
129 // First pass over the function, lower any unknown intrinsic functions
130 // with the IntrinsicLowering class.
131 LowerUnknownIntrinsicFunctionCalls(Fn);
133 F = &MachineFunction::construct(&Fn, TM);
135 // Create all of the machine basic blocks for the function...
136 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
137 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
141 // Set up a frame object for the return address. This is used by the
142 // llvm.returnaddress & llvm.frameaddress intrinisics.
143 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
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 this operand is a constant, emit the code to copy the constant into
396 // the register here...
398 if (Constant *C = dyn_cast<Constant>(V)) {
399 unsigned Reg = makeAnotherReg(V->getType());
400 copyConstantToRegister(MBB, IPt, C, Reg);
402 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
403 // GV is located at PC + distance
404 unsigned CurPC = makeAnotherReg(Type::IntTy);
405 unsigned Reg1 = makeAnotherReg(V->getType());
406 unsigned Reg2 = makeAnotherReg(V->getType());
407 // Move PC to destination reg
408 BuildMI(*MBB, IPt, PPC32::MovePCtoLR, 0, CurPC);
409 // Move value at PC + distance into return reg
410 BuildMI(*MBB, IPt, PPC32::LOADHiAddr, 2, Reg1).addReg(CurPC)
411 .addGlobalAddress(GV);
412 BuildMI(*MBB, IPt, PPC32::LOADLoAddr, 2, Reg2).addReg(Reg1)
413 .addGlobalAddress(GV);
415 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
416 // Do not emit noop casts at all.
417 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
418 return getReg(CI->getOperand(0), MBB, IPt);
419 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
420 unsigned Reg = makeAnotherReg(V->getType());
421 unsigned FI = getFixedSizedAllocaFI(AI);
422 addFrameReference(BuildMI(*MBB, IPt, PPC32::ADDI, 2, Reg), FI, 0, false);
426 unsigned &Reg = RegMap[V];
428 Reg = makeAnotherReg(V->getType());
435 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
436 /// that is to be statically allocated with the initial stack frame
438 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
439 // Already computed this?
440 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
441 if (I != AllocaMap.end() && I->first == AI) return I->second;
443 const Type *Ty = AI->getAllocatedType();
444 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
445 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
446 TySize *= CUI->getValue(); // Get total allocated size...
447 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
449 // Create a new stack object using the frame manager...
450 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
451 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
456 /// copyConstantToRegister - Output the instructions required to put the
457 /// specified constant into the specified register.
459 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
460 MachineBasicBlock::iterator IP,
461 Constant *C, unsigned R) {
462 if (C->getType()->isIntegral()) {
463 unsigned Class = getClassB(C->getType());
465 if (Class == cLong) {
466 // Copy the value into the register pair.
467 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
468 unsigned hiTmp = makeAnotherReg(Type::IntTy);
469 unsigned loTmp = makeAnotherReg(Type::IntTy);
470 BuildMI(*MBB, IP, PPC32::ADDIS, 2, loTmp).addReg(PPC32::R0)
472 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(loTmp)
473 .addImm((Val >> 32) & 0xFFFF);
474 BuildMI(*MBB, IP, PPC32::ADDIS, 2, hiTmp).addReg(PPC32::R0)
475 .addImm((Val >> 16) & 0xFFFF);
476 BuildMI(*MBB, IP, PPC32::ORI, 2, R+1).addReg(hiTmp).addImm(Val & 0xFFFF);
480 assert(Class <= cInt && "Type not handled yet!");
482 if (C->getType() == Type::BoolTy) {
483 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0)
484 .addImm(C == ConstantBool::True);
485 } else if (Class == cByte || Class == cShort) {
486 ConstantInt *CI = cast<ConstantInt>(C);
487 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0)
488 .addImm(CI->getRawValue());
490 ConstantInt *CI = cast<ConstantInt>(C);
491 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
492 if (TheVal < 32768 && TheVal >= -32768) {
493 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0)
494 .addImm(CI->getRawValue());
496 unsigned TmpReg = makeAnotherReg(Type::IntTy);
497 BuildMI(*MBB, IP, PPC32::ADDIS, 2, TmpReg).addReg(PPC32::R0)
498 .addImm(CI->getRawValue() >> 16);
499 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(TmpReg)
500 .addImm(CI->getRawValue() & 0xFFFF);
503 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
504 // We need to spill the constant to memory...
505 MachineConstantPool *CP = F->getConstantPool();
506 unsigned CPI = CP->getConstantPoolIndex(CFP);
507 const Type *Ty = CFP->getType();
509 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
511 // Load addr of constant to reg; constant is located at PC + distance
512 unsigned CurPC = makeAnotherReg(Type::IntTy);
513 unsigned Reg1 = makeAnotherReg(Type::IntTy);
514 unsigned Reg2 = makeAnotherReg(Type::IntTy);
515 // Move PC to destination reg
516 BuildMI(*MBB, IP, PPC32::MovePCtoLR, 0, CurPC);
517 // Move value at PC + distance into return reg
518 BuildMI(*MBB, IP, PPC32::LOADHiAddr, 2, Reg1).addReg(CurPC)
519 .addConstantPoolIndex(CPI);
520 BuildMI(*MBB, IP, PPC32::LOADLoAddr, 2, Reg2).addReg(Reg1)
521 .addConstantPoolIndex(CPI);
523 unsigned LoadOpcode = (Ty == Type::FloatTy) ? PPC32::LFS : PPC32::LFD;
524 BuildMI(*MBB, IP, LoadOpcode, 2, R).addImm(0).addReg(Reg2);
525 } else if (isa<ConstantPointerNull>(C)) {
526 // Copy zero (null pointer) to the register.
527 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0).addImm(0);
528 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
529 BuildMI(*MBB, IP, PPC32::ADDIS, 2, R).addReg(PPC32::R0)
530 .addGlobalAddress(CPR->getValue());
531 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(PPC32::R0)
532 .addGlobalAddress(CPR->getValue());
534 std::cerr << "Offending constant: " << C << "\n";
535 assert(0 && "Type not handled yet!");
539 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
540 /// the stack into virtual registers.
542 /// FIXME: When we can calculate which args are coming in via registers
543 /// source them from there instead.
544 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
545 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
546 unsigned GPR_remaining = 8;
547 unsigned FPR_remaining = 13;
548 unsigned GPR_idx = 0, FPR_idx = 0;
549 static const unsigned GPR[] = {
550 PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
551 PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
553 static const unsigned FPR[] = {
554 PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6, PPC32::F7,
555 PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12, PPC32::F13
558 MachineFrameInfo *MFI = F->getFrameInfo();
560 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
561 bool ArgLive = !I->use_empty();
562 unsigned Reg = ArgLive ? getReg(*I) : 0;
563 int FI; // Frame object index
565 switch (getClassB(I->getType())) {
568 FI = MFI->CreateFixedObject(1, ArgOffset);
569 if (GPR_remaining > 0) {
570 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
571 .addReg(GPR[GPR_idx]);
573 addFrameReference(BuildMI(BB, PPC32::LBZ, 2, Reg), FI);
579 FI = MFI->CreateFixedObject(2, ArgOffset);
580 if (GPR_remaining > 0) {
581 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
582 .addReg(GPR[GPR_idx]);
584 addFrameReference(BuildMI(BB, PPC32::LHZ, 2, Reg), FI);
590 FI = MFI->CreateFixedObject(4, ArgOffset);
591 if (GPR_remaining > 0) {
592 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
593 .addReg(GPR[GPR_idx]);
595 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
601 FI = MFI->CreateFixedObject(8, ArgOffset);
602 if (GPR_remaining > 1) {
603 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
604 .addReg(GPR[GPR_idx]);
605 BuildMI(BB, PPC32::OR, 2, Reg+1).addReg(GPR[GPR_idx+1])
606 .addReg(GPR[GPR_idx+1]);
608 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
609 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg+1), FI, 4);
612 ArgOffset += 4; // longs require 4 additional bytes
613 if (GPR_remaining > 1) {
614 GPR_remaining--; // uses up 2 GPRs
621 if (I->getType() == Type::FloatTy) {
623 FI = MFI->CreateFixedObject(4, ArgOffset);
626 FI = MFI->CreateFixedObject(8, ArgOffset);
628 if (FPR_remaining > 0) {
629 BuildMI(BB, PPC32::FMR, 1, Reg).addReg(FPR[FPR_idx]);
633 addFrameReference(BuildMI(BB, Opcode, 2, Reg), FI);
636 if (I->getType() == Type::DoubleTy) {
637 ArgOffset += 4; // doubles require 4 additional bytes
638 if (GPR_remaining > 0) {
639 GPR_remaining--; // uses up 2 GPRs
645 assert(0 && "Unhandled argument type!");
647 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
648 if (GPR_remaining > 0) {
649 GPR_remaining--; // uses up 2 GPRs
654 // If the function takes variable number of arguments, add a frame offset for
655 // the start of the first vararg value... this is used to expand
657 if (Fn.getFunctionType()->isVarArg())
658 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
662 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
663 /// because we have to generate our sources into the source basic blocks, not
666 void ISel::SelectPHINodes() {
667 const TargetInstrInfo &TII = *TM.getInstrInfo();
668 const Function &LF = *F->getFunction(); // The LLVM function...
669 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
670 const BasicBlock *BB = I;
671 MachineBasicBlock &MBB = *MBBMap[I];
673 // Loop over all of the PHI nodes in the LLVM basic block...
674 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
675 for (BasicBlock::const_iterator I = BB->begin();
676 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
678 // Create a new machine instr PHI node, and insert it.
679 unsigned PHIReg = getReg(*PN);
680 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
681 PPC32::PHI, PN->getNumOperands(), PHIReg);
683 MachineInstr *LongPhiMI = 0;
684 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
685 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
686 PPC32::PHI, PN->getNumOperands(), PHIReg+1);
688 // PHIValues - Map of blocks to incoming virtual registers. We use this
689 // so that we only initialize one incoming value for a particular block,
690 // even if the block has multiple entries in the PHI node.
692 std::map<MachineBasicBlock*, unsigned> PHIValues;
694 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
695 MachineBasicBlock *PredMBB = 0;
696 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
697 PE = MBB.pred_end (); PI != PE; ++PI)
698 if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
702 assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
705 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
706 PHIValues.lower_bound(PredMBB);
708 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
709 // We already inserted an initialization of the register for this
710 // predecessor. Recycle it.
711 ValReg = EntryIt->second;
714 // Get the incoming value into a virtual register.
716 Value *Val = PN->getIncomingValue(i);
718 // If this is a constant or GlobalValue, we may have to insert code
719 // into the basic block to compute it into a virtual register.
720 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
721 isa<GlobalValue>(Val)) {
722 // Simple constants get emitted at the end of the basic block,
723 // before any terminator instructions. We "know" that the code to
724 // move a constant into a register will never clobber any flags.
725 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
727 // Because we don't want to clobber any values which might be in
728 // physical registers with the computation of this constant (which
729 // might be arbitrarily complex if it is a constant expression),
730 // just insert the computation at the top of the basic block.
731 MachineBasicBlock::iterator PI = PredMBB->begin();
733 // Skip over any PHI nodes though!
734 while (PI != PredMBB->end() && PI->getOpcode() == PPC32::PHI)
737 ValReg = getReg(Val, PredMBB, PI);
740 // Remember that we inserted a value for this PHI for this predecessor
741 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
744 PhiMI->addRegOperand(ValReg);
745 PhiMI->addMachineBasicBlockOperand(PredMBB);
747 LongPhiMI->addRegOperand(ValReg+1);
748 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
752 // Now that we emitted all of the incoming values for the PHI node, make
753 // sure to reposition the InsertPoint after the PHI that we just added.
754 // This is needed because we might have inserted a constant into this
755 // block, right after the PHI's which is before the old insert point!
756 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
763 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
764 // it into the conditional branch or select instruction which is the only user
765 // of the cc instruction. This is the case if the conditional branch is the
766 // only user of the setcc, and if the setcc is in the same basic block as the
767 // conditional branch. We also don't handle long arguments below, so we reject
768 // them here as well.
770 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
771 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
772 if (SCI->hasOneUse()) {
773 Instruction *User = cast<Instruction>(SCI->use_back());
774 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
775 SCI->getParent() == User->getParent() &&
776 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
777 SCI->getOpcode() == Instruction::SetEQ ||
778 SCI->getOpcode() == Instruction::SetNE))
784 // Return a fixed numbering for setcc instructions which does not depend on the
785 // order of the opcodes.
787 static unsigned getSetCCNumber(unsigned Opcode) {
789 default: assert(0 && "Unknown setcc instruction!");
790 case Instruction::SetEQ: return 0;
791 case Instruction::SetNE: return 1;
792 case Instruction::SetLT: return 2;
793 case Instruction::SetGE: return 3;
794 case Instruction::SetGT: return 4;
795 case Instruction::SetLE: return 5;
799 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
801 default: assert(0 && "Unknown setcc instruction!");
802 case Instruction::SetEQ: return PPC32::BEQ;
803 case Instruction::SetNE: return PPC32::BNE;
804 case Instruction::SetLT: return PPC32::BLT;
805 case Instruction::SetGE: return PPC32::BGE;
806 case Instruction::SetGT: return PPC32::BGT;
807 case Instruction::SetLE: return PPC32::BLE;
811 static unsigned invertPPCBranchOpcode(unsigned Opcode) {
813 default: assert(0 && "Unknown PPC32 branch opcode!");
814 case PPC32::BEQ: return PPC32::BNE;
815 case PPC32::BNE: return PPC32::BEQ;
816 case PPC32::BLT: return PPC32::BGE;
817 case PPC32::BGE: return PPC32::BLT;
818 case PPC32::BGT: return PPC32::BLE;
819 case PPC32::BLE: return PPC32::BGT;
823 /// emitUCOM - emits an unordered FP compare.
824 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
825 unsigned LHS, unsigned RHS) {
826 BuildMI(*MBB, IP, PPC32::FCMPU, 2, PPC32::CR0).addReg(LHS).addReg(RHS);
829 // EmitComparison - This function emits a comparison of the two operands,
830 // returning the extended setcc code to use.
831 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
832 MachineBasicBlock *MBB,
833 MachineBasicBlock::iterator IP) {
834 // The arguments are already supposed to be of the same type.
835 const Type *CompTy = Op0->getType();
836 unsigned Class = getClassB(CompTy);
837 unsigned Op0r = getReg(Op0, MBB, IP);
839 // Special case handling of: cmp R, i
840 if (isa<ConstantPointerNull>(Op1)) {
841 BuildMI(*MBB, IP, PPC32::CMPI, 2, PPC32::CR0).addReg(Op0r).addImm(0);
842 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
843 if (Class == cByte || Class == cShort || Class == cInt) {
844 unsigned Op1v = CI->getRawValue();
846 // Mask off any upper bits of the constant, if there are any...
847 Op1v &= (1ULL << (8 << Class)) - 1;
849 // Compare immediate or promote to reg?
851 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMPI : PPC32::CMPLI, 3,
852 PPC32::CR0).addImm(0).addReg(Op0r).addImm(Op1v);
854 unsigned Op1r = getReg(Op1, MBB, IP);
855 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 3,
856 PPC32::CR0).addImm(0).addReg(Op0r).addReg(Op1r);
860 assert(Class == cLong && "Unknown integer class!");
861 unsigned LowCst = CI->getRawValue();
862 unsigned HiCst = CI->getRawValue() >> 32;
863 if (OpNum < 2) { // seteq, setne
864 unsigned LoTmp = Op0r;
866 unsigned LoLow = makeAnotherReg(Type::IntTy);
867 unsigned LoTmp = makeAnotherReg(Type::IntTy);
868 BuildMI(*MBB, IP, PPC32::XORI, 2, LoLow).addReg(Op0r).addImm(LowCst);
869 BuildMI(*MBB, IP, PPC32::XORIS, 2, LoTmp).addReg(LoLow)
870 .addImm(LowCst >> 16);
872 unsigned HiTmp = Op0r+1;
874 unsigned HiLow = makeAnotherReg(Type::IntTy);
875 unsigned HiTmp = makeAnotherReg(Type::IntTy);
876 BuildMI(*MBB, IP, PPC32::XORI, 2, HiLow).addReg(Op0r+1).addImm(HiCst);
877 BuildMI(*MBB, IP, PPC32::XORIS, 2, HiTmp).addReg(HiLow)
878 .addImm(HiCst >> 16);
880 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
881 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
882 //BuildMI(*MBB, IP, PPC32::CMPLI, 2, PPC32::CR0).addReg(FinalTmp).addImm(0);
885 // FIXME: Not Yet Implemented
886 std::cerr << "EmitComparison unimplemented: Opnum >= 2\n";
893 unsigned Op1r = getReg(Op1, MBB, IP);
895 default: assert(0 && "Unknown type class!");
899 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 2,
900 PPC32::CR0).addReg(Op0r).addReg(Op1r);
904 emitUCOM(MBB, IP, Op0r, Op1r);
908 if (OpNum < 2) { // seteq, setne
909 unsigned LoTmp = makeAnotherReg(Type::IntTy);
910 unsigned HiTmp = makeAnotherReg(Type::IntTy);
911 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
912 BuildMI(*MBB, IP, PPC32::XOR, 2, LoTmp).addReg(Op0r).addReg(Op1r);
913 BuildMI(*MBB, IP, PPC32::XOR, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
914 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
915 //BuildMI(*MBB, IP, PPC32::CMPLI, 2, PPC32::CR0).addReg(FinalTmp).addImm(0);
916 break; // Allow the sete or setne to be generated from flags set by OR
918 // FIXME: Not Yet Implemented
919 std::cerr << "EmitComparison (cLong) unimplemented: Opnum >= 2\n";
927 /// visitSetCondInst - emit code to calculate the condition via
928 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
930 void ISel::visitSetCondInst(SetCondInst &I) {
931 if (canFoldSetCCIntoBranchOrSelect(&I))
934 unsigned Op0Reg = getReg(I.getOperand(0));
935 unsigned Op1Reg = getReg(I.getOperand(1));
936 unsigned DestReg = getReg(I);
937 unsigned OpNum = I.getOpcode();
938 const Type *Ty = I.getOperand (0)->getType();
940 EmitComparison(OpNum, I.getOperand(0), I.getOperand(1), BB, BB->end());
942 unsigned Opcode = getPPCOpcodeForSetCCNumber(OpNum);
943 MachineBasicBlock *thisMBB = BB;
944 const BasicBlock *LLVM_BB = BB->getBasicBlock();
951 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
952 // if we could insert other, non-terminator instructions after the
953 // bCC. But MBB->getFirstTerminator() can't understand this.
954 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
955 F->getBasicBlockList().push_back(copy1MBB);
956 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0).addMBB(copy1MBB);
957 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
958 F->getBasicBlockList().push_back(copy0MBB);
959 BuildMI(BB, PPC32::B, 1).addMBB(copy0MBB);
960 // Update machine-CFG edges
961 BB->addSuccessor(copy1MBB);
962 BB->addSuccessor(copy0MBB);
965 // %FalseValue = li 0
968 unsigned FalseValue = makeAnotherReg(I.getType());
969 BuildMI(BB, PPC32::LI, 1, FalseValue).addZImm(0);
970 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
971 F->getBasicBlockList().push_back(sinkMBB);
972 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
973 // Update machine-CFG edges
974 BB->addSuccessor(sinkMBB);
976 DEBUG(std::cerr << "thisMBB is at " << (void*)thisMBB << "\n");
977 DEBUG(std::cerr << "copy1MBB is at " << (void*)copy1MBB << "\n");
978 DEBUG(std::cerr << "copy0MBB is at " << (void*)copy0MBB << "\n");
979 DEBUG(std::cerr << "sinkMBB is at " << (void*)sinkMBB << "\n");
985 unsigned TrueValue = makeAnotherReg (I.getType ());
986 BuildMI(BB, PPC32::LI, 1, TrueValue).addZImm(1);
987 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
988 // Update machine-CFG edges
989 BB->addSuccessor(sinkMBB);
992 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
995 BuildMI(BB, PPC32::PHI, 4, DestReg).addReg(FalseValue)
996 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
999 void ISel::visitSelectInst(SelectInst &SI) {
1000 unsigned DestReg = getReg(SI);
1001 MachineBasicBlock::iterator MII = BB->end();
1002 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1003 SI.getFalseValue(), DestReg);
1006 /// emitSelect - Common code shared between visitSelectInst and the constant
1007 /// expression support.
1008 /// FIXME: this is most likely broken in one or more ways. Namely, PowerPC has
1009 /// no select instruction. FSEL only works for comparisons against zero.
1010 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1011 MachineBasicBlock::iterator IP,
1012 Value *Cond, Value *TrueVal, Value *FalseVal,
1014 unsigned SelectClass = getClassB(TrueVal->getType());
1016 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1017 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1019 if (TrueReg == FalseReg) {
1020 if (SelectClass == cFP) {
1021 BuildMI(*MBB, IP, PPC32::FMR, 1, DestReg).addReg(TrueReg);
1023 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TrueReg).addReg(TrueReg);
1026 if (SelectClass == cLong)
1027 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TrueReg+1)
1032 unsigned CondReg = getReg(Cond, MBB, IP);
1033 unsigned numZeros = makeAnotherReg(Type::IntTy);
1034 unsigned falseHi = makeAnotherReg(Type::IntTy);
1035 unsigned falseAll = makeAnotherReg(Type::IntTy);
1036 unsigned trueAll = makeAnotherReg(Type::IntTy);
1037 unsigned Temp1 = makeAnotherReg(Type::IntTy);
1038 unsigned Temp2 = makeAnotherReg(Type::IntTy);
1040 BuildMI(*MBB, IP, PPC32::CNTLZW, 1, numZeros).addReg(CondReg);
1041 BuildMI(*MBB, IP, PPC32::RLWINM, 4, falseHi).addReg(numZeros).addImm(26)
1042 .addImm(0).addImm(0);
1043 BuildMI(*MBB, IP, PPC32::SRAWI, 2, falseAll).addReg(falseHi).addImm(31);
1044 BuildMI(*MBB, IP, PPC32::NOR, 2, trueAll).addReg(falseAll).addReg(falseAll);
1045 BuildMI(*MBB, IP, PPC32::AND, 2, Temp1).addReg(TrueReg).addReg(trueAll);
1046 BuildMI(*MBB, IP, PPC32::AND, 2, Temp2).addReg(FalseReg).addReg(falseAll);
1047 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Temp1).addReg(Temp2);
1049 if (SelectClass == cLong) {
1050 unsigned Temp3 = makeAnotherReg(Type::IntTy);
1051 unsigned Temp4 = makeAnotherReg(Type::IntTy);
1052 BuildMI(*MBB, IP, PPC32::AND, 2, Temp3).addReg(TrueReg+1).addReg(trueAll);
1053 BuildMI(*MBB, IP, PPC32::AND, 2, Temp4).addReg(FalseReg+1).addReg(falseAll);
1054 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(Temp3).addReg(Temp4);
1062 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1063 /// operand, in the specified target register.
1065 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1066 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1068 Value *Val = VR.Val;
1069 const Type *Ty = VR.Ty;
1071 if (Constant *C = dyn_cast<Constant>(Val)) {
1072 Val = ConstantExpr::getCast(C, Type::IntTy);
1076 // If this is a simple constant, just emit a load directly to avoid the copy
1077 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1078 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1080 if (TheVal < 32768 && TheVal >= -32768) {
1081 BuildMI(BB, PPC32::ADDI, 2, targetReg).addReg(PPC32::R0).addImm(TheVal);
1083 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1084 BuildMI(BB, PPC32::ADDIS, 2, TmpReg).addReg(PPC32::R0)
1085 .addImm(TheVal >> 16);
1086 BuildMI(BB, PPC32::ORI, 2, targetReg).addReg(TmpReg)
1087 .addImm(TheVal & 0xFFFF);
1093 // Make sure we have the register number for this value...
1094 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1096 switch (getClassB(Ty)) {
1098 // Extend value into target register (8->32)
1100 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1101 .addZImm(24).addZImm(31);
1103 BuildMI(BB, PPC32::EXTSB, 1, targetReg).addReg(Reg);
1106 // Extend value into target register (16->32)
1108 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1109 .addZImm(16).addZImm(31);
1111 BuildMI(BB, PPC32::EXTSH, 1, targetReg).addReg(Reg);
1114 // Move value into target register (32->32)
1115 BuildMI(BB, PPC32::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1118 assert(0 && "Unpromotable operand class in promote32");
1122 /// visitReturnInst - implemented with BLR
1124 void ISel::visitReturnInst(ReturnInst &I) {
1125 // Only do the processing if this is a non-void return
1126 if (I.getNumOperands() > 0) {
1127 Value *RetVal = I.getOperand(0);
1128 switch (getClassB(RetVal->getType())) {
1129 case cByte: // integral return values: extend or move into r3 and return
1132 promote32(PPC32::R3, ValueRecord(RetVal));
1134 case cFP: { // Floats & Doubles: Return in f1
1135 unsigned RetReg = getReg(RetVal);
1136 BuildMI(BB, PPC32::FMR, 1, PPC32::F1).addReg(RetReg);
1140 unsigned RetReg = getReg(RetVal);
1141 BuildMI(BB, PPC32::OR, 2, PPC32::R3).addReg(RetReg).addReg(RetReg);
1142 BuildMI(BB, PPC32::OR, 2, PPC32::R4).addReg(RetReg+1).addReg(RetReg+1);
1146 visitInstruction(I);
1149 BuildMI(BB, PPC32::BLR, 1).addImm(0);
1152 // getBlockAfter - Return the basic block which occurs lexically after the
1154 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1155 Function::iterator I = BB; ++I; // Get iterator to next block
1156 return I != BB->getParent()->end() ? &*I : 0;
1159 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1160 /// that since code layout is frozen at this point, that if we are trying to
1161 /// jump to a block that is the immediate successor of the current block, we can
1162 /// just make a fall-through (but we don't currently).
1164 void ISel::visitBranchInst(BranchInst &BI) {
1165 // Update machine-CFG edges
1166 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1167 if (BI.isConditional())
1168 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1170 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1172 if (!BI.isConditional()) { // Unconditional branch?
1173 if (BI.getSuccessor(0) != NextBB)
1174 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1178 // See if we can fold the setcc into the branch itself...
1179 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1181 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1182 // computed some other way...
1183 unsigned condReg = getReg(BI.getCondition());
1184 BuildMI(BB, PPC32::CMPLI, 3, PPC32::CR1).addImm(0).addReg(condReg)
1186 if (BI.getSuccessor(1) == NextBB) {
1187 if (BI.getSuccessor(0) != NextBB)
1188 BuildMI(BB, PPC32::BNE, 2).addReg(PPC32::CR1)
1189 .addMBB(MBBMap[BI.getSuccessor(0)]);
1191 BuildMI(BB, PPC32::BNE, 2).addReg(PPC32::CR1)
1192 .addMBB(MBBMap[BI.getSuccessor(1)]);
1194 if (BI.getSuccessor(0) != NextBB)
1195 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1200 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1201 unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1202 MachineBasicBlock::iterator MII = BB->end();
1203 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1205 if (BI.getSuccessor(0) != NextBB) {
1206 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1207 .addMBB(MBBMap[BI.getSuccessor(0)]);
1208 if (BI.getSuccessor(1) != NextBB)
1209 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1211 // Change to the inverse condition...
1212 if (BI.getSuccessor(1) != NextBB) {
1213 Opcode = invertPPCBranchOpcode(Opcode);
1214 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1215 .addMBB(MBBMap[BI.getSuccessor(1)]);
1220 static Constant* minUConstantForValue(uint64_t val) {
1222 return ConstantBool::get(val);
1223 else if (ConstantUInt::isValueValidForType(Type::UShortTy, val))
1224 return ConstantUInt::get(Type::UShortTy, val);
1225 else if (ConstantUInt::isValueValidForType(Type::UIntTy, val))
1226 return ConstantUInt::get(Type::UIntTy, val);
1227 else if (ConstantUInt::isValueValidForType(Type::ULongTy, val))
1228 return ConstantUInt::get(Type::ULongTy, val);
1230 std::cerr << "Value: " << val << " not accepted for any integral type!\n";
1234 /// doCall - This emits an abstract call instruction, setting up the arguments
1235 /// and the return value as appropriate. For the actual function call itself,
1236 /// it inserts the specified CallMI instruction into the stream.
1238 /// FIXME: See Documentation at the following URL for "correct" behavior
1239 /// <http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html>
1240 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1241 const std::vector<ValueRecord> &Args, bool isVarArg) {
1242 // Count how many bytes are to be pushed on the stack...
1243 unsigned NumBytes = 0;
1245 if (!Args.empty()) {
1246 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1247 switch (getClassB(Args[i].Ty)) {
1248 case cByte: case cShort: case cInt:
1249 NumBytes += 4; break;
1251 NumBytes += 8; break;
1253 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1255 default: assert(0 && "Unknown class!");
1258 // Adjust the stack pointer for the new arguments...
1259 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1261 // Arguments go on the stack in reverse order, as specified by the ABI.
1262 unsigned ArgOffset = 0;
1263 int GPR_remaining = 8, FPR_remaining = 13;
1264 unsigned GPR_idx = 0, FPR_idx = 0;
1265 static const unsigned GPR[] = {
1266 PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
1267 PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
1269 static const unsigned FPR[] = {
1270 PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6,
1271 PPC32::F7, PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12,
1275 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1277 switch (getClassB(Args[i].Ty)) {
1280 // Promote arg to 32 bits wide into a temporary register...
1281 ArgReg = makeAnotherReg(Type::UIntTy);
1282 promote32(ArgReg, Args[i]);
1285 if (GPR_remaining > 0) {
1286 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1289 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1294 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1297 if (GPR_remaining > 0) {
1298 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1301 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1306 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1309 if (GPR_remaining > 1) {
1310 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1312 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx + 1]).addReg(ArgReg+1)
1315 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1317 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg+1).addImm(ArgOffset+4)
1321 ArgOffset += 4; // 8 byte entry, not 4.
1322 GPR_remaining -= 1; // uses up 2 GPRs
1326 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1327 if (Args[i].Ty == Type::FloatTy) {
1328 assert(!isVarArg && "Cannot pass floats to vararg functions!");
1330 if (FPR_remaining > 0) {
1331 BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1335 BuildMI(BB, PPC32::STFS, 3).addReg(ArgReg).addImm(ArgOffset)
1339 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1341 if (FPR_remaining > 0) {
1342 BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1345 // For vararg functions, must pass doubles via int regs as well
1347 Value *Val = Args[i].Val;
1348 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Val)) {
1356 U.FVal = CFP->getValue();
1357 if (GPR_remaining > 0) {
1358 Constant *hi32 = minUConstantForValue(U.UVal.hi32);
1359 copyConstantToRegister(BB, BB->end(), hi32, GPR[GPR_idx]);
1361 if (GPR_remaining > 1) {
1362 Constant *lo32 = minUConstantForValue(U.UVal.lo32);
1363 copyConstantToRegister(BB, BB->end(), lo32, GPR[GPR_idx+1]);
1366 // Since this is not a constant, we must load it into int regs
1368 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addImm(ArgOffset)
1370 if (GPR_remaining > 0)
1371 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx]).addImm(ArgOffset)
1373 if (GPR_remaining > 1)
1374 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx+1])
1375 .addImm(ArgOffset+4).addReg(PPC32::R1);
1379 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addImm(ArgOffset)
1383 ArgOffset += 4; // 8 byte entry, not 4.
1384 GPR_remaining--; // uses up 2 GPRs
1389 default: assert(0 && "Unknown class!");
1396 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(0);
1399 BB->push_back(CallMI);
1400 BuildMI(BB, PPC32::ADJCALLSTACKUP, 1).addImm(NumBytes);
1402 // If there is a return value, scavenge the result from the location the call
1405 if (Ret.Ty != Type::VoidTy) {
1406 unsigned DestClass = getClassB(Ret.Ty);
1407 switch (DestClass) {
1411 // Integral results are in r3
1412 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1414 case cFP: // Floating-point return values live in f1
1415 BuildMI(BB, PPC32::FMR, 1, Ret.Reg).addReg(PPC32::F1);
1417 case cLong: // Long values are in r3:r4
1418 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1419 BuildMI(BB, PPC32::OR, 2, Ret.Reg+1).addReg(PPC32::R4).addReg(PPC32::R4);
1421 default: assert(0 && "Unknown class!");
1427 /// visitCallInst - Push args on stack and do a procedure call instruction.
1428 void ISel::visitCallInst(CallInst &CI) {
1429 MachineInstr *TheCall;
1430 Function *F = CI.getCalledFunction();
1432 // Is it an intrinsic function call?
1433 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1434 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1438 // Emit a CALL instruction with PC-relative displacement.
1439 TheCall = BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(F, true);
1440 } else { // Emit an indirect call through the CTR
1441 unsigned Reg = getReg(CI.getCalledValue());
1442 BuildMI(PPC32::MTSPR, 2).addZImm(9).addReg(Reg);
1443 TheCall = BuildMI(PPC32::CALLindirect, 1).addZImm(20).addZImm(0);
1446 std::vector<ValueRecord> Args;
1447 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1448 Args.push_back(ValueRecord(CI.getOperand(i)));
1450 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1451 bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1452 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1456 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1458 static Value *dyncastIsNan(Value *V) {
1459 if (CallInst *CI = dyn_cast<CallInst>(V))
1460 if (Function *F = CI->getCalledFunction())
1461 if (F->getIntrinsicID() == Intrinsic::isunordered)
1462 return CI->getOperand(1);
1466 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1467 /// or's whos operands are all calls to the isnan predicate.
1468 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1469 assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1471 // Check all uses, which will be or's of isnans if this predicate is true.
1472 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1473 Instruction *I = cast<Instruction>(*UI);
1474 if (I->getOpcode() != Instruction::Or) return false;
1475 if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1476 if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1482 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1483 /// function, lowering any calls to unknown intrinsic functions into the
1484 /// equivalent LLVM code.
1486 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1487 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1488 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1489 if (CallInst *CI = dyn_cast<CallInst>(I++))
1490 if (Function *F = CI->getCalledFunction())
1491 switch (F->getIntrinsicID()) {
1492 case Intrinsic::not_intrinsic:
1493 case Intrinsic::vastart:
1494 case Intrinsic::vacopy:
1495 case Intrinsic::vaend:
1496 case Intrinsic::returnaddress:
1497 case Intrinsic::frameaddress:
1498 // FIXME: should lower this ourselves
1499 // case Intrinsic::isunordered:
1500 // We directly implement these intrinsics
1502 case Intrinsic::readio: {
1503 // On PPC, memory operations are in-order. Lower this intrinsic
1504 // into a volatile load.
1505 Instruction *Before = CI->getPrev();
1506 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1507 CI->replaceAllUsesWith(LI);
1508 BB->getInstList().erase(CI);
1511 case Intrinsic::writeio: {
1512 // On PPC, memory operations are in-order. Lower this intrinsic
1513 // into a volatile store.
1514 Instruction *Before = CI->getPrev();
1515 StoreInst *LI = new StoreInst(CI->getOperand(1),
1516 CI->getOperand(2), true, CI);
1517 CI->replaceAllUsesWith(LI);
1518 BB->getInstList().erase(CI);
1522 // All other intrinsic calls we must lower.
1523 Instruction *Before = CI->getPrev();
1524 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1525 if (Before) { // Move iterator to instruction after call
1533 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1534 unsigned TmpReg1, TmpReg2, TmpReg3;
1536 case Intrinsic::vastart:
1537 // Get the address of the first vararg value...
1538 TmpReg1 = getReg(CI);
1539 addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1), VarArgsFrameIndex);
1542 case Intrinsic::vacopy:
1543 TmpReg1 = getReg(CI);
1544 TmpReg2 = getReg(CI.getOperand(1));
1545 BuildMI(BB, PPC32::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1547 case Intrinsic::vaend: return;
1549 case Intrinsic::returnaddress:
1550 case Intrinsic::frameaddress:
1551 TmpReg1 = getReg(CI);
1552 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1553 if (ID == Intrinsic::returnaddress) {
1554 // Just load the return address
1555 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, TmpReg1),
1556 ReturnAddressIndex);
1558 addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1),
1559 ReturnAddressIndex, -4, false);
1562 // Values other than zero are not implemented yet.
1563 BuildMI(BB, PPC32::ADDI, 2, TmpReg1).addReg(PPC32::R0).addImm(0);
1568 // This may be useful for supporting isunordered
1569 case Intrinsic::isnan:
1570 // If this is only used by 'isunordered' style comparisons, don't emit it.
1571 if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1572 TmpReg1 = getReg(CI.getOperand(1));
1573 emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1574 TmpReg2 = makeAnotherReg(Type::IntTy);
1575 BuildMI(BB, PPC32::MFCR, TmpReg2);
1576 TmpReg3 = getReg(CI);
1577 BuildMI(BB, PPC32::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1581 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1585 /// visitSimpleBinary - Implement simple binary operators for integral types...
1586 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1589 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1590 unsigned DestReg = getReg(B);
1591 MachineBasicBlock::iterator MI = BB->end();
1592 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1593 unsigned Class = getClassB(B.getType());
1595 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1598 /// emitBinaryFPOperation - This method handles emission of floating point
1599 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1600 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1601 MachineBasicBlock::iterator IP,
1602 Value *Op0, Value *Op1,
1603 unsigned OperatorClass, unsigned DestReg) {
1605 // Special case: op Reg, <const fp>
1606 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1607 // Create a constant pool entry for this constant.
1608 MachineConstantPool *CP = F->getConstantPool();
1609 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1610 const Type *Ty = Op1->getType();
1611 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1613 static const unsigned OpcodeTab[][4] = {
1614 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1615 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1618 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1619 unsigned Op1Reg = getReg(Op1C, BB, IP);
1620 unsigned Op0r = getReg(Op0, BB, IP);
1621 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1Reg);
1625 // Special case: R1 = op <const fp>, R2
1626 if (ConstantFP *Op0C = dyn_cast<ConstantFP>(Op0))
1627 if (Op0C->isExactlyValue(-0.0) && OperatorClass == 1) {
1629 unsigned op1Reg = getReg(Op1, BB, IP);
1630 BuildMI(*BB, IP, PPC32::FNEG, 1, DestReg).addReg(op1Reg);
1633 // R1 = op CST, R2 --> R1 = opr R2, CST
1635 // Create a constant pool entry for this constant.
1636 MachineConstantPool *CP = F->getConstantPool();
1637 unsigned CPI = CP->getConstantPoolIndex(Op0C);
1638 const Type *Ty = Op0C->getType();
1639 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1641 static const unsigned OpcodeTab[][4] = {
1642 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1643 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1646 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1647 unsigned Op0Reg = getReg(Op0C, BB, IP);
1648 unsigned Op1Reg = getReg(Op1, BB, IP);
1649 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1654 static const unsigned OpcodeTab[] = {
1655 PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV
1658 unsigned Opcode = OpcodeTab[OperatorClass];
1659 unsigned Op0r = getReg(Op0, BB, IP);
1660 unsigned Op1r = getReg(Op1, BB, IP);
1661 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1664 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1665 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1668 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1669 /// and constant expression support.
1671 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1672 MachineBasicBlock::iterator IP,
1673 Value *Op0, Value *Op1,
1674 unsigned OperatorClass, unsigned DestReg) {
1675 unsigned Class = getClassB(Op0->getType());
1677 // Arithmetic and Bitwise operators
1678 static const unsigned OpcodeTab[] = {
1679 PPC32::ADD, PPC32::SUB, PPC32::AND, PPC32::OR, PPC32::XOR
1681 // Otherwise, code generate the full operation with a constant.
1682 static const unsigned BottomTab[] = {
1683 PPC32::ADDC, PPC32::SUBC, PPC32::AND, PPC32::OR, PPC32::XOR
1685 static const unsigned TopTab[] = {
1686 PPC32::ADDE, PPC32::SUBFE, PPC32::AND, PPC32::OR, PPC32::XOR
1690 assert(OperatorClass < 2 && "No logical ops for FP!");
1691 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1695 if (Op0->getType() == Type::BoolTy) {
1696 if (OperatorClass == 3)
1697 // If this is an or of two isnan's, emit an FP comparison directly instead
1698 // of or'ing two isnan's together.
1699 if (Value *LHS = dyncastIsNan(Op0))
1700 if (Value *RHS = dyncastIsNan(Op1)) {
1701 unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1702 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1703 emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1704 BuildMI(*MBB, IP, PPC32::MFCR, TmpReg);
1705 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1706 .addImm(31).addImm(31);
1711 // sub 0, X -> neg X
1712 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
1713 if (OperatorClass == 1 && CI->isNullValue()) {
1714 unsigned op1Reg = getReg(Op1, MBB, IP);
1715 BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg).addReg(op1Reg);
1717 if (Class == cLong) {
1718 unsigned zeroes = makeAnotherReg(Type::IntTy);
1719 unsigned overflow = makeAnotherReg(Type::IntTy);
1720 unsigned T = makeAnotherReg(Type::IntTy);
1721 BuildMI(*MBB, IP, PPC32::CNTLZW, 1, zeroes).addReg(op1Reg);
1722 BuildMI(*MBB, IP, PPC32::RLWINM, 4, overflow).addReg(zeroes).addImm(27)
1723 .addImm(5).addImm(31);
1724 BuildMI(*MBB, IP, PPC32::ADD, 2, T).addReg(op1Reg+1).addReg(overflow);
1725 BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg+1).addReg(T);
1730 // Special case: op Reg, <const int>
1731 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1732 unsigned Op0r = getReg(Op0, MBB, IP);
1734 // xor X, -1 -> not X
1735 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1736 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1737 if (Class == cLong) // Invert the top part too
1738 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg+1).addReg(Op0r+1)
1743 unsigned Opcode = OpcodeTab[OperatorClass];
1744 unsigned Op1r = getReg(Op1, MBB, IP);
1746 if (Class != cLong) {
1747 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1751 // If the constant is zero in the low 32-bits, just copy the low part
1752 // across and apply the normal 32-bit operation to the high parts. There
1753 // will be no carry or borrow into the top.
1754 if (cast<ConstantInt>(Op1C)->getRawValue() == 0) {
1755 if (OperatorClass != 2) // All but and...
1756 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1758 BuildMI(*MBB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1759 BuildMI(*MBB, IP, Opcode, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1763 // If this is a long value and the high or low bits have a special
1764 // property, emit some special cases.
1765 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
1767 // If this is a logical operation and the top 32-bits are zero, just
1768 // operate on the lower 32.
1769 if (Op1h == 0 && OperatorClass > 1) {
1770 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1771 if (OperatorClass != 2) // All but and
1772 BuildMI(*MBB, IP, PPC32::OR, 2,DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
1774 BuildMI(*MBB, IP, PPC32::ADDI, 2,DestReg+1).addReg(PPC32::R0).addImm(0);
1778 // TODO: We could handle lots of other special cases here, such as AND'ing
1779 // with 0xFFFFFFFF00000000 -> noop, etc.
1781 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1783 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1788 unsigned Op0r = getReg(Op0, MBB, IP);
1789 unsigned Op1r = getReg(Op1, MBB, IP);
1791 if (Class != cLong) {
1792 unsigned Opcode = OpcodeTab[OperatorClass];
1793 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1795 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1797 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1803 /// doMultiply - Emit appropriate instructions to multiply together the
1804 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1805 /// result should be given as DestTy.
1807 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1808 unsigned DestReg, const Type *DestTy,
1809 unsigned op0Reg, unsigned op1Reg) {
1810 unsigned Class = getClass(DestTy);
1813 BuildMI(*MBB, MBBI, PPC32::MULHW, 2, DestReg+1).addReg(op0Reg+1)
1818 BuildMI(*MBB, MBBI, PPC32::MULLW, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1821 assert(0 && "doMultiply cannot operate on unknown type!");
1825 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1826 // returns zero when the input is not exactly a power of two.
1827 static unsigned ExactLog2(unsigned Val) {
1828 if (Val == 0 || (Val & (Val-1))) return 0;
1838 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
1839 /// 16, or 32-bit integer multiply by a constant.
1841 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1842 MachineBasicBlock::iterator IP,
1843 unsigned DestReg, const Type *DestTy,
1844 unsigned op0Reg, unsigned ConstRHS) {
1845 unsigned Class = getClass(DestTy);
1846 // Handle special cases here.
1849 BuildMI(*MBB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1852 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(op0Reg).addReg(op0Reg);
1855 BuildMI(*MBB, IP, PPC32::ADD, 2,DestReg).addReg(op0Reg).addReg(op0Reg);
1859 // If the element size is exactly a power of 2, use a shift to get it.
1860 if (unsigned Shift = ExactLog2(ConstRHS)) {
1862 default: assert(0 && "Unknown class for this function!");
1866 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(op0Reg)
1867 .addImm(Shift-1).addImm(0).addImm(31-Shift-1);
1872 // Most general case, emit a normal multiply...
1873 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
1874 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1875 BuildMI(*MBB, IP, PPC32::ADDIS, 2, TmpReg1).addReg(PPC32::R0)
1876 .addImm(ConstRHS >> 16);
1877 BuildMI(*MBB, IP, PPC32::ORI, 2, TmpReg2).addReg(TmpReg1).addImm(ConstRHS);
1879 // Emit a MUL to multiply the register holding the index by
1880 // elementSize, putting the result in OffsetReg.
1881 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg2);
1884 void ISel::visitMul(BinaryOperator &I) {
1885 unsigned ResultReg = getReg(I);
1887 Value *Op0 = I.getOperand(0);
1888 Value *Op1 = I.getOperand(1);
1890 MachineBasicBlock::iterator IP = BB->end();
1891 emitMultiply(BB, IP, Op0, Op1, ResultReg);
1894 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
1895 Value *Op0, Value *Op1, unsigned DestReg) {
1896 MachineBasicBlock &BB = *MBB;
1897 TypeClass Class = getClass(Op0->getType());
1899 // Simple scalar multiply?
1900 unsigned Op0Reg = getReg(Op0, &BB, IP);
1905 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1906 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
1907 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
1909 unsigned Op1Reg = getReg(Op1, &BB, IP);
1910 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
1914 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
1920 // Long value. We have to do things the hard way...
1921 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1922 unsigned CLow = CI->getRawValue();
1923 unsigned CHi = CI->getRawValue() >> 32;
1926 // If the low part of the constant is all zeros, things are simple.
1927 BuildMI(BB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1928 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
1932 // Multiply the two low parts
1933 unsigned OverflowReg = 0;
1935 BuildMI(BB, IP, PPC32::OR, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
1937 unsigned TmpRegL = makeAnotherReg(Type::UIntTy);
1938 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
1939 OverflowReg = makeAnotherReg(Type::UIntTy);
1940 BuildMI(BB, IP, PPC32::ADDIS, 2, TmpRegL).addReg(PPC32::R0)
1941 .addImm(CLow >> 16);
1942 BuildMI(BB, IP, PPC32::ORI, 2, Op1RegL).addReg(TmpRegL).addImm(CLow);
1943 BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1RegL);
1944 BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg)
1948 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1949 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
1951 unsigned AHBLplusOverflowReg;
1953 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1954 BuildMI(BB, IP, PPC32::ADD, 2,
1955 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1957 AHBLplusOverflowReg = AHBLReg;
1961 BuildMI(BB, IP, PPC32::OR, 2, DestReg+1).addReg(AHBLplusOverflowReg)
1962 .addReg(AHBLplusOverflowReg);
1964 unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
1965 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
1967 BuildMI(BB, IP, PPC32::ADD, 2,
1968 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1973 // General 64x64 multiply
1975 unsigned Op1Reg = getReg(Op1, &BB, IP);
1977 // Multiply the two low parts...
1978 BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1980 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1981 BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg).addReg(Op1Reg);
1983 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1984 BuildMI(BB, IP, PPC32::MULLW, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1986 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1987 BuildMI(BB, IP, PPC32::ADD, 2, AHBLplusOverflowReg).addReg(AHBLReg)
1988 .addReg(OverflowReg);
1990 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1991 BuildMI(BB, IP, PPC32::MULLW, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1993 BuildMI(BB, IP, PPC32::ADD, 2,
1994 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1998 /// visitDivRem - Handle division and remainder instructions... these
1999 /// instruction both require the same instructions to be generated, they just
2000 /// select the result from a different register. Note that both of these
2001 /// instructions work differently for signed and unsigned operands.
2003 void ISel::visitDivRem(BinaryOperator &I) {
2004 unsigned ResultReg = getReg(I);
2005 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2007 MachineBasicBlock::iterator IP = BB->end();
2008 emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
2012 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2013 MachineBasicBlock::iterator IP,
2014 Value *Op0, Value *Op1, bool isDiv,
2015 unsigned ResultReg) {
2016 const Type *Ty = Op0->getType();
2017 unsigned Class = getClass(Ty);
2019 case cFP: // Floating point divide
2021 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2023 } else { // Floating point remainder...
2024 unsigned Op0Reg = getReg(Op0, BB, IP);
2025 unsigned Op1Reg = getReg(Op1, BB, IP);
2026 MachineInstr *TheCall =
2027 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2028 std::vector<ValueRecord> Args;
2029 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2030 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2031 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2035 static Function* const Funcs[] =
2036 { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2037 unsigned Op0Reg = getReg(Op0, BB, IP);
2038 unsigned Op1Reg = getReg(Op1, BB, IP);
2039 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2040 MachineInstr *TheCall =
2041 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2043 std::vector<ValueRecord> Args;
2044 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2045 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2046 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2049 case cByte: case cShort: case cInt:
2050 break; // Small integrals, handled below...
2051 default: assert(0 && "Unknown class!");
2054 // Special case signed division by power of 2.
2056 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2057 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2058 int V = CI->getValue();
2060 if (V == 1) { // X /s 1 => X
2061 unsigned Op0Reg = getReg(Op0, BB, IP);
2062 BuildMI(*BB, IP, PPC32::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2066 if (V == -1) { // X /s -1 => -X
2067 unsigned Op0Reg = getReg(Op0, BB, IP);
2068 BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(Op0Reg);
2073 if (V < 0) { // Not a positive power of 2?
2075 isNeg = true; // Maybe it's a negative power of 2.
2077 if (unsigned Log = ExactLog2(V)) {
2079 unsigned Op0Reg = getReg(Op0, BB, IP);
2080 unsigned TmpReg = makeAnotherReg(Op0->getType());
2082 BuildMI(*BB, IP, PPC32::SRAWI,2, TmpReg).addReg(Op0Reg).addImm(Log-1);
2084 BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(Op0Reg).addReg(Op0Reg);
2086 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2087 BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg2).addReg(TmpReg).addImm(Log)
2088 .addImm(32-Log).addImm(31);
2090 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2091 BuildMI(*BB, IP, PPC32::ADD, 2, TmpReg3).addReg(Op0Reg).addReg(TmpReg2);
2093 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2094 BuildMI(*BB, IP, PPC32::SRAWI, 2, TmpReg4).addReg(Op0Reg).addImm(Log);
2097 BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(TmpReg4);
2102 unsigned Op0Reg = getReg(Op0, BB, IP);
2103 unsigned Op1Reg = getReg(Op1, BB, IP);
2106 if (Ty->isSigned()) {
2107 BuildMI(*BB, IP, PPC32::DIVW, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2109 BuildMI(*BB, IP,PPC32::DIVWU, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2111 } else { // Remainder
2112 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2113 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2115 if (Ty->isSigned()) {
2116 BuildMI(*BB, IP, PPC32::DIVW, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2118 BuildMI(*BB, IP, PPC32::DIVWU, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2120 BuildMI(*BB, IP, PPC32::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2121 BuildMI(*BB, IP, PPC32::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2126 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2127 /// for constant immediate shift values, and for constant immediate
2128 /// shift values equal to 1. Even the general case is sort of special,
2129 /// because the shift amount has to be in CL, not just any old register.
2131 void ISel::visitShiftInst(ShiftInst &I) {
2132 MachineBasicBlock::iterator IP = BB->end ();
2133 emitShiftOperation(BB, IP, I.getOperand (0), I.getOperand (1),
2134 I.getOpcode () == Instruction::Shl, I.getType (),
2138 /// emitShiftOperation - Common code shared between visitShiftInst and
2139 /// constant expression support.
2141 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2142 MachineBasicBlock::iterator IP,
2143 Value *Op, Value *ShiftAmount, bool isLeftShift,
2144 const Type *ResultTy, unsigned DestReg) {
2145 unsigned SrcReg = getReg (Op, MBB, IP);
2146 bool isSigned = ResultTy->isSigned ();
2147 unsigned Class = getClass (ResultTy);
2149 // Longs, as usual, are handled specially...
2150 if (Class == cLong) {
2151 // If we have a constant shift, we can generate much more efficient code
2152 // than otherwise...
2154 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2155 unsigned Amount = CUI->getValue();
2158 // FIXME: RLWIMI is a use-and-def of DestReg+1, but that violates SSA
2159 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2160 .addImm(Amount).addImm(0).addImm(31-Amount);
2161 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg+1).addReg(SrcReg)
2162 .addImm(Amount).addImm(32-Amount).addImm(31);
2163 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2164 .addImm(Amount).addImm(0).addImm(31-Amount);
2166 // FIXME: RLWIMI is a use-and-def of DestReg, but that violates SSA
2167 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2168 .addImm(32-Amount).addImm(Amount).addImm(31);
2169 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg).addReg(SrcReg+1)
2170 .addImm(32-Amount).addImm(0).addImm(Amount-1);
2171 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2172 .addImm(32-Amount).addImm(Amount).addImm(31);
2174 } else { // Shifting more than 32 bits
2178 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg)
2179 .addImm(Amount).addImm(0).addImm(31-Amount);
2181 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg)
2184 BuildMI(*MBB, IP, PPC32::ADDI, 2,DestReg).addReg(PPC32::R0).addImm(0);
2188 BuildMI(*MBB, IP, PPC32::SRAWI, 2, DestReg).addReg(SrcReg+1)
2191 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg+1)
2192 .addImm(32-Amount).addImm(Amount).addImm(31);
2194 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg+1)
2197 BuildMI(*MBB, IP,PPC32::ADDI,2,DestReg+1).addReg(PPC32::R0).addImm(0);
2201 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2202 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2203 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2204 unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2205 unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2206 unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2207 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2210 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2212 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(SrcReg+1)
2213 .addReg(ShiftAmountReg);
2214 BuildMI(*MBB, IP, PPC32::SRW, 2,TmpReg3).addReg(SrcReg).addReg(TmpReg1);
2215 BuildMI(*MBB, IP, PPC32::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2216 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2218 BuildMI(*MBB, IP, PPC32::SLW, 2,TmpReg6).addReg(SrcReg).addReg(TmpReg5);
2219 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TmpReg4)
2221 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2222 .addReg(ShiftAmountReg);
2225 // FIXME: Unimplemented
2226 // Page C-3 of the PowerPC 32bit Programming Environments Manual
2227 std::cerr << "Unimplemented: signed right shift\n";
2230 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2232 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg2).addReg(SrcReg)
2233 .addReg(ShiftAmountReg);
2234 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg3).addReg(SrcReg+1)
2236 BuildMI(*MBB, IP, PPC32::OR, 2, TmpReg4).addReg(TmpReg2)
2238 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2240 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg6).addReg(SrcReg+1)
2242 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TmpReg4)
2244 BuildMI(*MBB, IP, PPC32::SRW, 2, DestReg+1).addReg(SrcReg+1)
2245 .addReg(ShiftAmountReg);
2252 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2253 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2254 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2255 unsigned Amount = CUI->getValue();
2258 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2259 .addImm(Amount).addImm(0).addImm(31-Amount);
2262 BuildMI(*MBB, IP, PPC32::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2264 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2265 .addImm(32-Amount).addImm(Amount).addImm(31);
2268 } else { // The shift amount is non-constant.
2269 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2272 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2273 .addReg(ShiftAmountReg);
2275 BuildMI(*MBB, IP, isSigned ? PPC32::SRAW : PPC32::SRW, 2, DestReg)
2276 .addReg(SrcReg).addReg(ShiftAmountReg);
2282 /// visitLoadInst - Implement LLVM load instructions
2284 void ISel::visitLoadInst(LoadInst &I) {
2285 static const unsigned Opcodes[] = {
2286 PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS
2288 unsigned Class = getClassB(I.getType());
2289 unsigned Opcode = Opcodes[Class];
2290 if (I.getType() == Type::DoubleTy) Opcode = PPC32::LFD;
2292 unsigned DestReg = getReg(I);
2294 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
2295 unsigned FI = getFixedSizedAllocaFI(AI);
2296 if (Class == cLong) {
2297 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg), FI);
2298 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg+1), FI, 4);
2300 addFrameReference(BuildMI(BB, Opcode, 2, DestReg), FI);
2303 unsigned SrcAddrReg = getReg(I.getOperand(0));
2305 if (Class == cLong) {
2306 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2307 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(SrcAddrReg);
2309 BuildMI(BB, Opcode, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2314 /// visitStoreInst - Implement LLVM store instructions
2316 void ISel::visitStoreInst(StoreInst &I) {
2317 unsigned ValReg = getReg(I.getOperand(0));
2318 unsigned AddressReg = getReg(I.getOperand(1));
2320 const Type *ValTy = I.getOperand(0)->getType();
2321 unsigned Class = getClassB(ValTy);
2323 if (Class == cLong) {
2324 BuildMI(BB, PPC32::STW, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2325 BuildMI(BB, PPC32::STW, 3).addReg(ValReg+1).addImm(4).addReg(AddressReg);
2329 static const unsigned Opcodes[] = {
2330 PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS
2332 unsigned Opcode = Opcodes[Class];
2333 if (ValTy == Type::DoubleTy) Opcode = PPC32::STFD;
2334 BuildMI(BB, Opcode, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2338 /// visitCastInst - Here we have various kinds of copying with or without sign
2339 /// extension going on.
2341 void ISel::visitCastInst(CastInst &CI) {
2342 Value *Op = CI.getOperand(0);
2344 unsigned SrcClass = getClassB(Op->getType());
2345 unsigned DestClass = getClassB(CI.getType());
2346 // Noop casts are not emitted: getReg will return the source operand as the
2347 // register to use for any uses of the noop cast.
2348 if (DestClass == SrcClass)
2351 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2352 // of the case are GEP instructions, then the cast does not need to be
2353 // generated explicitly, it will be folded into the GEP.
2354 if (DestClass == cLong && SrcClass == cInt) {
2355 bool AllUsesAreGEPs = true;
2356 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2357 if (!isa<GetElementPtrInst>(*I)) {
2358 AllUsesAreGEPs = false;
2362 // No need to codegen this cast if all users are getelementptr instrs...
2363 if (AllUsesAreGEPs) return;
2366 unsigned DestReg = getReg(CI);
2367 MachineBasicBlock::iterator MI = BB->end();
2368 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2371 /// emitCastOperation - Common code shared between visitCastInst and constant
2372 /// expression cast support.
2374 void ISel::emitCastOperation(MachineBasicBlock *BB,
2375 MachineBasicBlock::iterator IP,
2376 Value *Src, const Type *DestTy,
2378 const Type *SrcTy = Src->getType();
2379 unsigned SrcClass = getClassB(SrcTy);
2380 unsigned DestClass = getClassB(DestTy);
2381 unsigned SrcReg = getReg(Src, BB, IP);
2383 // Implement casts to bool by using compare on the operand followed by set if
2384 // not zero on the result.
2385 if (DestTy == Type::BoolTy) {
2390 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2391 BuildMI(*BB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg).addImm(-1);
2392 BuildMI(*BB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2396 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2397 unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
2398 BuildMI(*BB, IP, PPC32::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
2399 BuildMI(*BB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg2).addImm(-1);
2400 BuildMI(*BB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg2);
2414 std::cerr << "Cast fp-to-bool not implemented!";
2420 // Implement casts between values of the same type class (as determined by
2421 // getClass) by using a register-to-register move.
2422 if (SrcClass == DestClass) {
2423 if (SrcClass <= cInt) {
2424 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2425 } else if (SrcClass == cFP && SrcTy == DestTy) {
2426 BuildMI(*BB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2427 } else if (SrcClass == cFP) {
2428 if (SrcTy == Type::FloatTy) { // float -> double
2429 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2430 BuildMI(*BB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2431 } else { // double -> float
2432 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2433 "Unknown cFP member!");
2434 BuildMI(*BB, IP, PPC32::FRSP, 1, DestReg).addReg(SrcReg);
2436 } else if (SrcClass == cLong) {
2437 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2438 BuildMI(*BB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg+1)
2441 assert(0 && "Cannot handle this type of cast instruction!");
2447 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2448 // or zero extension, depending on whether the source type was signed.
2449 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2450 SrcClass < DestClass) {
2451 bool isLong = DestClass == cLong;
2452 if (isLong) DestClass = cInt;
2454 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2455 if (SrcClass < cInt) {
2457 unsigned shift = (SrcClass == cByte) ? 24 : 16;
2458 BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2459 .addImm(shift).addImm(31);
2461 BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH,
2462 1, DestReg).addReg(SrcReg);
2465 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2468 if (isLong) { // Handle upper 32 bits as appropriate...
2469 if (isUnsigned) // Zero out top bits...
2470 BuildMI(*BB, IP, PPC32::ADDI, 2, DestReg+1).addReg(PPC32::R0).addImm(0);
2471 else // Sign extend bottom half...
2472 BuildMI(*BB, IP, PPC32::SRAWI, 2, DestReg+1).addReg(DestReg).addImm(31);
2477 // Special case long -> int ...
2478 if (SrcClass == cLong && DestClass == cInt) {
2479 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2483 // Handle cast of LARGER int to SMALLER int with a clear or sign extend
2484 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2485 && SrcClass > DestClass) {
2486 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2488 unsigned shift = (SrcClass == cByte) ? 24 : 16;
2489 BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2490 .addImm(shift).addImm(31);
2492 BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH, 1,
2493 DestReg).addReg(SrcReg);
2498 // Handle casts from integer to floating point now...
2499 if (DestClass == cFP) {
2501 // Emit a library call for long to float conversion
2502 if (SrcClass == cLong) {
2503 std::vector<ValueRecord> Args;
2504 Args.push_back(ValueRecord(SrcReg, SrcTy));
2505 Function *floatFn = (SrcTy==Type::FloatTy) ? __floatdisfFn : __floatdidfFn;
2506 MachineInstr *TheCall =
2507 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2508 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2512 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2513 switch (SrcTy->getTypeID()) {
2514 case Type::BoolTyID:
2515 case Type::SByteTyID:
2516 BuildMI(*BB, IP, PPC32::EXTSB, 1, TmpReg).addReg(SrcReg);
2518 case Type::UByteTyID:
2519 BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg).addReg(SrcReg).addZImm(0)
2520 .addImm(24).addImm(31);
2522 case Type::ShortTyID:
2523 BuildMI(*BB, IP, PPC32::EXTSB, 1, TmpReg).addReg(SrcReg);
2525 case Type::UShortTyID:
2526 BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg).addReg(SrcReg).addZImm(0)
2527 .addImm(16).addImm(31);
2530 BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(SrcReg).addReg(SrcReg);
2532 case Type::UIntTyID:
2533 BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(SrcReg).addReg(SrcReg);
2535 default: // No promotion needed...
2541 // Spill the integer to memory and reload it from there.
2542 // Also spill room for a special conversion constant
2543 int ConstantFrameIndex =
2544 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2546 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2548 unsigned constantHi = makeAnotherReg(Type::IntTy);
2549 unsigned constantLo = makeAnotherReg(Type::IntTy);
2550 unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2551 unsigned TempF = makeAnotherReg(Type::DoubleTy);
2553 if (!SrcTy->isSigned()) {
2554 BuildMI(*BB, IP, PPC32::ADDIS, 2, constantHi).addReg(PPC32::R0)
2556 BuildMI(*BB, IP, PPC32::ADDI, 2, constantLo).addReg(PPC32::R0).addImm(0);
2557 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2558 ConstantFrameIndex);
2559 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2560 ConstantFrameIndex, 4);
2561 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2563 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(SrcReg),
2565 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF),
2566 ConstantFrameIndex);
2567 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2568 BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2570 unsigned TempLo = makeAnotherReg(Type::IntTy);
2571 BuildMI(*BB, IP, PPC32::ADDIS, 2, constantHi).addReg(PPC32::R0)
2573 BuildMI(*BB, IP, PPC32::ADDIS, 2, constantLo).addReg(PPC32::R0)
2575 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2576 ConstantFrameIndex);
2577 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2578 ConstantFrameIndex, 4);
2579 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2581 BuildMI(*BB, IP, PPC32::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2582 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(TempLo),
2584 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF),
2585 ConstantFrameIndex);
2586 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2587 BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF ).addReg(ConstF);
2592 // Handle casts from floating point to integer now...
2593 if (SrcClass == cFP) {
2595 // emit library call
2596 if (DestClass == cLong) {
2597 std::vector<ValueRecord> Args;
2598 Args.push_back(ValueRecord(SrcReg, SrcTy));
2599 MachineInstr *TheCall =
2600 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(__fixdfdiFn, true);
2601 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2606 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2608 // load into 32 bit value, and then truncate as necessary
2609 // FIXME: This is wrong for unsigned dest types
2610 //if (DestTy->isSigned()) {
2611 unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2612 BuildMI(*BB, IP, PPC32::FCTIWZ, 1, TempReg).addReg(SrcReg);
2613 addFrameReference(BuildMI(*BB, IP, PPC32::STFD, 3)
2614 .addReg(TempReg), ValueFrameIdx);
2615 addFrameReference(BuildMI(*BB, IP, PPC32::LWZ, 2, DestReg),
2620 // FIXME: Truncate return value
2624 // Anything we haven't handled already, we can't (yet) handle at all.
2625 assert(0 && "Unhandled cast instruction!");
2629 /// visitVANextInst - Implement the va_next instruction...
2631 void ISel::visitVANextInst(VANextInst &I) {
2632 unsigned VAList = getReg(I.getOperand(0));
2633 unsigned DestReg = getReg(I);
2636 switch (I.getArgType()->getTypeID()) {
2639 assert(0 && "Error: bad type for va_next instruction!");
2641 case Type::PointerTyID:
2642 case Type::UIntTyID:
2646 case Type::ULongTyID:
2647 case Type::LongTyID:
2648 case Type::DoubleTyID:
2653 // Increment the VAList pointer...
2654 BuildMI(BB, PPC32::ADDI, 2, DestReg).addReg(VAList).addImm(Size);
2657 void ISel::visitVAArgInst(VAArgInst &I) {
2658 unsigned VAList = getReg(I.getOperand(0));
2659 unsigned DestReg = getReg(I);
2661 switch (I.getType()->getTypeID()) {
2664 assert(0 && "Error: bad type for va_next instruction!");
2666 case Type::PointerTyID:
2667 case Type::UIntTyID:
2669 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2671 case Type::ULongTyID:
2672 case Type::LongTyID:
2673 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2674 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(VAList);
2676 case Type::DoubleTyID:
2677 BuildMI(BB, PPC32::LFD, 2, DestReg).addImm(0).addReg(VAList);
2682 /// visitGetElementPtrInst - instruction-select GEP instructions
2684 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2685 unsigned outputReg = getReg(I);
2686 emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(),
2690 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2691 MachineBasicBlock::iterator IP,
2692 Value *Src, User::op_iterator IdxBegin,
2693 User::op_iterator IdxEnd, unsigned TargetReg) {
2694 const TargetData &TD = TM.getTargetData();
2695 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2696 Src = CPR->getValue();
2698 std::vector<Value*> GEPOps;
2699 GEPOps.resize(IdxEnd-IdxBegin+1);
2701 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2703 std::vector<const Type*> GEPTypes;
2704 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2705 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2707 // Keep emitting instructions until we consume the entire GEP instruction.
2708 while (!GEPOps.empty()) {
2709 if (GEPTypes.empty()) {
2710 // Load the base pointer into a register.
2711 unsigned Reg = getReg(Src, MBB, IP);
2712 BuildMI(*MBB, IP, PPC32::OR, 2, TargetReg).addReg(Reg).addReg(Reg);
2713 break; // we are now done
2715 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2716 // It's a struct access. CUI is the index into the structure,
2717 // which names the field. This index must have unsigned type.
2718 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2720 // Use the TargetData structure to pick out what the layout of the
2721 // structure is in memory. Since the structure index must be constant, we
2722 // can get its value and use it to find the right byte offset from the
2723 // StructLayout class's list of structure member offsets.
2724 unsigned Disp = TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2725 GEPOps.pop_back(); // Consume a GEP operand
2726 GEPTypes.pop_back();
2727 unsigned Reg = makeAnotherReg(Type::UIntTy);
2728 unsigned DispReg = makeAnotherReg(Type::UIntTy);
2729 BuildMI(*MBB, IP, PPC32::LI, 2, DispReg).addImm(Disp);
2730 BuildMI(*MBB, IP, PPC32::ADD, 2, TargetReg).addReg(Reg).addReg(DispReg);
2731 --IP; // Insert the next instruction before this one.
2732 TargetReg = Reg; // Codegen the rest of the GEP into this
2734 // It's an array or pointer access: [ArraySize x ElementType].
2735 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2736 Value *idx = GEPOps.back();
2737 GEPOps.pop_back(); // Consume a GEP operand
2738 GEPTypes.pop_back();
2740 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
2741 // operand. Handle this case directly now...
2742 if (CastInst *CI = dyn_cast<CastInst>(idx))
2743 if (CI->getOperand(0)->getType() == Type::IntTy ||
2744 CI->getOperand(0)->getType() == Type::UIntTy)
2745 idx = CI->getOperand(0);
2747 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2748 // must find the size of the pointed-to type (Not coincidentally, the next
2749 // type is the type of the elements in the array).
2750 const Type *ElTy = SqTy->getElementType();
2751 unsigned elementSize = TD.getTypeSize(ElTy);
2753 if (idx == Constant::getNullValue(idx->getType())) {
2754 // GEP with idx 0 is a no-op
2755 } else if (elementSize == 1) {
2756 // If the element size is 1, we don't have to multiply, just add
2757 unsigned idxReg = getReg(idx, MBB, IP);
2758 unsigned Reg = makeAnotherReg(Type::UIntTy);
2759 BuildMI(*MBB, IP, PPC32::ADD, 2,TargetReg).addReg(Reg).addReg(idxReg);
2760 --IP; // Insert the next instruction before this one.
2761 TargetReg = Reg; // Codegen the rest of the GEP into this
2763 unsigned idxReg = getReg(idx, MBB, IP);
2764 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2766 // Make sure we can back the iterator up to point to the first
2767 // instruction emitted.
2768 MachineBasicBlock::iterator BeforeIt = IP;
2769 if (IP == MBB->begin())
2770 BeforeIt = MBB->end();
2773 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2775 // Emit an ADD to add OffsetReg to the basePtr.
2776 unsigned Reg = makeAnotherReg(Type::UIntTy);
2777 BuildMI(*MBB, IP, PPC32::ADD, 2, TargetReg).addReg(Reg).addReg(OffsetReg);
2779 // Step to the first instruction of the multiply.
2780 if (BeforeIt == MBB->end())
2785 TargetReg = Reg; // Codegen the rest of the GEP into this
2791 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2792 /// frame manager, otherwise do it the hard way.
2794 void ISel::visitAllocaInst(AllocaInst &I) {
2795 // If this is a fixed size alloca in the entry block for the function, we
2796 // statically stack allocate the space, so we don't need to do anything here.
2798 if (dyn_castFixedAlloca(&I)) return;
2800 // Find the data size of the alloca inst's getAllocatedType.
2801 const Type *Ty = I.getAllocatedType();
2802 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2804 // Create a register to hold the temporary result of multiplying the type size
2805 // constant by the variable amount.
2806 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2807 unsigned SrcReg1 = getReg(I.getArraySize());
2809 // TotalSizeReg = mul <numelements>, <TypeSize>
2810 MachineBasicBlock::iterator MBBI = BB->end();
2811 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2813 // AddedSize = add <TotalSizeReg>, 15
2814 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2815 BuildMI(BB, PPC32::ADD, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2817 // AlignedSize = and <AddedSize>, ~15
2818 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2819 BuildMI(BB, PPC32::RLWNM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
2820 .addImm(0).addImm(27);
2822 // Subtract size from stack pointer, thereby allocating some space.
2823 BuildMI(BB, PPC32::SUB, 2, PPC32::R1).addReg(PPC32::R1).addReg(AlignedSize);
2825 // Put a pointer to the space into the result register, by copying
2826 // the stack pointer.
2827 BuildMI(BB, PPC32::OR, 2, getReg(I)).addReg(PPC32::R1).addReg(PPC32::R1);
2829 // Inform the Frame Information that we have just allocated a variable-sized
2831 F->getFrameInfo()->CreateVariableSizedObject();
2834 /// visitMallocInst - Malloc instructions are code generated into direct calls
2835 /// to the library malloc.
2837 void ISel::visitMallocInst(MallocInst &I) {
2838 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2841 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2842 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2844 Arg = makeAnotherReg(Type::UIntTy);
2845 unsigned Op0Reg = getReg(I.getOperand(0));
2846 MachineBasicBlock::iterator MBBI = BB->end();
2847 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2850 std::vector<ValueRecord> Args;
2851 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2852 MachineInstr *TheCall =
2853 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
2854 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
2858 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2861 void ISel::visitFreeInst(FreeInst &I) {
2862 std::vector<ValueRecord> Args;
2863 Args.push_back(ValueRecord(I.getOperand(0)));
2864 MachineInstr *TheCall =
2865 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(freeFn, true);
2866 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
2869 /// createPPC32SimpleInstructionSelector - This pass converts an LLVM function
2870 /// into a machine code representation is a very simple peep-hole fashion. The
2871 /// generated code sucks but the implementation is nice and simple.
2873 FunctionPass *llvm::createPPCSimpleInstructionSelector(TargetMachine &TM) {
2874 return new ISel(TM);