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);
150 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
152 // If the alignment of the value is smaller than the size of the value,
153 // and if the size of the value is particularly small (<= 8 bytes),
154 // round up to the size of the value for potentially better performance.
156 // FIXME: This could be made better with a preferred alignment hook in
157 // TargetData. It serves primarily to 8-byte align doubles for X86.
158 if (Align < TySize && TySize <= 8) Align = TySize;
159 TySize *= CUI->getValue(); // Get total allocated size.
160 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
161 StaticAllocaMap[AI] =
162 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
165 for (; BB != EB; ++BB)
166 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
167 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
168 if (!isa<AllocaInst>(I) ||
169 !StaticAllocaMap.count(cast<AllocaInst>(I)))
170 InitializeRegForValue(I);
172 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
173 // also creates the initial PHI MachineInstrs, though none of the input
174 // operands are populated.
175 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
176 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
178 MF.getBasicBlockList().push_back(MBB);
180 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
183 for (BasicBlock::iterator I = BB->begin();
184 (PN = dyn_cast<PHINode>(I)); ++I)
185 if (!PN->use_empty()) {
186 unsigned NumElements =
187 TLI.getNumElements(TLI.getValueType(PN->getType()));
188 unsigned PHIReg = ValueMap[PN];
189 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
190 for (unsigned i = 0; i != NumElements; ++i)
191 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
198 //===----------------------------------------------------------------------===//
199 /// SelectionDAGLowering - This is the common target-independent lowering
200 /// implementation that is parameterized by a TargetLowering object.
201 /// Also, targets can overload any lowering method.
204 class SelectionDAGLowering {
205 MachineBasicBlock *CurMBB;
207 std::map<const Value*, SDOperand> NodeMap;
209 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
210 /// them up and then emit token factor nodes when possible. This allows us to
211 /// get simple disambiguation between loads without worrying about alias
213 std::vector<SDOperand> PendingLoads;
216 // TLI - This is information that describes the available target features we
217 // need for lowering. This indicates when operations are unavailable,
218 // implemented with a libcall, etc.
221 const TargetData &TD;
223 /// FuncInfo - Information about the function as a whole.
225 FunctionLoweringInfo &FuncInfo;
227 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
228 FunctionLoweringInfo &funcinfo)
229 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
233 /// getRoot - Return the current virtual root of the Selection DAG.
235 SDOperand getRoot() {
236 if (PendingLoads.empty())
237 return DAG.getRoot();
239 if (PendingLoads.size() == 1) {
240 SDOperand Root = PendingLoads[0];
242 PendingLoads.clear();
246 // Otherwise, we have to make a token factor node.
247 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
248 PendingLoads.clear();
253 void visit(Instruction &I) { visit(I.getOpcode(), I); }
255 void visit(unsigned Opcode, User &I) {
257 default: assert(0 && "Unknown instruction type encountered!");
259 // Build the switch statement using the Instruction.def file.
260 #define HANDLE_INST(NUM, OPCODE, CLASS) \
261 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
262 #include "llvm/Instruction.def"
266 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
269 SDOperand getIntPtrConstant(uint64_t Val) {
270 return DAG.getConstant(Val, TLI.getPointerTy());
273 SDOperand getValue(const Value *V) {
274 SDOperand &N = NodeMap[V];
277 MVT::ValueType VT = TLI.getValueType(V->getType());
278 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
279 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
280 visit(CE->getOpcode(), *CE);
281 assert(N.Val && "visit didn't populate the ValueMap!");
283 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
284 return N = DAG.getGlobalAddress(GV, VT);
285 } else if (isa<ConstantPointerNull>(C)) {
286 return N = DAG.getConstant(0, TLI.getPointerTy());
287 } else if (isa<UndefValue>(C)) {
288 return N = DAG.getNode(ISD::UNDEF, VT);
289 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
290 return N = DAG.getConstantFP(CFP->getValue(), VT);
292 // Canonicalize all constant ints to be unsigned.
293 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
296 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
297 std::map<const AllocaInst*, int>::iterator SI =
298 FuncInfo.StaticAllocaMap.find(AI);
299 if (SI != FuncInfo.StaticAllocaMap.end())
300 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
303 std::map<const Value*, unsigned>::const_iterator VMI =
304 FuncInfo.ValueMap.find(V);
305 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
307 unsigned InReg = VMI->second;
309 // If this type is not legal, make it so now.
310 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
312 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
314 // Source must be expanded. This input value is actually coming from the
315 // register pair VMI->second and VMI->second+1.
316 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
317 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
319 if (DestVT > VT) { // Promotion case
320 if (MVT::isFloatingPoint(VT))
321 N = DAG.getNode(ISD::FP_ROUND, VT, N);
323 N = DAG.getNode(ISD::TRUNCATE, VT, N);
330 const SDOperand &setValue(const Value *V, SDOperand NewN) {
331 SDOperand &N = NodeMap[V];
332 assert(N.Val == 0 && "Already set a value for this node!");
336 // Terminator instructions.
337 void visitRet(ReturnInst &I);
338 void visitBr(BranchInst &I);
339 void visitUnreachable(UnreachableInst &I) { /* noop */ }
341 // These all get lowered before this pass.
342 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
343 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
344 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
347 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
348 void visitAdd(User &I) {
349 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FADD : ISD::ADD);
351 void visitSub(User &I);
352 void visitMul(User &I) {
353 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FMUL : ISD::MUL);
355 void visitDiv(User &I) {
357 const Type *Ty = I.getType();
358 if (Ty->isFloatingPoint())
360 else if (Ty->isUnsigned())
366 void visitRem(User &I) {
368 const Type *Ty = I.getType();
369 if (Ty->isFloatingPoint())
371 else if (Ty->isUnsigned())
377 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
378 void visitOr (User &I) { visitBinary(I, ISD::OR); }
379 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
380 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
381 void visitShr(User &I) {
382 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
385 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
386 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
387 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
388 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
389 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
390 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
391 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
393 void visitGetElementPtr(User &I);
394 void visitCast(User &I);
395 void visitSelect(User &I);
398 void visitMalloc(MallocInst &I);
399 void visitFree(FreeInst &I);
400 void visitAlloca(AllocaInst &I);
401 void visitLoad(LoadInst &I);
402 void visitStore(StoreInst &I);
403 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
404 void visitCall(CallInst &I);
406 void visitVAStart(CallInst &I);
407 void visitVAArg(VAArgInst &I);
408 void visitVAEnd(CallInst &I);
409 void visitVACopy(CallInst &I);
410 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
412 void visitMemIntrinsic(CallInst &I, unsigned Op);
414 void visitUserOp1(Instruction &I) {
415 assert(0 && "UserOp1 should not exist at instruction selection time!");
418 void visitUserOp2(Instruction &I) {
419 assert(0 && "UserOp2 should not exist at instruction selection time!");
423 } // end namespace llvm
425 void SelectionDAGLowering::visitRet(ReturnInst &I) {
426 if (I.getNumOperands() == 0) {
427 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
431 SDOperand Op1 = getValue(I.getOperand(0));
432 MVT::ValueType TmpVT;
434 switch (Op1.getValueType()) {
435 default: assert(0 && "Unknown value type!");
440 // If this is a machine where 32-bits is legal or expanded, promote to
441 // 32-bits, otherwise, promote to 64-bits.
442 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
443 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
447 // Extend integer types to result type.
448 if (I.getOperand(0)->getType()->isSigned())
449 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
451 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
456 break; // No extension needed!
458 // Allow targets to lower this further to meet ABI requirements
459 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
462 void SelectionDAGLowering::visitBr(BranchInst &I) {
463 // Update machine-CFG edges.
464 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
466 // Figure out which block is immediately after the current one.
467 MachineBasicBlock *NextBlock = 0;
468 MachineFunction::iterator BBI = CurMBB;
469 if (++BBI != CurMBB->getParent()->end())
472 if (I.isUnconditional()) {
473 // If this is not a fall-through branch, emit the branch.
474 if (Succ0MBB != NextBlock)
475 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
476 DAG.getBasicBlock(Succ0MBB)));
478 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
480 SDOperand Cond = getValue(I.getCondition());
481 if (Succ1MBB == NextBlock) {
482 // If the condition is false, fall through. This means we should branch
483 // if the condition is true to Succ #0.
484 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
485 Cond, DAG.getBasicBlock(Succ0MBB)));
486 } else if (Succ0MBB == NextBlock) {
487 // If the condition is true, fall through. This means we should branch if
488 // the condition is false to Succ #1. Invert the condition first.
489 SDOperand True = DAG.getConstant(1, Cond.getValueType());
490 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
491 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
492 Cond, DAG.getBasicBlock(Succ1MBB)));
494 std::vector<SDOperand> Ops;
495 Ops.push_back(getRoot());
497 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
498 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
499 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
504 void SelectionDAGLowering::visitSub(User &I) {
506 if (I.getType()->isFloatingPoint()) {
507 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
508 if (CFP->isExactlyValue(-0.0)) {
509 SDOperand Op2 = getValue(I.getOperand(1));
510 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
513 visitBinary(I, ISD::FSUB);
515 visitBinary(I, ISD::SUB);
519 void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
520 SDOperand Op1 = getValue(I.getOperand(0));
521 SDOperand Op2 = getValue(I.getOperand(1));
524 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
526 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
529 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
530 ISD::CondCode UnsignedOpcode) {
531 SDOperand Op1 = getValue(I.getOperand(0));
532 SDOperand Op2 = getValue(I.getOperand(1));
533 ISD::CondCode Opcode = SignedOpcode;
534 if (I.getOperand(0)->getType()->isUnsigned())
535 Opcode = UnsignedOpcode;
536 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
539 void SelectionDAGLowering::visitSelect(User &I) {
540 SDOperand Cond = getValue(I.getOperand(0));
541 SDOperand TrueVal = getValue(I.getOperand(1));
542 SDOperand FalseVal = getValue(I.getOperand(2));
543 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
547 void SelectionDAGLowering::visitCast(User &I) {
548 SDOperand N = getValue(I.getOperand(0));
549 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
550 MVT::ValueType DestTy = TLI.getValueType(I.getType());
552 if (N.getValueType() == DestTy) {
553 setValue(&I, N); // noop cast.
554 } else if (DestTy == MVT::i1) {
555 // Cast to bool is a comparison against zero, not truncation to zero.
556 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
557 DAG.getConstantFP(0.0, N.getValueType());
558 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
559 } else if (isInteger(SrcTy)) {
560 if (isInteger(DestTy)) { // Int -> Int cast
561 if (DestTy < SrcTy) // Truncating cast?
562 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
563 else if (I.getOperand(0)->getType()->isSigned())
564 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
566 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
567 } else { // Int -> FP cast
568 if (I.getOperand(0)->getType()->isSigned())
569 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
571 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
574 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
575 if (isFloatingPoint(DestTy)) { // FP -> FP cast
576 if (DestTy < SrcTy) // Rounding cast?
577 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
579 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
580 } else { // FP -> Int cast.
581 if (I.getType()->isSigned())
582 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
584 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
589 void SelectionDAGLowering::visitGetElementPtr(User &I) {
590 SDOperand N = getValue(I.getOperand(0));
591 const Type *Ty = I.getOperand(0)->getType();
592 const Type *UIntPtrTy = TD.getIntPtrType();
594 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
597 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
598 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
601 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
602 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
603 getIntPtrConstant(Offset));
605 Ty = StTy->getElementType(Field);
607 Ty = cast<SequentialType>(Ty)->getElementType();
608 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
609 // N = N + Idx * ElementSize;
610 uint64_t ElementSize = TD.getTypeSize(Ty);
611 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
613 // If the index is smaller or larger than intptr_t, truncate or extend
615 if (IdxN.getValueType() < Scale.getValueType()) {
616 if (Idx->getType()->isSigned())
617 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
619 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
620 } else if (IdxN.getValueType() > Scale.getValueType())
621 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
623 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
624 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
631 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
632 // If this is a fixed sized alloca in the entry block of the function,
633 // allocate it statically on the stack.
634 if (FuncInfo.StaticAllocaMap.count(&I))
635 return; // getValue will auto-populate this.
637 const Type *Ty = I.getAllocatedType();
638 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
639 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
641 SDOperand AllocSize = getValue(I.getArraySize());
642 MVT::ValueType IntPtr = TLI.getPointerTy();
643 if (IntPtr < AllocSize.getValueType())
644 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
645 else if (IntPtr > AllocSize.getValueType())
646 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
648 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
649 getIntPtrConstant(TySize));
651 // Handle alignment. If the requested alignment is less than or equal to the
652 // stack alignment, ignore it and round the size of the allocation up to the
653 // stack alignment size. If the size is greater than the stack alignment, we
654 // note this in the DYNAMIC_STACKALLOC node.
655 unsigned StackAlign =
656 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
657 if (Align <= StackAlign) {
659 // Add SA-1 to the size.
660 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
661 getIntPtrConstant(StackAlign-1));
662 // Mask out the low bits for alignment purposes.
663 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
664 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
667 std::vector<MVT::ValueType> VTs;
668 VTs.push_back(AllocSize.getValueType());
669 VTs.push_back(MVT::Other);
670 std::vector<SDOperand> Ops;
671 Ops.push_back(getRoot());
672 Ops.push_back(AllocSize);
673 Ops.push_back(getIntPtrConstant(Align));
674 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
675 DAG.setRoot(setValue(&I, DSA).getValue(1));
677 // Inform the Frame Information that we have just allocated a variable-sized
679 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
683 void SelectionDAGLowering::visitLoad(LoadInst &I) {
684 SDOperand Ptr = getValue(I.getOperand(0));
690 // Do not serialize non-volatile loads against each other.
691 Root = DAG.getRoot();
694 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
695 DAG.getSrcValue(I.getOperand(0)));
699 DAG.setRoot(L.getValue(1));
701 PendingLoads.push_back(L.getValue(1));
705 void SelectionDAGLowering::visitStore(StoreInst &I) {
706 Value *SrcV = I.getOperand(0);
707 SDOperand Src = getValue(SrcV);
708 SDOperand Ptr = getValue(I.getOperand(1));
709 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
710 DAG.getSrcValue(I.getOperand(1))));
713 void SelectionDAGLowering::visitCall(CallInst &I) {
714 const char *RenameFn = 0;
716 if (Function *F = I.getCalledFunction())
718 switch (F->getIntrinsicID()) {
719 case 0: // Not an LLVM intrinsic.
720 if (F->getName() == "fabs" || F->getName() == "fabsf") {
721 if (I.getNumOperands() == 2 && // Basic sanity checks.
722 I.getOperand(1)->getType()->isFloatingPoint() &&
723 I.getType() == I.getOperand(1)->getType()) {
724 Tmp = getValue(I.getOperand(1));
725 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
729 else if (F->getName() == "sin" || F->getName() == "sinf") {
730 if (I.getNumOperands() == 2 && // Basic sanity checks.
731 I.getOperand(1)->getType()->isFloatingPoint() &&
732 I.getType() == I.getOperand(1)->getType()) {
733 Tmp = getValue(I.getOperand(1));
734 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
738 else if (F->getName() == "cos" || F->getName() == "cosf") {
739 if (I.getNumOperands() == 2 && // Basic sanity checks.
740 I.getOperand(1)->getType()->isFloatingPoint() &&
741 I.getType() == I.getOperand(1)->getType()) {
742 Tmp = getValue(I.getOperand(1));
743 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
748 case Intrinsic::vastart: visitVAStart(I); return;
749 case Intrinsic::vaend: visitVAEnd(I); return;
750 case Intrinsic::vacopy: visitVACopy(I); return;
751 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
752 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
754 case Intrinsic::setjmp:
755 RenameFn = "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
757 case Intrinsic::longjmp:
758 RenameFn = "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
760 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
761 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
762 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
764 case Intrinsic::readport:
765 case Intrinsic::readio: {
766 std::vector<MVT::ValueType> VTs;
767 VTs.push_back(TLI.getValueType(I.getType()));
768 VTs.push_back(MVT::Other);
769 std::vector<SDOperand> Ops;
770 Ops.push_back(getRoot());
771 Ops.push_back(getValue(I.getOperand(1)));
772 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
773 ISD::READPORT : ISD::READIO, VTs, Ops);
776 DAG.setRoot(Tmp.getValue(1));
779 case Intrinsic::writeport:
780 case Intrinsic::writeio:
781 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
782 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
783 getRoot(), getValue(I.getOperand(1)),
784 getValue(I.getOperand(2))));
786 case Intrinsic::dbg_stoppoint:
787 case Intrinsic::dbg_region_start:
788 case Intrinsic::dbg_region_end:
789 case Intrinsic::dbg_func_start:
790 case Intrinsic::dbg_declare:
791 if (I.getType() != Type::VoidTy)
792 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
795 case Intrinsic::isunordered:
796 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
797 getValue(I.getOperand(2)), ISD::SETUO));
800 case Intrinsic::sqrt:
801 setValue(&I, DAG.getNode(ISD::FSQRT,
802 getValue(I.getOperand(1)).getValueType(),
803 getValue(I.getOperand(1))));
806 case Intrinsic::pcmarker:
807 Tmp = getValue(I.getOperand(1));
808 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
810 case Intrinsic::cttz:
811 setValue(&I, DAG.getNode(ISD::CTTZ,
812 getValue(I.getOperand(1)).getValueType(),
813 getValue(I.getOperand(1))));
815 case Intrinsic::ctlz:
816 setValue(&I, DAG.getNode(ISD::CTLZ,
817 getValue(I.getOperand(1)).getValueType(),
818 getValue(I.getOperand(1))));
820 case Intrinsic::ctpop:
821 setValue(&I, DAG.getNode(ISD::CTPOP,
822 getValue(I.getOperand(1)).getValueType(),
823 getValue(I.getOperand(1))));
827 assert(0 && "This intrinsic is not implemented yet!");
833 Callee = getValue(I.getOperand(0));
835 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
836 std::vector<std::pair<SDOperand, const Type*> > Args;
838 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
839 Value *Arg = I.getOperand(i);
840 SDOperand ArgNode = getValue(Arg);
841 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
844 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
845 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
847 std::pair<SDOperand,SDOperand> Result =
848 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
849 I.isTailCall(), Callee, Args, DAG);
850 if (I.getType() != Type::VoidTy)
851 setValue(&I, Result.first);
852 DAG.setRoot(Result.second);
855 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
856 SDOperand Src = getValue(I.getOperand(0));
858 MVT::ValueType IntPtr = TLI.getPointerTy();
860 if (IntPtr < Src.getValueType())
861 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
862 else if (IntPtr > Src.getValueType())
863 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
865 // Scale the source by the type size.
866 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
867 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
868 Src, getIntPtrConstant(ElementSize));
870 std::vector<std::pair<SDOperand, const Type*> > Args;
871 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
873 std::pair<SDOperand,SDOperand> Result =
874 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
875 DAG.getExternalSymbol("malloc", IntPtr),
877 setValue(&I, Result.first); // Pointers always fit in registers
878 DAG.setRoot(Result.second);
881 void SelectionDAGLowering::visitFree(FreeInst &I) {
882 std::vector<std::pair<SDOperand, const Type*> > Args;
883 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
884 TLI.getTargetData().getIntPtrType()));
885 MVT::ValueType IntPtr = TLI.getPointerTy();
886 std::pair<SDOperand,SDOperand> Result =
887 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
888 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
889 DAG.setRoot(Result.second);
892 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
893 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
894 // instructions are special in various ways, which require special support to
895 // insert. The specified MachineInstr is created but not inserted into any
896 // basic blocks, and the scheduler passes ownership of it to this method.
897 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
898 MachineBasicBlock *MBB) {
899 std::cerr << "If a target marks an instruction with "
900 "'usesCustomDAGSchedInserter', it must implement "
901 "TargetLowering::InsertAtEndOfBasicBlock!\n";
906 SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
908 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
911 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
912 SDOperand VAListP, Value *VAListV,
914 // We have no sane default behavior, just emit a useful error message and bail
916 std::cerr << "Variable arguments handling not implemented on this target!\n";
921 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
923 // Default to a noop.
927 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
928 SDOperand SrcP, Value *SrcV,
929 SDOperand DestP, Value *DestV,
931 // Default to copying the input list.
932 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
933 SrcP, DAG.getSrcValue(SrcV));
934 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
935 Val, DestP, DAG.getSrcValue(DestV));
939 std::pair<SDOperand,SDOperand>
940 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
941 const Type *ArgTy, SelectionDAG &DAG) {
942 // We have no sane default behavior, just emit a useful error message and bail
944 std::cerr << "Variable arguments handling not implemented on this target!\n";
946 return std::make_pair(SDOperand(), SDOperand());
950 void SelectionDAGLowering::visitVAStart(CallInst &I) {
951 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
952 I.getOperand(1), DAG));
955 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
956 std::pair<SDOperand,SDOperand> Result =
957 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
959 setValue(&I, Result.first);
960 DAG.setRoot(Result.second);
963 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
964 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
965 I.getOperand(1), DAG));
968 void SelectionDAGLowering::visitVACopy(CallInst &I) {
970 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
971 getValue(I.getOperand(1)), I.getOperand(1), DAG);
976 // It is always conservatively correct for llvm.returnaddress and
977 // llvm.frameaddress to return 0.
978 std::pair<SDOperand, SDOperand>
979 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
980 unsigned Depth, SelectionDAG &DAG) {
981 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
984 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
985 assert(0 && "LowerOperation not implemented for this target!");
990 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
991 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
992 std::pair<SDOperand,SDOperand> Result =
993 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
994 setValue(&I, Result.first);
995 DAG.setRoot(Result.second);
998 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
999 std::vector<SDOperand> Ops;
1000 Ops.push_back(getRoot());
1001 Ops.push_back(getValue(I.getOperand(1)));
1002 Ops.push_back(getValue(I.getOperand(2)));
1003 Ops.push_back(getValue(I.getOperand(3)));
1004 Ops.push_back(getValue(I.getOperand(4)));
1005 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1008 //===----------------------------------------------------------------------===//
1009 // SelectionDAGISel code
1010 //===----------------------------------------------------------------------===//
1012 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1013 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1016 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1017 // FIXME: we only modify the CFG to split critical edges. This
1018 // updates dom and loop info.
1022 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1023 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1024 RegMap = MF.getSSARegMap();
1025 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1027 // First pass, split all critical edges for PHI nodes with incoming values
1028 // that are constants, this way the load of the constant into a vreg will not
1029 // be placed into MBBs that are used some other way.
1030 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1032 for (BasicBlock::iterator BBI = BB->begin();
1033 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1034 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1035 if (isa<Constant>(PN->getIncomingValue(i)))
1036 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1039 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1041 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1042 SelectBasicBlock(I, MF, FuncInfo);
1048 SDOperand SelectionDAGISel::
1049 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1050 SDOperand Op = SDL.getValue(V);
1051 assert((Op.getOpcode() != ISD::CopyFromReg ||
1052 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1053 "Copy from a reg to the same reg!");
1055 // If this type is not legal, we must make sure to not create an invalid
1057 MVT::ValueType SrcVT = Op.getValueType();
1058 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1059 SelectionDAG &DAG = SDL.DAG;
1060 if (SrcVT == DestVT) {
1061 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1062 } else if (SrcVT < DestVT) {
1063 // The src value is promoted to the register.
1064 if (MVT::isFloatingPoint(SrcVT))
1065 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1067 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1068 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1070 // The src value is expanded into multiple registers.
1071 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1072 Op, DAG.getConstant(0, MVT::i32));
1073 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1074 Op, DAG.getConstant(1, MVT::i32));
1075 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1076 return DAG.getCopyToReg(Op, Reg+1, Hi);
1080 void SelectionDAGISel::
1081 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1082 std::vector<SDOperand> &UnorderedChains) {
1083 // If this is the entry block, emit arguments.
1084 Function &F = *BB->getParent();
1085 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1086 SDOperand OldRoot = SDL.DAG.getRoot();
1087 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1090 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1092 if (!AI->use_empty()) {
1093 SDL.setValue(AI, Args[a]);
1095 // If this argument is live outside of the entry block, insert a copy from
1096 // whereever we got it to the vreg that other BB's will reference it as.
1097 if (FuncInfo.ValueMap.count(AI)) {
1099 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1100 UnorderedChains.push_back(Copy);
1104 // Next, if the function has live ins that need to be copied into vregs,
1105 // emit the copies now, into the top of the block.
1106 MachineFunction &MF = SDL.DAG.getMachineFunction();
1107 if (MF.livein_begin() != MF.livein_end()) {
1108 SSARegMap *RegMap = MF.getSSARegMap();
1109 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1110 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1111 E = MF.livein_end(); LI != E; ++LI)
1113 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1114 LI->first, RegMap->getRegClass(LI->second));
1117 // Finally, if the target has anything special to do, allow it to do so.
1118 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1122 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1123 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1124 FunctionLoweringInfo &FuncInfo) {
1125 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1127 std::vector<SDOperand> UnorderedChains;
1129 // Lower any arguments needed in this block if this is the entry block.
1130 if (LLVMBB == &LLVMBB->getParent()->front())
1131 LowerArguments(LLVMBB, SDL, UnorderedChains);
1133 BB = FuncInfo.MBBMap[LLVMBB];
1134 SDL.setCurrentBasicBlock(BB);
1136 // Lower all of the non-terminator instructions.
1137 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1141 // Ensure that all instructions which are used outside of their defining
1142 // blocks are available as virtual registers.
1143 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1144 if (!I->use_empty() && !isa<PHINode>(I)) {
1145 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1146 if (VMI != FuncInfo.ValueMap.end())
1147 UnorderedChains.push_back(
1148 CopyValueToVirtualRegister(SDL, I, VMI->second));
1151 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1152 // ensure constants are generated when needed. Remember the virtual registers
1153 // that need to be added to the Machine PHI nodes as input. We cannot just
1154 // directly add them, because expansion might result in multiple MBB's for one
1155 // BB. As such, the start of the BB might correspond to a different MBB than
1159 // Emit constants only once even if used by multiple PHI nodes.
1160 std::map<Constant*, unsigned> ConstantsOut;
1162 // Check successor nodes PHI nodes that expect a constant to be available from
1164 TerminatorInst *TI = LLVMBB->getTerminator();
1165 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1166 BasicBlock *SuccBB = TI->getSuccessor(succ);
1167 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1170 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1171 // nodes and Machine PHI nodes, but the incoming operands have not been
1173 for (BasicBlock::iterator I = SuccBB->begin();
1174 (PN = dyn_cast<PHINode>(I)); ++I)
1175 if (!PN->use_empty()) {
1177 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1178 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1179 unsigned &RegOut = ConstantsOut[C];
1181 RegOut = FuncInfo.CreateRegForValue(C);
1182 UnorderedChains.push_back(
1183 CopyValueToVirtualRegister(SDL, C, RegOut));
1187 Reg = FuncInfo.ValueMap[PHIOp];
1189 assert(isa<AllocaInst>(PHIOp) &&
1190 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1191 "Didn't codegen value into a register!??");
1192 Reg = FuncInfo.CreateRegForValue(PHIOp);
1193 UnorderedChains.push_back(
1194 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1198 // Remember that this register needs to added to the machine PHI node as
1199 // the input for this MBB.
1200 unsigned NumElements =
1201 TLI.getNumElements(TLI.getValueType(PN->getType()));
1202 for (unsigned i = 0, e = NumElements; i != e; ++i)
1203 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1206 ConstantsOut.clear();
1208 // Turn all of the unordered chains into one factored node.
1209 if (!UnorderedChains.empty()) {
1210 UnorderedChains.push_back(SDL.getRoot());
1211 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1214 // Lower the terminator after the copies are emitted.
1215 SDL.visit(*LLVMBB->getTerminator());
1217 // Make sure the root of the DAG is up-to-date.
1218 DAG.setRoot(SDL.getRoot());
1221 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1222 FunctionLoweringInfo &FuncInfo) {
1223 SelectionDAG DAG(TLI, MF);
1225 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1227 // First step, lower LLVM code to some DAG. This DAG may use operations and
1228 // types that are not supported by the target.
1229 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1231 // Run the DAG combiner in pre-legalize mode.
1234 DEBUG(std::cerr << "Lowered selection DAG:\n");
1237 // Second step, hack on the DAG until it only uses operations and types that
1238 // the target supports.
1241 DEBUG(std::cerr << "Legalized selection DAG:\n");
1244 // Run the DAG combiner in post-legalize mode.
1247 if (ViewDAGs) DAG.viewGraph();
1249 // Third, instruction select all of the operations to machine code, adding the
1250 // code to the MachineBasicBlock.
1251 InstructionSelectBasicBlock(DAG);
1253 DEBUG(std::cerr << "Selected machine code:\n");
1256 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1257 // PHI nodes in successors.
1258 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1259 MachineInstr *PHI = PHINodesToUpdate[i].first;
1260 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1261 "This is not a machine PHI node that we are updating!");
1262 PHI->addRegOperand(PHINodesToUpdate[i].second);
1263 PHI->addMachineBasicBlockOperand(BB);
1266 // Finally, add the CFG edges from the last selected MBB to the successor
1268 TerminatorInst *TI = LLVMBB->getTerminator();
1269 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1270 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1271 BB->addSuccessor(Succ0MBB);