1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/CodeGen/SelectionDAGISel.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetFrameInfo.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
42 ViewDAGs("view-isel-dags", cl::Hidden,
43 cl::desc("Pop up a window to show isel dags as they are selected"));
45 static const bool ViewDAGs = 0;
50 //===--------------------------------------------------------------------===//
51 /// FunctionLoweringInfo - This contains information that is global to a
52 /// function that is used when lowering a region of the function.
53 class FunctionLoweringInfo {
60 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
62 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
63 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
65 /// ValueMap - Since we emit code for the function a basic block at a time,
66 /// we must remember which virtual registers hold the values for
67 /// cross-basic-block values.
68 std::map<const Value*, unsigned> ValueMap;
70 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
71 /// the entry block. This allows the allocas to be efficiently referenced
72 /// anywhere in the function.
73 std::map<const AllocaInst*, int> StaticAllocaMap;
75 /// BlockLocalArguments - If any arguments are only used in a single basic
76 /// block, and if the target can access the arguments without side-effects,
77 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
78 /// track of which arguments are local to each BB.
79 std::multimap<BasicBlock*, std::pair<Argument*,
80 unsigned> > BlockLocalArguments;
83 unsigned MakeReg(MVT::ValueType VT) {
84 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
87 unsigned CreateRegForValue(const Value *V) {
88 MVT::ValueType VT = TLI.getValueType(V->getType());
89 // The common case is that we will only create one register for this
90 // value. If we have that case, create and return the virtual register.
91 unsigned NV = TLI.getNumElements(VT);
93 // If we are promoting this value, pick the next largest supported type.
94 return MakeReg(TLI.getTypeToTransformTo(VT));
97 // If this value is represented with multiple target registers, make sure
98 // to create enough consequtive registers of the right (smaller) type.
99 unsigned NT = VT-1; // Find the type to use.
100 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
103 unsigned R = MakeReg((MVT::ValueType)NT);
104 for (unsigned i = 1; i != NV; ++i)
105 MakeReg((MVT::ValueType)NT);
109 unsigned InitializeRegForValue(const Value *V) {
110 unsigned &R = ValueMap[V];
111 assert(R == 0 && "Already initialized this value register!");
112 return R = CreateRegForValue(V);
117 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
118 /// PHI nodes or outside of the basic block that defines it.
119 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
120 if (isa<PHINode>(I)) return true;
121 BasicBlock *BB = I->getParent();
122 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
123 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
128 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
129 Function &fn, MachineFunction &mf)
130 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
132 // Initialize the mapping of values to registers. This is only set up for
133 // instruction values that are used outside of the block that defines
135 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
137 InitializeRegForValue(AI);
139 Function::iterator BB = Fn.begin(), EB = Fn.end();
140 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
141 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
142 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
143 const Type *Ty = AI->getAllocatedType();
144 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
145 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
147 // If the alignment of the value is smaller than the size of the value,
148 // and if the size of the value is particularly small (<= 8 bytes),
149 // round up to the size of the value for potentially better performance.
151 // FIXME: This could be made better with a preferred alignment hook in
152 // TargetData. It serves primarily to 8-byte align doubles for X86.
153 if (Align < TySize && TySize <= 8) Align = TySize;
155 if (CUI->getValue()) // Don't produce zero sized stack objects
156 TySize *= CUI->getValue(); // Get total allocated size.
157 StaticAllocaMap[AI] =
158 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
161 for (; BB != EB; ++BB)
162 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
163 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
164 if (!isa<AllocaInst>(I) ||
165 !StaticAllocaMap.count(cast<AllocaInst>(I)))
166 InitializeRegForValue(I);
168 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
169 // also creates the initial PHI MachineInstrs, though none of the input
170 // operands are populated.
171 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
172 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
174 MF.getBasicBlockList().push_back(MBB);
176 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
179 for (BasicBlock::iterator I = BB->begin();
180 (PN = dyn_cast<PHINode>(I)); ++I)
181 if (!PN->use_empty()) {
182 unsigned NumElements =
183 TLI.getNumElements(TLI.getValueType(PN->getType()));
184 unsigned PHIReg = ValueMap[PN];
185 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
186 for (unsigned i = 0; i != NumElements; ++i)
187 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
194 //===----------------------------------------------------------------------===//
195 /// SelectionDAGLowering - This is the common target-independent lowering
196 /// implementation that is parameterized by a TargetLowering object.
197 /// Also, targets can overload any lowering method.
200 class SelectionDAGLowering {
201 MachineBasicBlock *CurMBB;
203 std::map<const Value*, SDOperand> NodeMap;
205 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
206 /// them up and then emit token factor nodes when possible. This allows us to
207 /// get simple disambiguation between loads without worrying about alias
209 std::vector<SDOperand> PendingLoads;
212 // TLI - This is information that describes the available target features we
213 // need for lowering. This indicates when operations are unavailable,
214 // implemented with a libcall, etc.
217 const TargetData &TD;
219 /// FuncInfo - Information about the function as a whole.
221 FunctionLoweringInfo &FuncInfo;
223 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
224 FunctionLoweringInfo &funcinfo)
225 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
229 /// getRoot - Return the current virtual root of the Selection DAG.
231 SDOperand getRoot() {
232 if (PendingLoads.empty())
233 return DAG.getRoot();
235 if (PendingLoads.size() == 1) {
236 SDOperand Root = PendingLoads[0];
238 PendingLoads.clear();
242 // Otherwise, we have to make a token factor node.
243 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
244 PendingLoads.clear();
249 void visit(Instruction &I) { visit(I.getOpcode(), I); }
251 void visit(unsigned Opcode, User &I) {
253 default: assert(0 && "Unknown instruction type encountered!");
255 // Build the switch statement using the Instruction.def file.
256 #define HANDLE_INST(NUM, OPCODE, CLASS) \
257 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
258 #include "llvm/Instruction.def"
262 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
265 SDOperand getIntPtrConstant(uint64_t Val) {
266 return DAG.getConstant(Val, TLI.getPointerTy());
269 SDOperand getValue(const Value *V) {
270 SDOperand &N = NodeMap[V];
273 MVT::ValueType VT = TLI.getValueType(V->getType());
274 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
275 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
276 visit(CE->getOpcode(), *CE);
277 assert(N.Val && "visit didn't populate the ValueMap!");
279 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
280 return N = DAG.getGlobalAddress(GV, VT);
281 } else if (isa<ConstantPointerNull>(C)) {
282 return N = DAG.getConstant(0, TLI.getPointerTy());
283 } else if (isa<UndefValue>(C)) {
284 return N = DAG.getNode(ISD::UNDEF, VT);
285 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
286 return N = DAG.getConstantFP(CFP->getValue(), VT);
288 // Canonicalize all constant ints to be unsigned.
289 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
292 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
293 std::map<const AllocaInst*, int>::iterator SI =
294 FuncInfo.StaticAllocaMap.find(AI);
295 if (SI != FuncInfo.StaticAllocaMap.end())
296 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
299 std::map<const Value*, unsigned>::const_iterator VMI =
300 FuncInfo.ValueMap.find(V);
301 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
303 unsigned InReg = VMI->second;
305 // If this type is not legal, make it so now.
306 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
308 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
310 // Source must be expanded. This input value is actually coming from the
311 // register pair VMI->second and VMI->second+1.
312 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
313 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
315 if (DestVT > VT) { // Promotion case
316 if (MVT::isFloatingPoint(VT))
317 N = DAG.getNode(ISD::FP_ROUND, VT, N);
319 N = DAG.getNode(ISD::TRUNCATE, VT, N);
326 const SDOperand &setValue(const Value *V, SDOperand NewN) {
327 SDOperand &N = NodeMap[V];
328 assert(N.Val == 0 && "Already set a value for this node!");
332 // Terminator instructions.
333 void visitRet(ReturnInst &I);
334 void visitBr(BranchInst &I);
335 void visitUnreachable(UnreachableInst &I) { /* noop */ }
337 // These all get lowered before this pass.
338 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
339 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
340 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
343 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
344 void visitAdd(User &I) {
345 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FADD : ISD::ADD);
347 void visitSub(User &I);
348 void visitMul(User &I) {
349 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FMUL : ISD::MUL);
351 void visitDiv(User &I) {
353 const Type *Ty = I.getType();
354 if (Ty->isFloatingPoint())
356 else if (Ty->isUnsigned())
362 void visitRem(User &I) {
364 const Type *Ty = I.getType();
365 if (Ty->isFloatingPoint())
367 else if (Ty->isUnsigned())
373 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
374 void visitOr (User &I) { visitBinary(I, ISD::OR); }
375 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
376 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
377 void visitShr(User &I) {
378 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
381 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
382 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
383 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
384 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
385 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
386 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
387 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
389 void visitGetElementPtr(User &I);
390 void visitCast(User &I);
391 void visitSelect(User &I);
394 void visitMalloc(MallocInst &I);
395 void visitFree(FreeInst &I);
396 void visitAlloca(AllocaInst &I);
397 void visitLoad(LoadInst &I);
398 void visitStore(StoreInst &I);
399 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
400 void visitCall(CallInst &I);
402 void visitVAStart(CallInst &I);
403 void visitVAArg(VAArgInst &I);
404 void visitVAEnd(CallInst &I);
405 void visitVACopy(CallInst &I);
406 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
408 void visitMemIntrinsic(CallInst &I, unsigned Op);
410 void visitUserOp1(Instruction &I) {
411 assert(0 && "UserOp1 should not exist at instruction selection time!");
414 void visitUserOp2(Instruction &I) {
415 assert(0 && "UserOp2 should not exist at instruction selection time!");
419 } // end namespace llvm
421 void SelectionDAGLowering::visitRet(ReturnInst &I) {
422 if (I.getNumOperands() == 0) {
423 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
427 SDOperand Op1 = getValue(I.getOperand(0));
428 MVT::ValueType TmpVT;
430 switch (Op1.getValueType()) {
431 default: assert(0 && "Unknown value type!");
436 // If this is a machine where 32-bits is legal or expanded, promote to
437 // 32-bits, otherwise, promote to 64-bits.
438 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
439 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
443 // Extend integer types to result type.
444 if (I.getOperand(0)->getType()->isSigned())
445 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
447 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
452 break; // No extension needed!
455 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
458 void SelectionDAGLowering::visitBr(BranchInst &I) {
459 // Update machine-CFG edges.
460 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
462 // Figure out which block is immediately after the current one.
463 MachineBasicBlock *NextBlock = 0;
464 MachineFunction::iterator BBI = CurMBB;
465 if (++BBI != CurMBB->getParent()->end())
468 if (I.isUnconditional()) {
469 // If this is not a fall-through branch, emit the branch.
470 if (Succ0MBB != NextBlock)
471 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
472 DAG.getBasicBlock(Succ0MBB)));
474 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
476 SDOperand Cond = getValue(I.getCondition());
477 if (Succ1MBB == NextBlock) {
478 // If the condition is false, fall through. This means we should branch
479 // if the condition is true to Succ #0.
480 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
481 Cond, DAG.getBasicBlock(Succ0MBB)));
482 } else if (Succ0MBB == NextBlock) {
483 // If the condition is true, fall through. This means we should branch if
484 // the condition is false to Succ #1. Invert the condition first.
485 SDOperand True = DAG.getConstant(1, Cond.getValueType());
486 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
487 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
488 Cond, DAG.getBasicBlock(Succ1MBB)));
490 std::vector<SDOperand> Ops;
491 Ops.push_back(getRoot());
493 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
494 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
495 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
500 void SelectionDAGLowering::visitSub(User &I) {
502 if (I.getType()->isFloatingPoint()) {
503 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
504 if (CFP->isExactlyValue(-0.0)) {
505 SDOperand Op2 = getValue(I.getOperand(1));
506 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
509 visitBinary(I, ISD::FSUB);
511 visitBinary(I, ISD::SUB);
515 void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
516 SDOperand Op1 = getValue(I.getOperand(0));
517 SDOperand Op2 = getValue(I.getOperand(1));
520 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
522 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
525 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
526 ISD::CondCode UnsignedOpcode) {
527 SDOperand Op1 = getValue(I.getOperand(0));
528 SDOperand Op2 = getValue(I.getOperand(1));
529 ISD::CondCode Opcode = SignedOpcode;
530 if (I.getOperand(0)->getType()->isUnsigned())
531 Opcode = UnsignedOpcode;
532 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
535 void SelectionDAGLowering::visitSelect(User &I) {
536 SDOperand Cond = getValue(I.getOperand(0));
537 SDOperand TrueVal = getValue(I.getOperand(1));
538 SDOperand FalseVal = getValue(I.getOperand(2));
539 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
543 void SelectionDAGLowering::visitCast(User &I) {
544 SDOperand N = getValue(I.getOperand(0));
545 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
546 MVT::ValueType DestTy = TLI.getValueType(I.getType());
548 if (N.getValueType() == DestTy) {
549 setValue(&I, N); // noop cast.
550 } else if (DestTy == MVT::i1) {
551 // Cast to bool is a comparison against zero, not truncation to zero.
552 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
553 DAG.getConstantFP(0.0, N.getValueType());
554 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
555 } else if (isInteger(SrcTy)) {
556 if (isInteger(DestTy)) { // Int -> Int cast
557 if (DestTy < SrcTy) // Truncating cast?
558 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
559 else if (I.getOperand(0)->getType()->isSigned())
560 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
562 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
563 } else { // Int -> FP cast
564 if (I.getOperand(0)->getType()->isSigned())
565 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
567 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
570 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
571 if (isFloatingPoint(DestTy)) { // FP -> FP cast
572 if (DestTy < SrcTy) // Rounding cast?
573 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
575 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
576 } else { // FP -> Int cast.
577 if (I.getType()->isSigned())
578 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
580 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
585 void SelectionDAGLowering::visitGetElementPtr(User &I) {
586 SDOperand N = getValue(I.getOperand(0));
587 const Type *Ty = I.getOperand(0)->getType();
588 const Type *UIntPtrTy = TD.getIntPtrType();
590 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
593 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
594 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
597 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
598 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
599 getIntPtrConstant(Offset));
601 Ty = StTy->getElementType(Field);
603 Ty = cast<SequentialType>(Ty)->getElementType();
604 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
605 // N = N + Idx * ElementSize;
606 uint64_t ElementSize = TD.getTypeSize(Ty);
607 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
609 // If the index is smaller or larger than intptr_t, truncate or extend
611 if (IdxN.getValueType() < Scale.getValueType()) {
612 if (Idx->getType()->isSigned())
613 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
615 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
616 } else if (IdxN.getValueType() > Scale.getValueType())
617 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
619 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
620 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
627 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
628 // If this is a fixed sized alloca in the entry block of the function,
629 // allocate it statically on the stack.
630 if (FuncInfo.StaticAllocaMap.count(&I))
631 return; // getValue will auto-populate this.
633 const Type *Ty = I.getAllocatedType();
634 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
635 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
637 SDOperand AllocSize = getValue(I.getArraySize());
638 MVT::ValueType IntPtr = TLI.getPointerTy();
639 if (IntPtr < AllocSize.getValueType())
640 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
641 else if (IntPtr > AllocSize.getValueType())
642 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
644 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
645 getIntPtrConstant(TySize));
647 // Handle alignment. If the requested alignment is less than or equal to the
648 // stack alignment, ignore it and round the size of the allocation up to the
649 // stack alignment size. If the size is greater than the stack alignment, we
650 // note this in the DYNAMIC_STACKALLOC node.
651 unsigned StackAlign =
652 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
653 if (Align <= StackAlign) {
655 // Add SA-1 to the size.
656 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
657 getIntPtrConstant(StackAlign-1));
658 // Mask out the low bits for alignment purposes.
659 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
660 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
663 std::vector<MVT::ValueType> VTs;
664 VTs.push_back(AllocSize.getValueType());
665 VTs.push_back(MVT::Other);
666 std::vector<SDOperand> Ops;
667 Ops.push_back(getRoot());
668 Ops.push_back(AllocSize);
669 Ops.push_back(getIntPtrConstant(Align));
670 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
671 DAG.setRoot(setValue(&I, DSA).getValue(1));
673 // Inform the Frame Information that we have just allocated a variable-sized
675 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
679 void SelectionDAGLowering::visitLoad(LoadInst &I) {
680 SDOperand Ptr = getValue(I.getOperand(0));
686 // Do not serialize non-volatile loads against each other.
687 Root = DAG.getRoot();
690 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
691 DAG.getSrcValue(I.getOperand(0)));
695 DAG.setRoot(L.getValue(1));
697 PendingLoads.push_back(L.getValue(1));
701 void SelectionDAGLowering::visitStore(StoreInst &I) {
702 Value *SrcV = I.getOperand(0);
703 SDOperand Src = getValue(SrcV);
704 SDOperand Ptr = getValue(I.getOperand(1));
705 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
706 DAG.getSrcValue(I.getOperand(1))));
709 void SelectionDAGLowering::visitCall(CallInst &I) {
710 const char *RenameFn = 0;
712 if (Function *F = I.getCalledFunction())
714 switch (F->getIntrinsicID()) {
715 case 0: // Not an LLVM intrinsic.
716 if (F->getName() == "fabs" || F->getName() == "fabsf") {
717 if (I.getNumOperands() == 2 && // Basic sanity checks.
718 I.getOperand(1)->getType()->isFloatingPoint() &&
719 I.getType() == I.getOperand(1)->getType()) {
720 Tmp = getValue(I.getOperand(1));
721 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
725 else if (F->getName() == "sin" || F->getName() == "sinf") {
726 if (I.getNumOperands() == 2 && // Basic sanity checks.
727 I.getOperand(1)->getType()->isFloatingPoint() &&
728 I.getType() == I.getOperand(1)->getType()) {
729 Tmp = getValue(I.getOperand(1));
730 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
734 else if (F->getName() == "cos" || F->getName() == "cosf") {
735 if (I.getNumOperands() == 2 && // Basic sanity checks.
736 I.getOperand(1)->getType()->isFloatingPoint() &&
737 I.getType() == I.getOperand(1)->getType()) {
738 Tmp = getValue(I.getOperand(1));
739 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
744 case Intrinsic::vastart: visitVAStart(I); return;
745 case Intrinsic::vaend: visitVAEnd(I); return;
746 case Intrinsic::vacopy: visitVACopy(I); return;
747 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
748 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
750 case Intrinsic::setjmp:
751 RenameFn = "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
753 case Intrinsic::longjmp:
754 RenameFn = "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
756 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
757 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
758 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
760 case Intrinsic::readport:
761 case Intrinsic::readio: {
762 std::vector<MVT::ValueType> VTs;
763 VTs.push_back(TLI.getValueType(I.getType()));
764 VTs.push_back(MVT::Other);
765 std::vector<SDOperand> Ops;
766 Ops.push_back(getRoot());
767 Ops.push_back(getValue(I.getOperand(1)));
768 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
769 ISD::READPORT : ISD::READIO, VTs, Ops);
772 DAG.setRoot(Tmp.getValue(1));
775 case Intrinsic::writeport:
776 case Intrinsic::writeio:
777 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
778 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
779 getRoot(), getValue(I.getOperand(1)),
780 getValue(I.getOperand(2))));
782 case Intrinsic::dbg_stoppoint:
783 case Intrinsic::dbg_region_start:
784 case Intrinsic::dbg_region_end:
785 case Intrinsic::dbg_func_start:
786 case Intrinsic::dbg_declare:
787 if (I.getType() != Type::VoidTy)
788 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
791 case Intrinsic::isunordered:
792 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
793 getValue(I.getOperand(2)), ISD::SETUO));
796 case Intrinsic::sqrt:
797 setValue(&I, DAG.getNode(ISD::FSQRT,
798 getValue(I.getOperand(1)).getValueType(),
799 getValue(I.getOperand(1))));
802 case Intrinsic::pcmarker:
803 Tmp = getValue(I.getOperand(1));
804 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
806 case Intrinsic::cttz:
807 setValue(&I, DAG.getNode(ISD::CTTZ,
808 getValue(I.getOperand(1)).getValueType(),
809 getValue(I.getOperand(1))));
811 case Intrinsic::ctlz:
812 setValue(&I, DAG.getNode(ISD::CTLZ,
813 getValue(I.getOperand(1)).getValueType(),
814 getValue(I.getOperand(1))));
816 case Intrinsic::ctpop:
817 setValue(&I, DAG.getNode(ISD::CTPOP,
818 getValue(I.getOperand(1)).getValueType(),
819 getValue(I.getOperand(1))));
823 assert(0 && "This intrinsic is not implemented yet!");
829 Callee = getValue(I.getOperand(0));
831 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
832 std::vector<std::pair<SDOperand, const Type*> > Args;
834 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
835 Value *Arg = I.getOperand(i);
836 SDOperand ArgNode = getValue(Arg);
837 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
840 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
841 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
843 std::pair<SDOperand,SDOperand> Result =
844 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
845 I.isTailCall(), Callee, Args, DAG);
846 if (I.getType() != Type::VoidTy)
847 setValue(&I, Result.first);
848 DAG.setRoot(Result.second);
851 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
852 SDOperand Src = getValue(I.getOperand(0));
854 MVT::ValueType IntPtr = TLI.getPointerTy();
856 if (IntPtr < Src.getValueType())
857 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
858 else if (IntPtr > Src.getValueType())
859 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
861 // Scale the source by the type size.
862 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
863 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
864 Src, getIntPtrConstant(ElementSize));
866 std::vector<std::pair<SDOperand, const Type*> > Args;
867 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
869 std::pair<SDOperand,SDOperand> Result =
870 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
871 DAG.getExternalSymbol("malloc", IntPtr),
873 setValue(&I, Result.first); // Pointers always fit in registers
874 DAG.setRoot(Result.second);
877 void SelectionDAGLowering::visitFree(FreeInst &I) {
878 std::vector<std::pair<SDOperand, const Type*> > Args;
879 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
880 TLI.getTargetData().getIntPtrType()));
881 MVT::ValueType IntPtr = TLI.getPointerTy();
882 std::pair<SDOperand,SDOperand> Result =
883 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
884 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
885 DAG.setRoot(Result.second);
888 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
889 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
890 // instructions are special in various ways, which require special support to
891 // insert. The specified MachineInstr is created but not inserted into any
892 // basic blocks, and the scheduler passes ownership of it to this method.
893 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
894 MachineBasicBlock *MBB) {
895 std::cerr << "If a target marks an instruction with "
896 "'usesCustomDAGSchedInserter', it must implement "
897 "TargetLowering::InsertAtEndOfBasicBlock!\n";
902 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
903 SDOperand VAListP, Value *VAListV,
905 // We have no sane default behavior, just emit a useful error message and bail
907 std::cerr << "Variable arguments handling not implemented on this target!\n";
912 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
914 // Default to a noop.
918 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
919 SDOperand SrcP, Value *SrcV,
920 SDOperand DestP, Value *DestV,
922 // Default to copying the input list.
923 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
924 SrcP, DAG.getSrcValue(SrcV));
925 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
926 Val, DestP, DAG.getSrcValue(DestV));
930 std::pair<SDOperand,SDOperand>
931 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
932 const Type *ArgTy, SelectionDAG &DAG) {
933 // We have no sane default behavior, just emit a useful error message and bail
935 std::cerr << "Variable arguments handling not implemented on this target!\n";
937 return std::make_pair(SDOperand(), SDOperand());
941 void SelectionDAGLowering::visitVAStart(CallInst &I) {
942 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
943 I.getOperand(1), DAG));
946 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
947 std::pair<SDOperand,SDOperand> Result =
948 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
950 setValue(&I, Result.first);
951 DAG.setRoot(Result.second);
954 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
955 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
956 I.getOperand(1), DAG));
959 void SelectionDAGLowering::visitVACopy(CallInst &I) {
961 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
962 getValue(I.getOperand(1)), I.getOperand(1), DAG);
967 // It is always conservatively correct for llvm.returnaddress and
968 // llvm.frameaddress to return 0.
969 std::pair<SDOperand, SDOperand>
970 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
971 unsigned Depth, SelectionDAG &DAG) {
972 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
975 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
976 assert(0 && "LowerOperation not implemented for this target!");
981 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
982 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
983 std::pair<SDOperand,SDOperand> Result =
984 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
985 setValue(&I, Result.first);
986 DAG.setRoot(Result.second);
989 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
990 std::vector<SDOperand> Ops;
991 Ops.push_back(getRoot());
992 Ops.push_back(getValue(I.getOperand(1)));
993 Ops.push_back(getValue(I.getOperand(2)));
994 Ops.push_back(getValue(I.getOperand(3)));
995 Ops.push_back(getValue(I.getOperand(4)));
996 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
999 //===----------------------------------------------------------------------===//
1000 // SelectionDAGISel code
1001 //===----------------------------------------------------------------------===//
1003 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1004 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1007 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1008 // FIXME: we only modify the CFG to split critical edges. This
1009 // updates dom and loop info.
1013 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1014 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1015 RegMap = MF.getSSARegMap();
1016 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1018 // First pass, split all critical edges for PHI nodes with incoming values
1019 // that are constants, this way the load of the constant into a vreg will not
1020 // be placed into MBBs that are used some other way.
1021 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1023 for (BasicBlock::iterator BBI = BB->begin();
1024 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1025 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1026 if (isa<Constant>(PN->getIncomingValue(i)))
1027 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1030 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1032 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1033 SelectBasicBlock(I, MF, FuncInfo);
1039 SDOperand SelectionDAGISel::
1040 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1041 SDOperand Op = SDL.getValue(V);
1042 assert((Op.getOpcode() != ISD::CopyFromReg ||
1043 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1044 "Copy from a reg to the same reg!");
1046 // If this type is not legal, we must make sure to not create an invalid
1048 MVT::ValueType SrcVT = Op.getValueType();
1049 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1050 SelectionDAG &DAG = SDL.DAG;
1051 if (SrcVT == DestVT) {
1052 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1053 } else if (SrcVT < DestVT) {
1054 // The src value is promoted to the register.
1055 if (MVT::isFloatingPoint(SrcVT))
1056 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1058 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1059 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1061 // The src value is expanded into multiple registers.
1062 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1063 Op, DAG.getConstant(0, MVT::i32));
1064 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1065 Op, DAG.getConstant(1, MVT::i32));
1066 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1067 return DAG.getCopyToReg(Op, Reg+1, Hi);
1071 /// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
1072 /// single basic block, return that block. Otherwise, return a null pointer.
1073 static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
1074 if (A->use_empty()) return 0;
1075 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
1076 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
1078 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
1079 return 0; // Disagreement among the users?
1081 // Okay, there is a single BB user. Only permit this optimization if this is
1082 // the entry block, otherwise, we might sink argument loads into loops and
1083 // stuff. Later, when we have global instruction selection, this won't be an
1085 if (BB == BB->getParent()->begin())
1090 void SelectionDAGISel::
1091 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1092 std::vector<SDOperand> &UnorderedChains) {
1093 // If this is the entry block, emit arguments.
1094 Function &F = *BB->getParent();
1095 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1097 if (BB == &F.front()) {
1098 SDOperand OldRoot = SDL.DAG.getRoot();
1100 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1102 // If there were side effects accessing the argument list, do not do
1103 // anything special.
1104 if (OldRoot != SDL.DAG.getRoot()) {
1106 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1108 if (!AI->use_empty()) {
1109 SDL.setValue(AI, Args[a]);
1112 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1113 UnorderedChains.push_back(Copy);
1116 // Otherwise, if any argument is only accessed in a single basic block,
1117 // emit that argument only to that basic block.
1119 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1121 if (!AI->use_empty()) {
1122 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
1123 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
1124 std::make_pair(AI, a)));
1126 SDL.setValue(AI, Args[a]);
1128 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1129 UnorderedChains.push_back(Copy);
1134 // Next, if the function has live ins that need to be copied into vregs,
1135 // emit the copies now, into the top of the block.
1136 MachineFunction &MF = SDL.DAG.getMachineFunction();
1137 if (MF.livein_begin() != MF.livein_end()) {
1138 SSARegMap *RegMap = MF.getSSARegMap();
1139 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1140 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1141 E = MF.livein_end(); LI != E; ++LI)
1143 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1144 LI->first, RegMap->getRegClass(LI->second));
1147 // Finally, if the target has anything special to do, allow it to do so.
1148 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1151 // See if there are any block-local arguments that need to be emitted in this
1154 if (!FuncInfo.BlockLocalArguments.empty()) {
1155 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
1156 FuncInfo.BlockLocalArguments.lower_bound(BB);
1157 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
1158 // Lower the arguments into this block.
1159 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1161 // Set up the value mapping for the local arguments.
1162 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
1164 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
1166 // Any dead arguments will just be ignored here.
1172 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1173 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1174 FunctionLoweringInfo &FuncInfo) {
1175 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1177 std::vector<SDOperand> UnorderedChains;
1179 // Lower any arguments needed in this block.
1180 LowerArguments(LLVMBB, SDL, UnorderedChains);
1182 BB = FuncInfo.MBBMap[LLVMBB];
1183 SDL.setCurrentBasicBlock(BB);
1185 // Lower all of the non-terminator instructions.
1186 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1190 // Ensure that all instructions which are used outside of their defining
1191 // blocks are available as virtual registers.
1192 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1193 if (!I->use_empty() && !isa<PHINode>(I)) {
1194 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1195 if (VMI != FuncInfo.ValueMap.end())
1196 UnorderedChains.push_back(
1197 CopyValueToVirtualRegister(SDL, I, VMI->second));
1200 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1201 // ensure constants are generated when needed. Remember the virtual registers
1202 // that need to be added to the Machine PHI nodes as input. We cannot just
1203 // directly add them, because expansion might result in multiple MBB's for one
1204 // BB. As such, the start of the BB might correspond to a different MBB than
1208 // Emit constants only once even if used by multiple PHI nodes.
1209 std::map<Constant*, unsigned> ConstantsOut;
1211 // Check successor nodes PHI nodes that expect a constant to be available from
1213 TerminatorInst *TI = LLVMBB->getTerminator();
1214 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1215 BasicBlock *SuccBB = TI->getSuccessor(succ);
1216 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1219 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1220 // nodes and Machine PHI nodes, but the incoming operands have not been
1222 for (BasicBlock::iterator I = SuccBB->begin();
1223 (PN = dyn_cast<PHINode>(I)); ++I)
1224 if (!PN->use_empty()) {
1226 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1227 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1228 unsigned &RegOut = ConstantsOut[C];
1230 RegOut = FuncInfo.CreateRegForValue(C);
1231 UnorderedChains.push_back(
1232 CopyValueToVirtualRegister(SDL, C, RegOut));
1236 Reg = FuncInfo.ValueMap[PHIOp];
1238 assert(isa<AllocaInst>(PHIOp) &&
1239 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1240 "Didn't codegen value into a register!??");
1241 Reg = FuncInfo.CreateRegForValue(PHIOp);
1242 UnorderedChains.push_back(
1243 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1247 // Remember that this register needs to added to the machine PHI node as
1248 // the input for this MBB.
1249 unsigned NumElements =
1250 TLI.getNumElements(TLI.getValueType(PN->getType()));
1251 for (unsigned i = 0, e = NumElements; i != e; ++i)
1252 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1255 ConstantsOut.clear();
1257 // Turn all of the unordered chains into one factored node.
1258 if (!UnorderedChains.empty()) {
1259 UnorderedChains.push_back(SDL.getRoot());
1260 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1263 // Lower the terminator after the copies are emitted.
1264 SDL.visit(*LLVMBB->getTerminator());
1266 // Make sure the root of the DAG is up-to-date.
1267 DAG.setRoot(SDL.getRoot());
1270 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1271 FunctionLoweringInfo &FuncInfo) {
1272 SelectionDAG DAG(TLI, MF);
1274 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1276 // First step, lower LLVM code to some DAG. This DAG may use operations and
1277 // types that are not supported by the target.
1278 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1280 // Run the DAG combiner in pre-legalize mode.
1283 DEBUG(std::cerr << "Lowered selection DAG:\n");
1286 // Second step, hack on the DAG until it only uses operations and types that
1287 // the target supports.
1290 DEBUG(std::cerr << "Legalized selection DAG:\n");
1293 // Run the DAG combiner in post-legalize mode.
1296 if (ViewDAGs) DAG.viewGraph();
1298 // Third, instruction select all of the operations to machine code, adding the
1299 // code to the MachineBasicBlock.
1300 InstructionSelectBasicBlock(DAG);
1302 DEBUG(std::cerr << "Selected machine code:\n");
1305 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1306 // PHI nodes in successors.
1307 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1308 MachineInstr *PHI = PHINodesToUpdate[i].first;
1309 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1310 "This is not a machine PHI node that we are updating!");
1311 PHI->addRegOperand(PHINodesToUpdate[i].second);
1312 PHI->addMachineBasicBlockOperand(BB);
1315 // Finally, add the CFG edges from the last selected MBB to the successor
1317 TerminatorInst *TI = LLVMBB->getTerminator();
1318 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1319 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1320 BB->addSuccessor(Succ0MBB);