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 unsigned MakeReg(MVT::ValueType VT) {
76 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
79 unsigned CreateRegForValue(const Value *V) {
80 MVT::ValueType VT = TLI.getValueType(V->getType());
81 // The common case is that we will only create one register for this
82 // value. If we have that case, create and return the virtual register.
83 unsigned NV = TLI.getNumElements(VT);
85 // If we are promoting this value, pick the next largest supported type.
86 return MakeReg(TLI.getTypeToTransformTo(VT));
89 // If this value is represented with multiple target registers, make sure
90 // to create enough consequtive registers of the right (smaller) type.
91 unsigned NT = VT-1; // Find the type to use.
92 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
95 unsigned R = MakeReg((MVT::ValueType)NT);
96 for (unsigned i = 1; i != NV; ++i)
97 MakeReg((MVT::ValueType)NT);
101 unsigned InitializeRegForValue(const Value *V) {
102 unsigned &R = ValueMap[V];
103 assert(R == 0 && "Already initialized this value register!");
104 return R = CreateRegForValue(V);
109 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
110 /// PHI nodes or outside of the basic block that defines it.
111 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
112 if (isa<PHINode>(I)) return true;
113 BasicBlock *BB = I->getParent();
114 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
115 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
120 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
121 /// entry block, return true.
122 static bool isOnlyUsedInEntryBlock(Argument *A) {
123 BasicBlock *Entry = A->getParent()->begin();
124 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
125 if (cast<Instruction>(*UI)->getParent() != Entry)
126 return false; // Use not in entry block.
130 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
131 Function &fn, MachineFunction &mf)
132 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
134 // Create a vreg for each argument register that is not dead and is used
135 // outside of the entry block for the function.
136 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
138 if (!isOnlyUsedInEntryBlock(AI))
139 InitializeRegForValue(AI);
141 // Initialize the mapping of values to registers. This is only set up for
142 // instruction values that are used outside of the block that defines
144 Function::iterator BB = Fn.begin(), EB = Fn.end();
145 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
146 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
147 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
148 const Type *Ty = AI->getAllocatedType();
149 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
151 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
154 // If the alignment of the value is smaller than the size of the value,
155 // and if the size of the value is particularly small (<= 8 bytes),
156 // round up to the size of the value for potentially better performance.
158 // FIXME: This could be made better with a preferred alignment hook in
159 // TargetData. It serves primarily to 8-byte align doubles for X86.
160 if (Align < TySize && TySize <= 8) Align = TySize;
161 TySize *= CUI->getValue(); // Get total allocated size.
162 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
163 StaticAllocaMap[AI] =
164 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
167 for (; BB != EB; ++BB)
168 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
169 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
170 if (!isa<AllocaInst>(I) ||
171 !StaticAllocaMap.count(cast<AllocaInst>(I)))
172 InitializeRegForValue(I);
174 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
175 // also creates the initial PHI MachineInstrs, though none of the input
176 // operands are populated.
177 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
178 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
180 MF.getBasicBlockList().push_back(MBB);
182 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
185 for (BasicBlock::iterator I = BB->begin();
186 (PN = dyn_cast<PHINode>(I)); ++I)
187 if (!PN->use_empty()) {
188 unsigned NumElements =
189 TLI.getNumElements(TLI.getValueType(PN->getType()));
190 unsigned PHIReg = ValueMap[PN];
191 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
192 for (unsigned i = 0; i != NumElements; ++i)
193 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
200 //===----------------------------------------------------------------------===//
201 /// SelectionDAGLowering - This is the common target-independent lowering
202 /// implementation that is parameterized by a TargetLowering object.
203 /// Also, targets can overload any lowering method.
206 class SelectionDAGLowering {
207 MachineBasicBlock *CurMBB;
209 std::map<const Value*, SDOperand> NodeMap;
211 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
212 /// them up and then emit token factor nodes when possible. This allows us to
213 /// get simple disambiguation between loads without worrying about alias
215 std::vector<SDOperand> PendingLoads;
218 // TLI - This is information that describes the available target features we
219 // need for lowering. This indicates when operations are unavailable,
220 // implemented with a libcall, etc.
223 const TargetData &TD;
225 /// FuncInfo - Information about the function as a whole.
227 FunctionLoweringInfo &FuncInfo;
229 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
230 FunctionLoweringInfo &funcinfo)
231 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
235 /// getRoot - Return the current virtual root of the Selection DAG.
237 SDOperand getRoot() {
238 if (PendingLoads.empty())
239 return DAG.getRoot();
241 if (PendingLoads.size() == 1) {
242 SDOperand Root = PendingLoads[0];
244 PendingLoads.clear();
248 // Otherwise, we have to make a token factor node.
249 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
250 PendingLoads.clear();
255 void visit(Instruction &I) { visit(I.getOpcode(), I); }
257 void visit(unsigned Opcode, User &I) {
259 default: assert(0 && "Unknown instruction type encountered!");
261 // Build the switch statement using the Instruction.def file.
262 #define HANDLE_INST(NUM, OPCODE, CLASS) \
263 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
264 #include "llvm/Instruction.def"
268 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
271 SDOperand getIntPtrConstant(uint64_t Val) {
272 return DAG.getConstant(Val, TLI.getPointerTy());
275 SDOperand getValue(const Value *V) {
276 SDOperand &N = NodeMap[V];
279 MVT::ValueType VT = TLI.getValueType(V->getType());
280 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
281 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
282 visit(CE->getOpcode(), *CE);
283 assert(N.Val && "visit didn't populate the ValueMap!");
285 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
286 return N = DAG.getGlobalAddress(GV, VT);
287 } else if (isa<ConstantPointerNull>(C)) {
288 return N = DAG.getConstant(0, TLI.getPointerTy());
289 } else if (isa<UndefValue>(C)) {
290 return N = DAG.getNode(ISD::UNDEF, VT);
291 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
292 return N = DAG.getConstantFP(CFP->getValue(), VT);
294 // Canonicalize all constant ints to be unsigned.
295 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
298 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
299 std::map<const AllocaInst*, int>::iterator SI =
300 FuncInfo.StaticAllocaMap.find(AI);
301 if (SI != FuncInfo.StaticAllocaMap.end())
302 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
305 std::map<const Value*, unsigned>::const_iterator VMI =
306 FuncInfo.ValueMap.find(V);
307 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
309 unsigned InReg = VMI->second;
311 // If this type is not legal, make it so now.
312 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
314 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
316 // Source must be expanded. This input value is actually coming from the
317 // register pair VMI->second and VMI->second+1.
318 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
319 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
321 if (DestVT > VT) { // Promotion case
322 if (MVT::isFloatingPoint(VT))
323 N = DAG.getNode(ISD::FP_ROUND, VT, N);
325 N = DAG.getNode(ISD::TRUNCATE, VT, N);
332 const SDOperand &setValue(const Value *V, SDOperand NewN) {
333 SDOperand &N = NodeMap[V];
334 assert(N.Val == 0 && "Already set a value for this node!");
338 // Terminator instructions.
339 void visitRet(ReturnInst &I);
340 void visitBr(BranchInst &I);
341 void visitUnreachable(UnreachableInst &I) { /* noop */ }
343 // These all get lowered before this pass.
344 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
345 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
346 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
349 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
350 void visitAdd(User &I) {
351 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FADD : ISD::ADD);
353 void visitSub(User &I);
354 void visitMul(User &I) {
355 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FMUL : ISD::MUL);
357 void visitDiv(User &I) {
359 const Type *Ty = I.getType();
360 if (Ty->isFloatingPoint())
362 else if (Ty->isUnsigned())
368 void visitRem(User &I) {
370 const Type *Ty = I.getType();
371 if (Ty->isFloatingPoint())
373 else if (Ty->isUnsigned())
379 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
380 void visitOr (User &I) { visitBinary(I, ISD::OR); }
381 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
382 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
383 void visitShr(User &I) {
384 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
387 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
388 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
389 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
390 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
391 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
392 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
393 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
395 void visitGetElementPtr(User &I);
396 void visitCast(User &I);
397 void visitSelect(User &I);
400 void visitMalloc(MallocInst &I);
401 void visitFree(FreeInst &I);
402 void visitAlloca(AllocaInst &I);
403 void visitLoad(LoadInst &I);
404 void visitStore(StoreInst &I);
405 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
406 void visitCall(CallInst &I);
408 void visitVAStart(CallInst &I);
409 void visitVAArg(VAArgInst &I);
410 void visitVAEnd(CallInst &I);
411 void visitVACopy(CallInst &I);
412 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
414 void visitMemIntrinsic(CallInst &I, unsigned Op);
416 void visitUserOp1(Instruction &I) {
417 assert(0 && "UserOp1 should not exist at instruction selection time!");
420 void visitUserOp2(Instruction &I) {
421 assert(0 && "UserOp2 should not exist at instruction selection time!");
425 } // end namespace llvm
427 void SelectionDAGLowering::visitRet(ReturnInst &I) {
428 if (I.getNumOperands() == 0) {
429 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
433 SDOperand Op1 = getValue(I.getOperand(0));
434 MVT::ValueType TmpVT;
436 switch (Op1.getValueType()) {
437 default: assert(0 && "Unknown value type!");
442 // If this is a machine where 32-bits is legal or expanded, promote to
443 // 32-bits, otherwise, promote to 64-bits.
444 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
445 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
449 // Extend integer types to result type.
450 if (I.getOperand(0)->getType()->isSigned())
451 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
453 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
458 break; // No extension needed!
460 // Allow targets to lower this further to meet ABI requirements
461 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
464 void SelectionDAGLowering::visitBr(BranchInst &I) {
465 // Update machine-CFG edges.
466 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
468 // Figure out which block is immediately after the current one.
469 MachineBasicBlock *NextBlock = 0;
470 MachineFunction::iterator BBI = CurMBB;
471 if (++BBI != CurMBB->getParent()->end())
474 if (I.isUnconditional()) {
475 // If this is not a fall-through branch, emit the branch.
476 if (Succ0MBB != NextBlock)
477 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
478 DAG.getBasicBlock(Succ0MBB)));
480 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
482 SDOperand Cond = getValue(I.getCondition());
483 if (Succ1MBB == NextBlock) {
484 // If the condition is false, fall through. This means we should branch
485 // if the condition is true to Succ #0.
486 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
487 Cond, DAG.getBasicBlock(Succ0MBB)));
488 } else if (Succ0MBB == NextBlock) {
489 // If the condition is true, fall through. This means we should branch if
490 // the condition is false to Succ #1. Invert the condition first.
491 SDOperand True = DAG.getConstant(1, Cond.getValueType());
492 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
493 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
494 Cond, DAG.getBasicBlock(Succ1MBB)));
496 std::vector<SDOperand> Ops;
497 Ops.push_back(getRoot());
499 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
500 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
501 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
506 void SelectionDAGLowering::visitSub(User &I) {
508 if (I.getType()->isFloatingPoint()) {
509 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
510 if (CFP->isExactlyValue(-0.0)) {
511 SDOperand Op2 = getValue(I.getOperand(1));
512 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
515 visitBinary(I, ISD::FSUB);
517 visitBinary(I, ISD::SUB);
521 void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
522 SDOperand Op1 = getValue(I.getOperand(0));
523 SDOperand Op2 = getValue(I.getOperand(1));
526 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
528 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
531 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
532 ISD::CondCode UnsignedOpcode) {
533 SDOperand Op1 = getValue(I.getOperand(0));
534 SDOperand Op2 = getValue(I.getOperand(1));
535 ISD::CondCode Opcode = SignedOpcode;
536 if (I.getOperand(0)->getType()->isUnsigned())
537 Opcode = UnsignedOpcode;
538 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
541 void SelectionDAGLowering::visitSelect(User &I) {
542 SDOperand Cond = getValue(I.getOperand(0));
543 SDOperand TrueVal = getValue(I.getOperand(1));
544 SDOperand FalseVal = getValue(I.getOperand(2));
545 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
549 void SelectionDAGLowering::visitCast(User &I) {
550 SDOperand N = getValue(I.getOperand(0));
551 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
552 MVT::ValueType DestTy = TLI.getValueType(I.getType());
554 if (N.getValueType() == DestTy) {
555 setValue(&I, N); // noop cast.
556 } else if (DestTy == MVT::i1) {
557 // Cast to bool is a comparison against zero, not truncation to zero.
558 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
559 DAG.getConstantFP(0.0, N.getValueType());
560 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
561 } else if (isInteger(SrcTy)) {
562 if (isInteger(DestTy)) { // Int -> Int cast
563 if (DestTy < SrcTy) // Truncating cast?
564 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
565 else if (I.getOperand(0)->getType()->isSigned())
566 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
568 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
569 } else { // Int -> FP cast
570 if (I.getOperand(0)->getType()->isSigned())
571 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
573 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
576 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
577 if (isFloatingPoint(DestTy)) { // FP -> FP cast
578 if (DestTy < SrcTy) // Rounding cast?
579 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
581 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
582 } else { // FP -> Int cast.
583 if (I.getType()->isSigned())
584 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
586 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
591 void SelectionDAGLowering::visitGetElementPtr(User &I) {
592 SDOperand N = getValue(I.getOperand(0));
593 const Type *Ty = I.getOperand(0)->getType();
594 const Type *UIntPtrTy = TD.getIntPtrType();
596 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
599 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
600 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
603 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
604 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
605 getIntPtrConstant(Offset));
607 Ty = StTy->getElementType(Field);
609 Ty = cast<SequentialType>(Ty)->getElementType();
610 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
611 // N = N + Idx * ElementSize;
612 uint64_t ElementSize = TD.getTypeSize(Ty);
613 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
615 // If the index is smaller or larger than intptr_t, truncate or extend
617 if (IdxN.getValueType() < Scale.getValueType()) {
618 if (Idx->getType()->isSigned())
619 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
621 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
622 } else if (IdxN.getValueType() > Scale.getValueType())
623 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
625 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
626 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
633 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
634 // If this is a fixed sized alloca in the entry block of the function,
635 // allocate it statically on the stack.
636 if (FuncInfo.StaticAllocaMap.count(&I))
637 return; // getValue will auto-populate this.
639 const Type *Ty = I.getAllocatedType();
640 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
641 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
644 SDOperand AllocSize = getValue(I.getArraySize());
645 MVT::ValueType IntPtr = TLI.getPointerTy();
646 if (IntPtr < AllocSize.getValueType())
647 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
648 else if (IntPtr > AllocSize.getValueType())
649 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
651 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
652 getIntPtrConstant(TySize));
654 // Handle alignment. If the requested alignment is less than or equal to the
655 // stack alignment, ignore it and round the size of the allocation up to the
656 // stack alignment size. If the size is greater than the stack alignment, we
657 // note this in the DYNAMIC_STACKALLOC node.
658 unsigned StackAlign =
659 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
660 if (Align <= StackAlign) {
662 // Add SA-1 to the size.
663 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
664 getIntPtrConstant(StackAlign-1));
665 // Mask out the low bits for alignment purposes.
666 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
667 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
670 std::vector<MVT::ValueType> VTs;
671 VTs.push_back(AllocSize.getValueType());
672 VTs.push_back(MVT::Other);
673 std::vector<SDOperand> Ops;
674 Ops.push_back(getRoot());
675 Ops.push_back(AllocSize);
676 Ops.push_back(getIntPtrConstant(Align));
677 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
678 DAG.setRoot(setValue(&I, DSA).getValue(1));
680 // Inform the Frame Information that we have just allocated a variable-sized
682 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
686 void SelectionDAGLowering::visitLoad(LoadInst &I) {
687 SDOperand Ptr = getValue(I.getOperand(0));
693 // Do not serialize non-volatile loads against each other.
694 Root = DAG.getRoot();
697 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
698 DAG.getSrcValue(I.getOperand(0)));
702 DAG.setRoot(L.getValue(1));
704 PendingLoads.push_back(L.getValue(1));
708 void SelectionDAGLowering::visitStore(StoreInst &I) {
709 Value *SrcV = I.getOperand(0);
710 SDOperand Src = getValue(SrcV);
711 SDOperand Ptr = getValue(I.getOperand(1));
712 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
713 DAG.getSrcValue(I.getOperand(1))));
716 void SelectionDAGLowering::visitCall(CallInst &I) {
717 const char *RenameFn = 0;
719 if (Function *F = I.getCalledFunction())
721 switch (F->getIntrinsicID()) {
722 case 0: // Not an LLVM intrinsic.
723 if (F->getName() == "fabs" || F->getName() == "fabsf") {
724 if (I.getNumOperands() == 2 && // Basic sanity checks.
725 I.getOperand(1)->getType()->isFloatingPoint() &&
726 I.getType() == I.getOperand(1)->getType()) {
727 Tmp = getValue(I.getOperand(1));
728 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
732 else if (F->getName() == "sin" || F->getName() == "sinf") {
733 if (I.getNumOperands() == 2 && // Basic sanity checks.
734 I.getOperand(1)->getType()->isFloatingPoint() &&
735 I.getType() == I.getOperand(1)->getType()) {
736 Tmp = getValue(I.getOperand(1));
737 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
741 else if (F->getName() == "cos" || F->getName() == "cosf") {
742 if (I.getNumOperands() == 2 && // Basic sanity checks.
743 I.getOperand(1)->getType()->isFloatingPoint() &&
744 I.getType() == I.getOperand(1)->getType()) {
745 Tmp = getValue(I.getOperand(1));
746 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
751 case Intrinsic::vastart: visitVAStart(I); return;
752 case Intrinsic::vaend: visitVAEnd(I); return;
753 case Intrinsic::vacopy: visitVACopy(I); return;
754 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
755 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
757 case Intrinsic::setjmp:
758 RenameFn = "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
760 case Intrinsic::longjmp:
761 RenameFn = "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
763 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
764 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
765 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
767 case Intrinsic::readport:
768 case Intrinsic::readio: {
769 std::vector<MVT::ValueType> VTs;
770 VTs.push_back(TLI.getValueType(I.getType()));
771 VTs.push_back(MVT::Other);
772 std::vector<SDOperand> Ops;
773 Ops.push_back(getRoot());
774 Ops.push_back(getValue(I.getOperand(1)));
775 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
776 ISD::READPORT : ISD::READIO, VTs, Ops);
779 DAG.setRoot(Tmp.getValue(1));
782 case Intrinsic::writeport:
783 case Intrinsic::writeio:
784 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
785 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
786 getRoot(), getValue(I.getOperand(1)),
787 getValue(I.getOperand(2))));
789 case Intrinsic::dbg_stoppoint:
790 case Intrinsic::dbg_region_start:
791 case Intrinsic::dbg_region_end:
792 case Intrinsic::dbg_func_start:
793 case Intrinsic::dbg_declare:
794 if (I.getType() != Type::VoidTy)
795 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
798 case Intrinsic::isunordered:
799 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
800 getValue(I.getOperand(2)), ISD::SETUO));
803 case Intrinsic::sqrt:
804 setValue(&I, DAG.getNode(ISD::FSQRT,
805 getValue(I.getOperand(1)).getValueType(),
806 getValue(I.getOperand(1))));
809 case Intrinsic::pcmarker:
810 Tmp = getValue(I.getOperand(1));
811 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
813 case Intrinsic::cttz:
814 setValue(&I, DAG.getNode(ISD::CTTZ,
815 getValue(I.getOperand(1)).getValueType(),
816 getValue(I.getOperand(1))));
818 case Intrinsic::ctlz:
819 setValue(&I, DAG.getNode(ISD::CTLZ,
820 getValue(I.getOperand(1)).getValueType(),
821 getValue(I.getOperand(1))));
823 case Intrinsic::ctpop:
824 setValue(&I, DAG.getNode(ISD::CTPOP,
825 getValue(I.getOperand(1)).getValueType(),
826 getValue(I.getOperand(1))));
830 assert(0 && "This intrinsic is not implemented yet!");
836 Callee = getValue(I.getOperand(0));
838 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
839 std::vector<std::pair<SDOperand, const Type*> > Args;
841 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
842 Value *Arg = I.getOperand(i);
843 SDOperand ArgNode = getValue(Arg);
844 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
847 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
848 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
850 std::pair<SDOperand,SDOperand> Result =
851 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
852 I.isTailCall(), Callee, Args, DAG);
853 if (I.getType() != Type::VoidTy)
854 setValue(&I, Result.first);
855 DAG.setRoot(Result.second);
858 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
859 SDOperand Src = getValue(I.getOperand(0));
861 MVT::ValueType IntPtr = TLI.getPointerTy();
863 if (IntPtr < Src.getValueType())
864 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
865 else if (IntPtr > Src.getValueType())
866 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
868 // Scale the source by the type size.
869 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
870 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
871 Src, getIntPtrConstant(ElementSize));
873 std::vector<std::pair<SDOperand, const Type*> > Args;
874 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
876 std::pair<SDOperand,SDOperand> Result =
877 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
878 DAG.getExternalSymbol("malloc", IntPtr),
880 setValue(&I, Result.first); // Pointers always fit in registers
881 DAG.setRoot(Result.second);
884 void SelectionDAGLowering::visitFree(FreeInst &I) {
885 std::vector<std::pair<SDOperand, const Type*> > Args;
886 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
887 TLI.getTargetData().getIntPtrType()));
888 MVT::ValueType IntPtr = TLI.getPointerTy();
889 std::pair<SDOperand,SDOperand> Result =
890 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
891 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
892 DAG.setRoot(Result.second);
895 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
896 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
897 // instructions are special in various ways, which require special support to
898 // insert. The specified MachineInstr is created but not inserted into any
899 // basic blocks, and the scheduler passes ownership of it to this method.
900 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
901 MachineBasicBlock *MBB) {
902 std::cerr << "If a target marks an instruction with "
903 "'usesCustomDAGSchedInserter', it must implement "
904 "TargetLowering::InsertAtEndOfBasicBlock!\n";
909 SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
911 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
914 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
915 SDOperand VAListP, Value *VAListV,
917 // We have no sane default behavior, just emit a useful error message and bail
919 std::cerr << "Variable arguments handling not implemented on this target!\n";
924 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
926 // Default to a noop.
930 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
931 SDOperand SrcP, Value *SrcV,
932 SDOperand DestP, Value *DestV,
934 // Default to copying the input list.
935 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
936 SrcP, DAG.getSrcValue(SrcV));
937 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
938 Val, DestP, DAG.getSrcValue(DestV));
942 std::pair<SDOperand,SDOperand>
943 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
944 const Type *ArgTy, SelectionDAG &DAG) {
945 // We have no sane default behavior, just emit a useful error message and bail
947 std::cerr << "Variable arguments handling not implemented on this target!\n";
949 return std::make_pair(SDOperand(), SDOperand());
953 void SelectionDAGLowering::visitVAStart(CallInst &I) {
954 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
955 I.getOperand(1), DAG));
958 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
959 std::pair<SDOperand,SDOperand> Result =
960 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
962 setValue(&I, Result.first);
963 DAG.setRoot(Result.second);
966 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
967 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
968 I.getOperand(1), DAG));
971 void SelectionDAGLowering::visitVACopy(CallInst &I) {
973 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
974 getValue(I.getOperand(1)), I.getOperand(1), DAG);
979 // It is always conservatively correct for llvm.returnaddress and
980 // llvm.frameaddress to return 0.
981 std::pair<SDOperand, SDOperand>
982 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
983 unsigned Depth, SelectionDAG &DAG) {
984 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
987 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
988 assert(0 && "LowerOperation not implemented for this target!");
993 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
994 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
995 std::pair<SDOperand,SDOperand> Result =
996 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
997 setValue(&I, Result.first);
998 DAG.setRoot(Result.second);
1001 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1002 std::vector<SDOperand> Ops;
1003 Ops.push_back(getRoot());
1004 Ops.push_back(getValue(I.getOperand(1)));
1005 Ops.push_back(getValue(I.getOperand(2)));
1006 Ops.push_back(getValue(I.getOperand(3)));
1007 Ops.push_back(getValue(I.getOperand(4)));
1008 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1011 //===----------------------------------------------------------------------===//
1012 // SelectionDAGISel code
1013 //===----------------------------------------------------------------------===//
1015 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1016 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1019 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1020 // FIXME: we only modify the CFG to split critical edges. This
1021 // updates dom and loop info.
1025 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1026 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1027 RegMap = MF.getSSARegMap();
1028 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1030 // First pass, split all critical edges for PHI nodes with incoming values
1031 // that are constants, this way the load of the constant into a vreg will not
1032 // be placed into MBBs that are used some other way.
1033 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1035 for (BasicBlock::iterator BBI = BB->begin();
1036 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1037 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1038 if (isa<Constant>(PN->getIncomingValue(i)))
1039 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1042 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1044 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1045 SelectBasicBlock(I, MF, FuncInfo);
1051 SDOperand SelectionDAGISel::
1052 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1053 SDOperand Op = SDL.getValue(V);
1054 assert((Op.getOpcode() != ISD::CopyFromReg ||
1055 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1056 "Copy from a reg to the same reg!");
1058 // If this type is not legal, we must make sure to not create an invalid
1060 MVT::ValueType SrcVT = Op.getValueType();
1061 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1062 SelectionDAG &DAG = SDL.DAG;
1063 if (SrcVT == DestVT) {
1064 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1065 } else if (SrcVT < DestVT) {
1066 // The src value is promoted to the register.
1067 if (MVT::isFloatingPoint(SrcVT))
1068 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1070 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1071 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1073 // The src value is expanded into multiple registers.
1074 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1075 Op, DAG.getConstant(0, MVT::i32));
1076 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1077 Op, DAG.getConstant(1, MVT::i32));
1078 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1079 return DAG.getCopyToReg(Op, Reg+1, Hi);
1083 void SelectionDAGISel::
1084 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1085 std::vector<SDOperand> &UnorderedChains) {
1086 // If this is the entry block, emit arguments.
1087 Function &F = *BB->getParent();
1088 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1089 SDOperand OldRoot = SDL.DAG.getRoot();
1090 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1093 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1095 if (!AI->use_empty()) {
1096 SDL.setValue(AI, Args[a]);
1098 // If this argument is live outside of the entry block, insert a copy from
1099 // whereever we got it to the vreg that other BB's will reference it as.
1100 if (FuncInfo.ValueMap.count(AI)) {
1102 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1103 UnorderedChains.push_back(Copy);
1107 // Next, if the function has live ins that need to be copied into vregs,
1108 // emit the copies now, into the top of the block.
1109 MachineFunction &MF = SDL.DAG.getMachineFunction();
1110 if (MF.livein_begin() != MF.livein_end()) {
1111 SSARegMap *RegMap = MF.getSSARegMap();
1112 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1113 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1114 E = MF.livein_end(); LI != E; ++LI)
1116 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1117 LI->first, RegMap->getRegClass(LI->second));
1120 // Finally, if the target has anything special to do, allow it to do so.
1121 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1125 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1126 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1127 FunctionLoweringInfo &FuncInfo) {
1128 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1130 std::vector<SDOperand> UnorderedChains;
1132 // Lower any arguments needed in this block if this is the entry block.
1133 if (LLVMBB == &LLVMBB->getParent()->front())
1134 LowerArguments(LLVMBB, SDL, UnorderedChains);
1136 BB = FuncInfo.MBBMap[LLVMBB];
1137 SDL.setCurrentBasicBlock(BB);
1139 // Lower all of the non-terminator instructions.
1140 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1144 // Ensure that all instructions which are used outside of their defining
1145 // blocks are available as virtual registers.
1146 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1147 if (!I->use_empty() && !isa<PHINode>(I)) {
1148 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1149 if (VMI != FuncInfo.ValueMap.end())
1150 UnorderedChains.push_back(
1151 CopyValueToVirtualRegister(SDL, I, VMI->second));
1154 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1155 // ensure constants are generated when needed. Remember the virtual registers
1156 // that need to be added to the Machine PHI nodes as input. We cannot just
1157 // directly add them, because expansion might result in multiple MBB's for one
1158 // BB. As such, the start of the BB might correspond to a different MBB than
1162 // Emit constants only once even if used by multiple PHI nodes.
1163 std::map<Constant*, unsigned> ConstantsOut;
1165 // Check successor nodes PHI nodes that expect a constant to be available from
1167 TerminatorInst *TI = LLVMBB->getTerminator();
1168 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1169 BasicBlock *SuccBB = TI->getSuccessor(succ);
1170 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1173 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1174 // nodes and Machine PHI nodes, but the incoming operands have not been
1176 for (BasicBlock::iterator I = SuccBB->begin();
1177 (PN = dyn_cast<PHINode>(I)); ++I)
1178 if (!PN->use_empty()) {
1180 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1181 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1182 unsigned &RegOut = ConstantsOut[C];
1184 RegOut = FuncInfo.CreateRegForValue(C);
1185 UnorderedChains.push_back(
1186 CopyValueToVirtualRegister(SDL, C, RegOut));
1190 Reg = FuncInfo.ValueMap[PHIOp];
1192 assert(isa<AllocaInst>(PHIOp) &&
1193 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1194 "Didn't codegen value into a register!??");
1195 Reg = FuncInfo.CreateRegForValue(PHIOp);
1196 UnorderedChains.push_back(
1197 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1201 // Remember that this register needs to added to the machine PHI node as
1202 // the input for this MBB.
1203 unsigned NumElements =
1204 TLI.getNumElements(TLI.getValueType(PN->getType()));
1205 for (unsigned i = 0, e = NumElements; i != e; ++i)
1206 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1209 ConstantsOut.clear();
1211 // Turn all of the unordered chains into one factored node.
1212 if (!UnorderedChains.empty()) {
1213 UnorderedChains.push_back(SDL.getRoot());
1214 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1217 // Lower the terminator after the copies are emitted.
1218 SDL.visit(*LLVMBB->getTerminator());
1220 // Make sure the root of the DAG is up-to-date.
1221 DAG.setRoot(SDL.getRoot());
1224 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1225 FunctionLoweringInfo &FuncInfo) {
1226 SelectionDAG DAG(TLI, MF);
1228 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1230 // First step, lower LLVM code to some DAG. This DAG may use operations and
1231 // types that are not supported by the target.
1232 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1234 // Run the DAG combiner in pre-legalize mode.
1237 DEBUG(std::cerr << "Lowered selection DAG:\n");
1240 // Second step, hack on the DAG until it only uses operations and types that
1241 // the target supports.
1244 DEBUG(std::cerr << "Legalized selection DAG:\n");
1247 // Run the DAG combiner in post-legalize mode.
1250 if (ViewDAGs) DAG.viewGraph();
1252 // Third, instruction select all of the operations to machine code, adding the
1253 // code to the MachineBasicBlock.
1254 InstructionSelectBasicBlock(DAG);
1256 DEBUG(std::cerr << "Selected machine code:\n");
1259 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1260 // PHI nodes in successors.
1261 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1262 MachineInstr *PHI = PHINodesToUpdate[i].first;
1263 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1264 "This is not a machine PHI node that we are updating!");
1265 PHI->addRegOperand(PHINodesToUpdate[i].second);
1266 PHI->addMachineBasicBlockOperand(BB);
1269 // Finally, add the CFG edges from the last selected MBB to the successor
1271 TerminatorInst *TI = LLVMBB->getTerminator();
1272 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1273 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1274 BB->addSuccessor(Succ0MBB);