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/CodeGen/ScheduleDAG.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/InlineAsm.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CodeGen/IntrinsicLowering.h"
26 #include "llvm/CodeGen/MachineDebugInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/SSARegMap.h"
32 #include "llvm/Target/MRegisterInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetFrameInfo.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/Debug.h"
49 ViewISelDAGs("view-isel-dags", cl::Hidden,
50 cl::desc("Pop up a window to show isel dags as they are selected"));
52 ViewSchedDAGs("view-sched-dags", cl::Hidden,
53 cl::desc("Pop up a window to show sched dags as they are processed"));
55 static const bool ViewISelDAGs = 0;
56 static const bool ViewSchedDAGs = 0;
60 cl::opt<SchedHeuristics>
63 cl::desc("Choose scheduling style"),
64 cl::init(defaultScheduling),
66 clEnumValN(defaultScheduling, "default",
67 "Target preferred scheduling style"),
68 clEnumValN(noScheduling, "none",
69 "No scheduling: breadth first sequencing"),
70 clEnumValN(simpleScheduling, "simple",
71 "Simple two pass scheduling: minimize critical path "
72 "and maximize processor utilization"),
73 clEnumValN(simpleNoItinScheduling, "simple-noitin",
74 "Simple two pass scheduling: Same as simple "
75 "except using generic latency"),
76 clEnumValN(listSchedulingBURR, "list-burr",
77 "Bottom up register reduction list scheduling"),
83 //===--------------------------------------------------------------------===//
84 /// FunctionLoweringInfo - This contains information that is global to a
85 /// function that is used when lowering a region of the function.
86 class FunctionLoweringInfo {
93 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
95 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
96 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
98 /// ValueMap - Since we emit code for the function a basic block at a time,
99 /// we must remember which virtual registers hold the values for
100 /// cross-basic-block values.
101 std::map<const Value*, unsigned> ValueMap;
103 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
104 /// the entry block. This allows the allocas to be efficiently referenced
105 /// anywhere in the function.
106 std::map<const AllocaInst*, int> StaticAllocaMap;
108 unsigned MakeReg(MVT::ValueType VT) {
109 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
112 unsigned CreateRegForValue(const Value *V) {
113 MVT::ValueType VT = TLI.getValueType(V->getType());
114 // The common case is that we will only create one register for this
115 // value. If we have that case, create and return the virtual register.
116 unsigned NV = TLI.getNumElements(VT);
118 // If we are promoting this value, pick the next largest supported type.
119 return MakeReg(TLI.getTypeToTransformTo(VT));
122 // If this value is represented with multiple target registers, make sure
123 // to create enough consequtive registers of the right (smaller) type.
124 unsigned NT = VT-1; // Find the type to use.
125 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
128 unsigned R = MakeReg((MVT::ValueType)NT);
129 for (unsigned i = 1; i != NV; ++i)
130 MakeReg((MVT::ValueType)NT);
134 unsigned InitializeRegForValue(const Value *V) {
135 unsigned &R = ValueMap[V];
136 assert(R == 0 && "Already initialized this value register!");
137 return R = CreateRegForValue(V);
142 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
143 /// PHI nodes or outside of the basic block that defines it.
144 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
145 if (isa<PHINode>(I)) return true;
146 BasicBlock *BB = I->getParent();
147 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
148 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
153 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
154 /// entry block, return true.
155 static bool isOnlyUsedInEntryBlock(Argument *A) {
156 BasicBlock *Entry = A->getParent()->begin();
157 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
158 if (cast<Instruction>(*UI)->getParent() != Entry)
159 return false; // Use not in entry block.
163 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
164 Function &fn, MachineFunction &mf)
165 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
167 // Create a vreg for each argument register that is not dead and is used
168 // outside of the entry block for the function.
169 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
171 if (!isOnlyUsedInEntryBlock(AI))
172 InitializeRegForValue(AI);
174 // Initialize the mapping of values to registers. This is only set up for
175 // instruction values that are used outside of the block that defines
177 Function::iterator BB = Fn.begin(), EB = Fn.end();
178 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
179 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
180 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
181 const Type *Ty = AI->getAllocatedType();
182 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
184 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
187 // If the alignment of the value is smaller than the size of the value,
188 // and if the size of the value is particularly small (<= 8 bytes),
189 // round up to the size of the value for potentially better performance.
191 // FIXME: This could be made better with a preferred alignment hook in
192 // TargetData. It serves primarily to 8-byte align doubles for X86.
193 if (Align < TySize && TySize <= 8) Align = TySize;
194 TySize *= CUI->getValue(); // Get total allocated size.
195 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
196 StaticAllocaMap[AI] =
197 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
200 for (; BB != EB; ++BB)
201 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
202 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
203 if (!isa<AllocaInst>(I) ||
204 !StaticAllocaMap.count(cast<AllocaInst>(I)))
205 InitializeRegForValue(I);
207 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
208 // also creates the initial PHI MachineInstrs, though none of the input
209 // operands are populated.
210 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
211 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
213 MF.getBasicBlockList().push_back(MBB);
215 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
218 for (BasicBlock::iterator I = BB->begin();
219 (PN = dyn_cast<PHINode>(I)); ++I)
220 if (!PN->use_empty()) {
221 unsigned NumElements =
222 TLI.getNumElements(TLI.getValueType(PN->getType()));
223 unsigned PHIReg = ValueMap[PN];
224 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
225 for (unsigned i = 0; i != NumElements; ++i)
226 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
233 //===----------------------------------------------------------------------===//
234 /// SelectionDAGLowering - This is the common target-independent lowering
235 /// implementation that is parameterized by a TargetLowering object.
236 /// Also, targets can overload any lowering method.
239 class SelectionDAGLowering {
240 MachineBasicBlock *CurMBB;
242 std::map<const Value*, SDOperand> NodeMap;
244 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
245 /// them up and then emit token factor nodes when possible. This allows us to
246 /// get simple disambiguation between loads without worrying about alias
248 std::vector<SDOperand> PendingLoads;
251 // TLI - This is information that describes the available target features we
252 // need for lowering. This indicates when operations are unavailable,
253 // implemented with a libcall, etc.
256 const TargetData &TD;
258 /// FuncInfo - Information about the function as a whole.
260 FunctionLoweringInfo &FuncInfo;
262 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
263 FunctionLoweringInfo &funcinfo)
264 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
268 /// getRoot - Return the current virtual root of the Selection DAG.
270 SDOperand getRoot() {
271 if (PendingLoads.empty())
272 return DAG.getRoot();
274 if (PendingLoads.size() == 1) {
275 SDOperand Root = PendingLoads[0];
277 PendingLoads.clear();
281 // Otherwise, we have to make a token factor node.
282 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
283 PendingLoads.clear();
288 void visit(Instruction &I) { visit(I.getOpcode(), I); }
290 void visit(unsigned Opcode, User &I) {
292 default: assert(0 && "Unknown instruction type encountered!");
294 // Build the switch statement using the Instruction.def file.
295 #define HANDLE_INST(NUM, OPCODE, CLASS) \
296 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
297 #include "llvm/Instruction.def"
301 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
304 SDOperand getIntPtrConstant(uint64_t Val) {
305 return DAG.getConstant(Val, TLI.getPointerTy());
308 SDOperand getValue(const Value *V) {
309 SDOperand &N = NodeMap[V];
312 const Type *VTy = V->getType();
313 MVT::ValueType VT = TLI.getValueType(VTy);
314 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
315 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
316 visit(CE->getOpcode(), *CE);
317 assert(N.Val && "visit didn't populate the ValueMap!");
319 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
320 return N = DAG.getGlobalAddress(GV, VT);
321 } else if (isa<ConstantPointerNull>(C)) {
322 return N = DAG.getConstant(0, TLI.getPointerTy());
323 } else if (isa<UndefValue>(C)) {
324 return N = DAG.getNode(ISD::UNDEF, VT);
325 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
326 return N = DAG.getConstantFP(CFP->getValue(), VT);
327 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
328 unsigned NumElements = PTy->getNumElements();
329 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
330 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
332 // Now that we know the number and type of the elements, push a
333 // Constant or ConstantFP node onto the ops list for each element of
334 // the packed constant.
335 std::vector<SDOperand> Ops;
336 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
337 if (MVT::isFloatingPoint(PVT)) {
338 for (unsigned i = 0; i != NumElements; ++i) {
339 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
340 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
343 for (unsigned i = 0; i != NumElements; ++i) {
344 const ConstantIntegral *El =
345 cast<ConstantIntegral>(CP->getOperand(i));
346 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
350 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
352 if (MVT::isFloatingPoint(PVT))
353 Op = DAG.getConstantFP(0, PVT);
355 Op = DAG.getConstant(0, PVT);
356 Ops.assign(NumElements, Op);
359 // Handle the case where we have a 1-element vector, in which
360 // case we want to immediately turn it into a scalar constant.
361 if (Ops.size() == 1) {
363 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
364 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
366 // If the packed type isn't legal, then create a ConstantVec node with
367 // generic Vector type instead.
368 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
371 // Canonicalize all constant ints to be unsigned.
372 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
375 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
376 std::map<const AllocaInst*, int>::iterator SI =
377 FuncInfo.StaticAllocaMap.find(AI);
378 if (SI != FuncInfo.StaticAllocaMap.end())
379 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
382 std::map<const Value*, unsigned>::const_iterator VMI =
383 FuncInfo.ValueMap.find(V);
384 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
386 unsigned InReg = VMI->second;
388 // If this type is not legal, make it so now.
389 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
391 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
393 // Source must be expanded. This input value is actually coming from the
394 // register pair VMI->second and VMI->second+1.
395 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
396 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
398 if (DestVT > VT) { // Promotion case
399 if (MVT::isFloatingPoint(VT))
400 N = DAG.getNode(ISD::FP_ROUND, VT, N);
402 N = DAG.getNode(ISD::TRUNCATE, VT, N);
409 const SDOperand &setValue(const Value *V, SDOperand NewN) {
410 SDOperand &N = NodeMap[V];
411 assert(N.Val == 0 && "Already set a value for this node!");
415 unsigned GetAvailableRegister(bool OutReg, bool InReg,
416 const std::vector<unsigned> &RegChoices,
417 std::set<unsigned> &OutputRegs,
418 std::set<unsigned> &InputRegs);
420 // Terminator instructions.
421 void visitRet(ReturnInst &I);
422 void visitBr(BranchInst &I);
423 void visitUnreachable(UnreachableInst &I) { /* noop */ }
425 // These all get lowered before this pass.
426 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
427 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
428 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
429 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
430 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
433 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
434 void visitShift(User &I, unsigned Opcode);
435 void visitAdd(User &I) {
436 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
438 void visitSub(User &I);
439 void visitMul(User &I) {
440 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
442 void visitDiv(User &I) {
443 const Type *Ty = I.getType();
444 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
446 void visitRem(User &I) {
447 const Type *Ty = I.getType();
448 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
450 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
451 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
452 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
453 void visitShl(User &I) { visitShift(I, ISD::SHL); }
454 void visitShr(User &I) {
455 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
458 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
459 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
460 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
461 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
462 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
463 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
464 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
466 void visitGetElementPtr(User &I);
467 void visitCast(User &I);
468 void visitSelect(User &I);
471 void visitMalloc(MallocInst &I);
472 void visitFree(FreeInst &I);
473 void visitAlloca(AllocaInst &I);
474 void visitLoad(LoadInst &I);
475 void visitStore(StoreInst &I);
476 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
477 void visitCall(CallInst &I);
478 void visitInlineAsm(CallInst &I);
479 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
481 void visitVAStart(CallInst &I);
482 void visitVAArg(VAArgInst &I);
483 void visitVAEnd(CallInst &I);
484 void visitVACopy(CallInst &I);
485 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
487 void visitMemIntrinsic(CallInst &I, unsigned Op);
489 void visitUserOp1(Instruction &I) {
490 assert(0 && "UserOp1 should not exist at instruction selection time!");
493 void visitUserOp2(Instruction &I) {
494 assert(0 && "UserOp2 should not exist at instruction selection time!");
498 } // end namespace llvm
500 void SelectionDAGLowering::visitRet(ReturnInst &I) {
501 if (I.getNumOperands() == 0) {
502 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
505 std::vector<SDOperand> NewValues;
506 NewValues.push_back(getRoot());
507 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
508 SDOperand RetOp = getValue(I.getOperand(i));
510 // If this is an integer return value, we need to promote it ourselves to
511 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
513 if (MVT::isInteger(RetOp.getValueType()) &&
514 RetOp.getValueType() < MVT::i64) {
515 MVT::ValueType TmpVT;
516 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
517 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
521 if (I.getOperand(i)->getType()->isSigned())
522 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
524 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
526 NewValues.push_back(RetOp);
528 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
531 void SelectionDAGLowering::visitBr(BranchInst &I) {
532 // Update machine-CFG edges.
533 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
535 // Figure out which block is immediately after the current one.
536 MachineBasicBlock *NextBlock = 0;
537 MachineFunction::iterator BBI = CurMBB;
538 if (++BBI != CurMBB->getParent()->end())
541 if (I.isUnconditional()) {
542 // If this is not a fall-through branch, emit the branch.
543 if (Succ0MBB != NextBlock)
544 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
545 DAG.getBasicBlock(Succ0MBB)));
547 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
549 SDOperand Cond = getValue(I.getCondition());
550 if (Succ1MBB == NextBlock) {
551 // If the condition is false, fall through. This means we should branch
552 // if the condition is true to Succ #0.
553 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
554 Cond, DAG.getBasicBlock(Succ0MBB)));
555 } else if (Succ0MBB == NextBlock) {
556 // If the condition is true, fall through. This means we should branch if
557 // the condition is false to Succ #1. Invert the condition first.
558 SDOperand True = DAG.getConstant(1, Cond.getValueType());
559 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
560 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
561 Cond, DAG.getBasicBlock(Succ1MBB)));
563 std::vector<SDOperand> Ops;
564 Ops.push_back(getRoot());
566 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
567 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
568 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
573 void SelectionDAGLowering::visitSub(User &I) {
575 if (I.getType()->isFloatingPoint()) {
576 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
577 if (CFP->isExactlyValue(-0.0)) {
578 SDOperand Op2 = getValue(I.getOperand(1));
579 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
583 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
586 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
588 const Type *Ty = I.getType();
589 SDOperand Op1 = getValue(I.getOperand(0));
590 SDOperand Op2 = getValue(I.getOperand(1));
592 if (Ty->isIntegral()) {
593 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
594 } else if (Ty->isFloatingPoint()) {
595 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
597 const PackedType *PTy = cast<PackedType>(Ty);
598 unsigned NumElements = PTy->getNumElements();
599 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
600 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
602 // Immediately scalarize packed types containing only one element, so that
603 // the Legalize pass does not have to deal with them. Similarly, if the
604 // abstract vector is going to turn into one that the target natively
605 // supports, generate that type now so that Legalize doesn't have to deal
606 // with that either. These steps ensure that Legalize only has to handle
607 // vector types in its Expand case.
608 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
609 if (NumElements == 1) {
610 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
611 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
612 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
614 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
615 SDOperand Typ = DAG.getValueType(PVT);
616 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
621 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
622 SDOperand Op1 = getValue(I.getOperand(0));
623 SDOperand Op2 = getValue(I.getOperand(1));
625 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
627 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
630 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
631 ISD::CondCode UnsignedOpcode) {
632 SDOperand Op1 = getValue(I.getOperand(0));
633 SDOperand Op2 = getValue(I.getOperand(1));
634 ISD::CondCode Opcode = SignedOpcode;
635 if (I.getOperand(0)->getType()->isUnsigned())
636 Opcode = UnsignedOpcode;
637 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
640 void SelectionDAGLowering::visitSelect(User &I) {
641 SDOperand Cond = getValue(I.getOperand(0));
642 SDOperand TrueVal = getValue(I.getOperand(1));
643 SDOperand FalseVal = getValue(I.getOperand(2));
644 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
648 void SelectionDAGLowering::visitCast(User &I) {
649 SDOperand N = getValue(I.getOperand(0));
650 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
651 MVT::ValueType DestTy = TLI.getValueType(I.getType());
653 if (N.getValueType() == DestTy) {
654 setValue(&I, N); // noop cast.
655 } else if (DestTy == MVT::i1) {
656 // Cast to bool is a comparison against zero, not truncation to zero.
657 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
658 DAG.getConstantFP(0.0, N.getValueType());
659 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
660 } else if (isInteger(SrcTy)) {
661 if (isInteger(DestTy)) { // Int -> Int cast
662 if (DestTy < SrcTy) // Truncating cast?
663 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
664 else if (I.getOperand(0)->getType()->isSigned())
665 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
667 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
668 } else { // Int -> FP cast
669 if (I.getOperand(0)->getType()->isSigned())
670 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
672 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
675 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
676 if (isFloatingPoint(DestTy)) { // FP -> FP cast
677 if (DestTy < SrcTy) // Rounding cast?
678 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
680 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
681 } else { // FP -> Int cast.
682 if (I.getType()->isSigned())
683 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
685 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
690 void SelectionDAGLowering::visitGetElementPtr(User &I) {
691 SDOperand N = getValue(I.getOperand(0));
692 const Type *Ty = I.getOperand(0)->getType();
693 const Type *UIntPtrTy = TD.getIntPtrType();
695 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
698 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
699 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
702 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
703 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
704 getIntPtrConstant(Offset));
706 Ty = StTy->getElementType(Field);
708 Ty = cast<SequentialType>(Ty)->getElementType();
710 // If this is a constant subscript, handle it quickly.
711 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
712 if (CI->getRawValue() == 0) continue;
715 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
716 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
718 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
719 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
723 // N = N + Idx * ElementSize;
724 uint64_t ElementSize = TD.getTypeSize(Ty);
725 SDOperand IdxN = getValue(Idx);
727 // If the index is smaller or larger than intptr_t, truncate or extend
729 if (IdxN.getValueType() < N.getValueType()) {
730 if (Idx->getType()->isSigned())
731 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
733 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
734 } else if (IdxN.getValueType() > N.getValueType())
735 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
737 // If this is a multiply by a power of two, turn it into a shl
738 // immediately. This is a very common case.
739 if (isPowerOf2_64(ElementSize)) {
740 unsigned Amt = Log2_64(ElementSize);
741 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
742 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
743 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
747 SDOperand Scale = getIntPtrConstant(ElementSize);
748 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
749 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
755 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
756 // If this is a fixed sized alloca in the entry block of the function,
757 // allocate it statically on the stack.
758 if (FuncInfo.StaticAllocaMap.count(&I))
759 return; // getValue will auto-populate this.
761 const Type *Ty = I.getAllocatedType();
762 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
763 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
766 SDOperand AllocSize = getValue(I.getArraySize());
767 MVT::ValueType IntPtr = TLI.getPointerTy();
768 if (IntPtr < AllocSize.getValueType())
769 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
770 else if (IntPtr > AllocSize.getValueType())
771 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
773 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
774 getIntPtrConstant(TySize));
776 // Handle alignment. If the requested alignment is less than or equal to the
777 // stack alignment, ignore it and round the size of the allocation up to the
778 // stack alignment size. If the size is greater than the stack alignment, we
779 // note this in the DYNAMIC_STACKALLOC node.
780 unsigned StackAlign =
781 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
782 if (Align <= StackAlign) {
784 // Add SA-1 to the size.
785 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
786 getIntPtrConstant(StackAlign-1));
787 // Mask out the low bits for alignment purposes.
788 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
789 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
792 std::vector<MVT::ValueType> VTs;
793 VTs.push_back(AllocSize.getValueType());
794 VTs.push_back(MVT::Other);
795 std::vector<SDOperand> Ops;
796 Ops.push_back(getRoot());
797 Ops.push_back(AllocSize);
798 Ops.push_back(getIntPtrConstant(Align));
799 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
800 DAG.setRoot(setValue(&I, DSA).getValue(1));
802 // Inform the Frame Information that we have just allocated a variable-sized
804 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
807 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
808 /// global into a string value. Return an empty string if we can't do it.
810 static std::string getStringValue(Value *V, unsigned Offset = 0) {
811 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
812 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
813 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
814 if (Init->isString()) {
815 std::string Result = Init->getAsString();
816 if (Offset < Result.size()) {
817 // If we are pointing INTO The string, erase the beginning...
818 Result.erase(Result.begin(), Result.begin()+Offset);
820 // Take off the null terminator, and any string fragments after it.
821 std::string::size_type NullPos = Result.find_first_of((char)0);
822 if (NullPos != std::string::npos)
823 Result.erase(Result.begin()+NullPos, Result.end());
828 } else if (Constant *C = dyn_cast<Constant>(V)) {
829 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
830 return getStringValue(GV, Offset);
831 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
832 if (CE->getOpcode() == Instruction::GetElementPtr) {
833 // Turn a gep into the specified offset.
834 if (CE->getNumOperands() == 3 &&
835 cast<Constant>(CE->getOperand(1))->isNullValue() &&
836 isa<ConstantInt>(CE->getOperand(2))) {
837 return getStringValue(CE->getOperand(0),
838 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
846 void SelectionDAGLowering::visitLoad(LoadInst &I) {
847 SDOperand Ptr = getValue(I.getOperand(0));
853 // Do not serialize non-volatile loads against each other.
854 Root = DAG.getRoot();
857 const Type *Ty = I.getType();
860 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
861 unsigned NumElements = PTy->getNumElements();
862 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
863 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
865 // Immediately scalarize packed types containing only one element, so that
866 // the Legalize pass does not have to deal with them.
867 if (NumElements == 1) {
868 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
869 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
870 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
872 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
873 DAG.getSrcValue(I.getOperand(0)));
876 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
877 DAG.getSrcValue(I.getOperand(0)));
882 DAG.setRoot(L.getValue(1));
884 PendingLoads.push_back(L.getValue(1));
888 void SelectionDAGLowering::visitStore(StoreInst &I) {
889 Value *SrcV = I.getOperand(0);
890 SDOperand Src = getValue(SrcV);
891 SDOperand Ptr = getValue(I.getOperand(1));
892 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
893 DAG.getSrcValue(I.getOperand(1))));
896 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
897 /// we want to emit this as a call to a named external function, return the name
898 /// otherwise lower it and return null.
900 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
902 case Intrinsic::vastart: visitVAStart(I); return 0;
903 case Intrinsic::vaend: visitVAEnd(I); return 0;
904 case Intrinsic::vacopy: visitVACopy(I); return 0;
905 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
906 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
907 case Intrinsic::setjmp:
908 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
910 case Intrinsic::longjmp:
911 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
913 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
914 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
915 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
917 case Intrinsic::readport:
918 case Intrinsic::readio: {
919 std::vector<MVT::ValueType> VTs;
920 VTs.push_back(TLI.getValueType(I.getType()));
921 VTs.push_back(MVT::Other);
922 std::vector<SDOperand> Ops;
923 Ops.push_back(getRoot());
924 Ops.push_back(getValue(I.getOperand(1)));
925 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
926 ISD::READPORT : ISD::READIO, VTs, Ops);
929 DAG.setRoot(Tmp.getValue(1));
932 case Intrinsic::writeport:
933 case Intrinsic::writeio:
934 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
935 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
936 getRoot(), getValue(I.getOperand(1)),
937 getValue(I.getOperand(2))));
940 case Intrinsic::dbg_stoppoint: {
941 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
942 return "llvm_debugger_stop";
944 std::string fname = "<unknown>";
945 std::vector<SDOperand> Ops;
948 Ops.push_back(getRoot());
951 Ops.push_back(getValue(I.getOperand(2)));
954 Ops.push_back(getValue(I.getOperand(3)));
956 // filename/working dir
957 // Pull the filename out of the the compilation unit.
958 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
959 if (cunit && cunit->hasInitializer()) {
960 if (ConstantStruct *CS =
961 dyn_cast<ConstantStruct>(cunit->getInitializer())) {
962 if (CS->getNumOperands() > 0) {
963 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
964 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
969 if (Ops.size() == 5) // Found filename/workingdir.
970 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
971 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
974 case Intrinsic::dbg_region_start:
975 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
976 return "llvm_dbg_region_start";
977 if (I.getType() != Type::VoidTy)
978 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
980 case Intrinsic::dbg_region_end:
981 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
982 return "llvm_dbg_region_end";
983 if (I.getType() != Type::VoidTy)
984 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
986 case Intrinsic::dbg_func_start:
987 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
988 return "llvm_dbg_subprogram";
989 if (I.getType() != Type::VoidTy)
990 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
992 case Intrinsic::dbg_declare:
993 if (I.getType() != Type::VoidTy)
994 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
997 case Intrinsic::isunordered_f32:
998 case Intrinsic::isunordered_f64:
999 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1000 getValue(I.getOperand(2)), ISD::SETUO));
1003 case Intrinsic::sqrt_f32:
1004 case Intrinsic::sqrt_f64:
1005 setValue(&I, DAG.getNode(ISD::FSQRT,
1006 getValue(I.getOperand(1)).getValueType(),
1007 getValue(I.getOperand(1))));
1009 case Intrinsic::pcmarker: {
1010 SDOperand Tmp = getValue(I.getOperand(1));
1011 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1014 case Intrinsic::readcyclecounter: {
1015 std::vector<MVT::ValueType> VTs;
1016 VTs.push_back(MVT::i64);
1017 VTs.push_back(MVT::Other);
1018 std::vector<SDOperand> Ops;
1019 Ops.push_back(getRoot());
1020 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1022 DAG.setRoot(Tmp.getValue(1));
1025 case Intrinsic::bswap_i16:
1026 case Intrinsic::bswap_i32:
1027 case Intrinsic::bswap_i64:
1028 setValue(&I, DAG.getNode(ISD::BSWAP,
1029 getValue(I.getOperand(1)).getValueType(),
1030 getValue(I.getOperand(1))));
1032 case Intrinsic::cttz_i8:
1033 case Intrinsic::cttz_i16:
1034 case Intrinsic::cttz_i32:
1035 case Intrinsic::cttz_i64:
1036 setValue(&I, DAG.getNode(ISD::CTTZ,
1037 getValue(I.getOperand(1)).getValueType(),
1038 getValue(I.getOperand(1))));
1040 case Intrinsic::ctlz_i8:
1041 case Intrinsic::ctlz_i16:
1042 case Intrinsic::ctlz_i32:
1043 case Intrinsic::ctlz_i64:
1044 setValue(&I, DAG.getNode(ISD::CTLZ,
1045 getValue(I.getOperand(1)).getValueType(),
1046 getValue(I.getOperand(1))));
1048 case Intrinsic::ctpop_i8:
1049 case Intrinsic::ctpop_i16:
1050 case Intrinsic::ctpop_i32:
1051 case Intrinsic::ctpop_i64:
1052 setValue(&I, DAG.getNode(ISD::CTPOP,
1053 getValue(I.getOperand(1)).getValueType(),
1054 getValue(I.getOperand(1))));
1056 case Intrinsic::stacksave: {
1057 std::vector<MVT::ValueType> VTs;
1058 VTs.push_back(TLI.getPointerTy());
1059 VTs.push_back(MVT::Other);
1060 std::vector<SDOperand> Ops;
1061 Ops.push_back(getRoot());
1062 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1064 DAG.setRoot(Tmp.getValue(1));
1067 case Intrinsic::stackrestore: {
1068 SDOperand Tmp = getValue(I.getOperand(1));
1069 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1072 case Intrinsic::prefetch:
1073 // FIXME: Currently discarding prefetches.
1077 assert(0 && "This intrinsic is not implemented yet!");
1083 void SelectionDAGLowering::visitCall(CallInst &I) {
1084 const char *RenameFn = 0;
1085 if (Function *F = I.getCalledFunction()) {
1086 if (F->isExternal())
1087 if (unsigned IID = F->getIntrinsicID()) {
1088 RenameFn = visitIntrinsicCall(I, IID);
1091 } else { // Not an LLVM intrinsic.
1092 const std::string &Name = F->getName();
1093 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1094 if (I.getNumOperands() == 2 && // Basic sanity checks.
1095 I.getOperand(1)->getType()->isFloatingPoint() &&
1096 I.getType() == I.getOperand(1)->getType()) {
1097 SDOperand Tmp = getValue(I.getOperand(1));
1098 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1101 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1102 if (I.getNumOperands() == 2 && // Basic sanity checks.
1103 I.getOperand(1)->getType()->isFloatingPoint() &&
1104 I.getType() == I.getOperand(1)->getType() &&
1105 TLI.isOperationLegal(ISD::FSIN,
1106 TLI.getValueType(I.getOperand(1)->getType()))) {
1107 SDOperand Tmp = getValue(I.getOperand(1));
1108 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1111 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1112 if (I.getNumOperands() == 2 && // Basic sanity checks.
1113 I.getOperand(1)->getType()->isFloatingPoint() &&
1114 I.getType() == I.getOperand(1)->getType() &&
1115 TLI.isOperationLegal(ISD::FCOS,
1116 TLI.getValueType(I.getOperand(1)->getType()))) {
1117 SDOperand Tmp = getValue(I.getOperand(1));
1118 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1123 } else if (isa<InlineAsm>(I.getOperand(0))) {
1130 Callee = getValue(I.getOperand(0));
1132 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1133 std::vector<std::pair<SDOperand, const Type*> > Args;
1134 Args.reserve(I.getNumOperands());
1135 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1136 Value *Arg = I.getOperand(i);
1137 SDOperand ArgNode = getValue(Arg);
1138 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1141 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1142 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1144 std::pair<SDOperand,SDOperand> Result =
1145 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1146 I.isTailCall(), Callee, Args, DAG);
1147 if (I.getType() != Type::VoidTy)
1148 setValue(&I, Result.first);
1149 DAG.setRoot(Result.second);
1152 /// GetAvailableRegister - Pick a register from RegChoices that is available
1153 /// for input and/or output as specified by isOutReg/isInReg. If an allocatable
1154 /// register is found, it is returned and added to the specified set of used
1155 /// registers. If not, zero is returned.
1156 unsigned SelectionDAGLowering::
1157 GetAvailableRegister(bool isOutReg, bool isInReg,
1158 const std::vector<unsigned> &RegChoices,
1159 std::set<unsigned> &OutputRegs,
1160 std::set<unsigned> &InputRegs) {
1161 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1162 MachineFunction &MF = *CurMBB->getParent();
1163 for (unsigned i = 0, e = RegChoices.size(); i != e; ++i) {
1164 unsigned Reg = RegChoices[i];
1165 // See if this register is available.
1166 if (isOutReg && OutputRegs.count(Reg)) continue; // Already used.
1167 if (isInReg && InputRegs.count(Reg)) continue; // Already used.
1169 // Check to see if this register is allocatable (i.e. don't give out the
1172 for (MRegisterInfo::regclass_iterator RC = MRI->regclass_begin(),
1173 E = MRI->regclass_end(); !Found && RC != E; ++RC) {
1174 // NOTE: This isn't ideal. In particular, this might allocate the
1175 // frame pointer in functions that need it (due to them not being taken
1176 // out of allocation, because a variable sized allocation hasn't been seen
1177 // yet). This is a slight code pessimization, but should still work.
1178 for (TargetRegisterClass::iterator I = (*RC)->allocation_order_begin(MF),
1179 E = (*RC)->allocation_order_end(MF); I != E; ++I)
1185 if (!Found) continue;
1187 // Okay, this register is good, return it.
1188 if (isOutReg) OutputRegs.insert(Reg); // Mark used.
1189 if (isInReg) InputRegs.insert(Reg); // Mark used.
1195 /// visitInlineAsm - Handle a call to an InlineAsm object.
1197 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1198 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1200 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1203 // Note, we treat inline asms both with and without side-effects as the same.
1204 // If an inline asm doesn't have side effects and doesn't access memory, we
1205 // could not choose to not chain it.
1206 bool hasSideEffects = IA->hasSideEffects();
1208 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1210 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1211 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1212 /// if it is a def of that register.
1213 std::vector<SDOperand> AsmNodeOperands;
1214 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1215 AsmNodeOperands.push_back(AsmStr);
1217 SDOperand Chain = getRoot();
1220 // Loop over all of the inputs, copying the operand values into the
1221 // appropriate registers and processing the output regs.
1222 unsigned RetValReg = 0;
1223 std::vector<std::pair<unsigned, Value*> > IndirectStoresToEmit;
1225 bool FoundOutputConstraint = false;
1227 // We fully assign registers here at isel time. This is not optimal, but
1228 // should work. For register classes that correspond to LLVM classes, we
1229 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1230 // over the constraints, collecting fixed registers that we know we can't use.
1231 std::set<unsigned> OutputRegs, InputRegs;
1232 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1233 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1234 std::string &ConstraintCode = Constraints[i].Codes[0];
1236 std::vector<unsigned> Regs =
1237 TLI.getRegForInlineAsmConstraint(ConstraintCode);
1238 if (Regs.size() != 1) continue; // Not assigned a fixed reg.
1239 unsigned TheReg = Regs[0];
1241 switch (Constraints[i].Type) {
1242 case InlineAsm::isOutput:
1243 // We can't assign any other output to this register.
1244 OutputRegs.insert(TheReg);
1245 // If this is an early-clobber output, it cannot be assigned to the same
1246 // value as the input reg.
1247 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1248 InputRegs.insert(TheReg);
1250 case InlineAsm::isClobber:
1251 // Clobbered regs cannot be used as inputs or outputs.
1252 InputRegs.insert(TheReg);
1253 OutputRegs.insert(TheReg);
1255 case InlineAsm::isInput:
1256 // We can't assign any other input to this register.
1257 InputRegs.insert(TheReg);
1262 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1263 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1264 std::string &ConstraintCode = Constraints[i].Codes[0];
1265 switch (Constraints[i].Type) {
1266 case InlineAsm::isOutput: {
1267 // Copy the output from the appropriate register.
1268 std::vector<unsigned> Regs =
1269 TLI.getRegForInlineAsmConstraint(ConstraintCode);
1271 // Find a regsister that we can use.
1273 if (Regs.size() == 1)
1276 bool UsesInputRegister = false;
1277 // If this is an early-clobber output, or if there is an input
1278 // constraint that matches this, we need to reserve the input register
1279 // so no other inputs allocate to it.
1280 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1281 UsesInputRegister = true;
1282 DestReg = GetAvailableRegister(true, UsesInputRegister,
1283 Regs, OutputRegs, InputRegs);
1286 assert(DestReg && "Couldn't allocate output reg!");
1289 if (!Constraints[i].isIndirectOutput) {
1290 assert(!FoundOutputConstraint &&
1291 "Cannot have multiple output constraints yet!");
1292 FoundOutputConstraint = true;
1293 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1295 RetValReg = DestReg;
1298 IndirectStoresToEmit.push_back(std::make_pair(DestReg,
1299 I.getOperand(OpNum)));
1300 OpTy = I.getOperand(OpNum)->getType();
1301 OpTy = cast<PointerType>(OpTy)->getElementType();
1302 OpNum++; // Consumes a call operand.
1305 // Add information to the INLINEASM node to know that this register is
1307 AsmNodeOperands.push_back(DAG.getRegister(DestReg,
1308 TLI.getValueType(OpTy)));
1309 AsmNodeOperands.push_back(DAG.getConstant(2, MVT::i32)); // ISDEF
1313 case InlineAsm::isInput: {
1314 Value *Operand = I.getOperand(OpNum);
1315 const Type *OpTy = Operand->getType();
1316 OpNum++; // Consumes a call operand.
1319 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1320 // If this is required to match an output register we have already set,
1321 // just use its register.
1322 unsigned OperandNo = atoi(ConstraintCode.c_str());
1323 SrcReg = cast<RegisterSDNode>(AsmNodeOperands[OperandNo*2+2])->getReg();
1325 // Copy the input into the appropriate register.
1326 std::vector<unsigned> Regs =
1327 TLI.getRegForInlineAsmConstraint(ConstraintCode);
1328 if (Regs.size() == 1)
1331 SrcReg = GetAvailableRegister(false, true, Regs,
1332 OutputRegs, InputRegs);
1334 assert(SrcReg && "Couldn't allocate input reg!");
1336 Chain = DAG.getCopyToReg(Chain, SrcReg, getValue(Operand), Flag);
1337 Flag = Chain.getValue(1);
1339 // Add information to the INLINEASM node to know that this register is
1341 AsmNodeOperands.push_back(DAG.getRegister(SrcReg,TLI.getValueType(OpTy)));
1342 AsmNodeOperands.push_back(DAG.getConstant(1, MVT::i32)); // ISUSE
1345 case InlineAsm::isClobber:
1351 // Finish up input operands.
1352 AsmNodeOperands[0] = Chain;
1353 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1355 std::vector<MVT::ValueType> VTs;
1356 VTs.push_back(MVT::Other);
1357 VTs.push_back(MVT::Flag);
1358 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1359 Flag = Chain.getValue(1);
1361 // If this asm returns a register value, copy the result from that register
1362 // and set it as the value of the call.
1364 SDOperand Val = DAG.getCopyFromReg(Chain, RetValReg,
1365 TLI.getValueType(I.getType()), Flag);
1366 Chain = Val.getValue(1);
1367 Flag = Val.getValue(2);
1371 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1373 // Process indirect outputs, first output all of the flagged copies out of
1375 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
1376 Value *Ptr = IndirectStoresToEmit[i].second;
1377 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1378 SDOperand Val = DAG.getCopyFromReg(Chain, IndirectStoresToEmit[i].first,
1379 TLI.getValueType(Ty), Flag);
1380 Chain = Val.getValue(1);
1381 Flag = Val.getValue(2);
1382 StoresToEmit.push_back(std::make_pair(Val, Ptr));
1385 // Emit the non-flagged stores from the physregs.
1386 std::vector<SDOperand> OutChains;
1387 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1388 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1389 StoresToEmit[i].first,
1390 getValue(StoresToEmit[i].second),
1391 DAG.getSrcValue(StoresToEmit[i].second)));
1392 if (!OutChains.empty())
1393 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
1398 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1399 SDOperand Src = getValue(I.getOperand(0));
1401 MVT::ValueType IntPtr = TLI.getPointerTy();
1403 if (IntPtr < Src.getValueType())
1404 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1405 else if (IntPtr > Src.getValueType())
1406 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
1408 // Scale the source by the type size.
1409 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1410 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1411 Src, getIntPtrConstant(ElementSize));
1413 std::vector<std::pair<SDOperand, const Type*> > Args;
1414 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
1416 std::pair<SDOperand,SDOperand> Result =
1417 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
1418 DAG.getExternalSymbol("malloc", IntPtr),
1420 setValue(&I, Result.first); // Pointers always fit in registers
1421 DAG.setRoot(Result.second);
1424 void SelectionDAGLowering::visitFree(FreeInst &I) {
1425 std::vector<std::pair<SDOperand, const Type*> > Args;
1426 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1427 TLI.getTargetData().getIntPtrType()));
1428 MVT::ValueType IntPtr = TLI.getPointerTy();
1429 std::pair<SDOperand,SDOperand> Result =
1430 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
1431 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1432 DAG.setRoot(Result.second);
1435 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
1436 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1437 // instructions are special in various ways, which require special support to
1438 // insert. The specified MachineInstr is created but not inserted into any
1439 // basic blocks, and the scheduler passes ownership of it to this method.
1440 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1441 MachineBasicBlock *MBB) {
1442 std::cerr << "If a target marks an instruction with "
1443 "'usesCustomDAGSchedInserter', it must implement "
1444 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1449 void SelectionDAGLowering::visitVAStart(CallInst &I) {
1450 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1451 getValue(I.getOperand(1)),
1452 DAG.getSrcValue(I.getOperand(1))));
1455 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1456 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1457 getValue(I.getOperand(0)),
1458 DAG.getSrcValue(I.getOperand(0)));
1460 DAG.setRoot(V.getValue(1));
1463 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
1464 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1465 getValue(I.getOperand(1)),
1466 DAG.getSrcValue(I.getOperand(1))));
1469 void SelectionDAGLowering::visitVACopy(CallInst &I) {
1470 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1471 getValue(I.getOperand(1)),
1472 getValue(I.getOperand(2)),
1473 DAG.getSrcValue(I.getOperand(1)),
1474 DAG.getSrcValue(I.getOperand(2))));
1477 // It is always conservatively correct for llvm.returnaddress and
1478 // llvm.frameaddress to return 0.
1479 std::pair<SDOperand, SDOperand>
1480 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1481 unsigned Depth, SelectionDAG &DAG) {
1482 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
1485 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1486 assert(0 && "LowerOperation not implemented for this target!");
1491 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1492 SelectionDAG &DAG) {
1493 assert(0 && "CustomPromoteOperation not implemented for this target!");
1498 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1499 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1500 std::pair<SDOperand,SDOperand> Result =
1501 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
1502 setValue(&I, Result.first);
1503 DAG.setRoot(Result.second);
1506 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1507 std::vector<SDOperand> Ops;
1508 Ops.push_back(getRoot());
1509 Ops.push_back(getValue(I.getOperand(1)));
1510 Ops.push_back(getValue(I.getOperand(2)));
1511 Ops.push_back(getValue(I.getOperand(3)));
1512 Ops.push_back(getValue(I.getOperand(4)));
1513 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1516 //===----------------------------------------------------------------------===//
1517 // SelectionDAGISel code
1518 //===----------------------------------------------------------------------===//
1520 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1521 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1524 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1525 // FIXME: we only modify the CFG to split critical edges. This
1526 // updates dom and loop info.
1530 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1531 /// casting to the type of GEPI.
1532 static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1533 Value *Ptr, Value *PtrOffset) {
1534 if (V) return V; // Already computed.
1536 BasicBlock::iterator InsertPt;
1537 if (BB == GEPI->getParent()) {
1538 // If insert into the GEP's block, insert right after the GEP.
1542 // Otherwise, insert at the top of BB, after any PHI nodes
1543 InsertPt = BB->begin();
1544 while (isa<PHINode>(InsertPt)) ++InsertPt;
1547 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1548 // BB so that there is only one value live across basic blocks (the cast
1550 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1551 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1552 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1554 // Add the offset, cast it to the right type.
1555 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1556 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1561 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1562 /// selection, we want to be a bit careful about some things. In particular, if
1563 /// we have a GEP instruction that is used in a different block than it is
1564 /// defined, the addressing expression of the GEP cannot be folded into loads or
1565 /// stores that use it. In this case, decompose the GEP and move constant
1566 /// indices into blocks that use it.
1567 static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1568 const TargetData &TD) {
1569 // If this GEP is only used inside the block it is defined in, there is no
1570 // need to rewrite it.
1571 bool isUsedOutsideDefBB = false;
1572 BasicBlock *DefBB = GEPI->getParent();
1573 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1575 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1576 isUsedOutsideDefBB = true;
1580 if (!isUsedOutsideDefBB) return;
1582 // If this GEP has no non-zero constant indices, there is nothing we can do,
1584 bool hasConstantIndex = false;
1585 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1586 E = GEPI->op_end(); OI != E; ++OI) {
1587 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1588 if (CI->getRawValue()) {
1589 hasConstantIndex = true;
1593 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1594 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
1596 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1597 // constant offset (which we now know is non-zero) and deal with it later.
1598 uint64_t ConstantOffset = 0;
1599 const Type *UIntPtrTy = TD.getIntPtrType();
1600 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1601 const Type *Ty = GEPI->getOperand(0)->getType();
1603 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1604 E = GEPI->op_end(); OI != E; ++OI) {
1606 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1607 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1609 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1610 Ty = StTy->getElementType(Field);
1612 Ty = cast<SequentialType>(Ty)->getElementType();
1614 // Handle constant subscripts.
1615 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1616 if (CI->getRawValue() == 0) continue;
1618 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1619 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1621 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1625 // Ptr = Ptr + Idx * ElementSize;
1627 // Cast Idx to UIntPtrTy if needed.
1628 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1630 uint64_t ElementSize = TD.getTypeSize(Ty);
1631 // Mask off bits that should not be set.
1632 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1633 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1635 // Multiply by the element size and add to the base.
1636 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1637 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1641 // Make sure that the offset fits in uintptr_t.
1642 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1643 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1645 // Okay, we have now emitted all of the variable index parts to the BB that
1646 // the GEP is defined in. Loop over all of the using instructions, inserting
1647 // an "add Ptr, ConstantOffset" into each block that uses it and update the
1648 // instruction to use the newly computed value, making GEPI dead. When the
1649 // user is a load or store instruction address, we emit the add into the user
1650 // block, otherwise we use a canonical version right next to the gep (these
1651 // won't be foldable as addresses, so we might as well share the computation).
1653 std::map<BasicBlock*,Value*> InsertedExprs;
1654 while (!GEPI->use_empty()) {
1655 Instruction *User = cast<Instruction>(GEPI->use_back());
1657 // If this use is not foldable into the addressing mode, use a version
1658 // emitted in the GEP block.
1660 if (!isa<LoadInst>(User) &&
1661 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1662 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1665 // Otherwise, insert the code in the User's block so it can be folded into
1666 // any users in that block.
1667 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
1668 User->getParent(), GEPI,
1671 User->replaceUsesOfWith(GEPI, NewVal);
1674 // Finally, the GEP is dead, remove it.
1675 GEPI->eraseFromParent();
1678 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1679 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1680 RegMap = MF.getSSARegMap();
1681 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1683 // First, split all critical edges for PHI nodes with incoming values that are
1684 // constants, this way the load of the constant into a vreg will not be placed
1685 // into MBBs that are used some other way.
1687 // In this pass we also look for GEP instructions that are used across basic
1688 // blocks and rewrites them to improve basic-block-at-a-time selection.
1690 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1692 BasicBlock::iterator BBI;
1693 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1694 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1695 if (isa<Constant>(PN->getIncomingValue(i)))
1696 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1698 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1699 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1700 OptimizeGEPExpression(GEPI, TLI.getTargetData());
1703 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1705 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1706 SelectBasicBlock(I, MF, FuncInfo);
1712 SDOperand SelectionDAGISel::
1713 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1714 SDOperand Op = SDL.getValue(V);
1715 assert((Op.getOpcode() != ISD::CopyFromReg ||
1716 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1717 "Copy from a reg to the same reg!");
1719 // If this type is not legal, we must make sure to not create an invalid
1721 MVT::ValueType SrcVT = Op.getValueType();
1722 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1723 SelectionDAG &DAG = SDL.DAG;
1724 if (SrcVT == DestVT) {
1725 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1726 } else if (SrcVT < DestVT) {
1727 // The src value is promoted to the register.
1728 if (MVT::isFloatingPoint(SrcVT))
1729 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1731 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1732 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1734 // The src value is expanded into multiple registers.
1735 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1736 Op, DAG.getConstant(0, MVT::i32));
1737 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1738 Op, DAG.getConstant(1, MVT::i32));
1739 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1740 return DAG.getCopyToReg(Op, Reg+1, Hi);
1744 void SelectionDAGISel::
1745 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1746 std::vector<SDOperand> &UnorderedChains) {
1747 // If this is the entry block, emit arguments.
1748 Function &F = *BB->getParent();
1749 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1750 SDOperand OldRoot = SDL.DAG.getRoot();
1751 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1754 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1756 if (!AI->use_empty()) {
1757 SDL.setValue(AI, Args[a]);
1759 // If this argument is live outside of the entry block, insert a copy from
1760 // whereever we got it to the vreg that other BB's will reference it as.
1761 if (FuncInfo.ValueMap.count(AI)) {
1763 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1764 UnorderedChains.push_back(Copy);
1768 // Next, if the function has live ins that need to be copied into vregs,
1769 // emit the copies now, into the top of the block.
1770 MachineFunction &MF = SDL.DAG.getMachineFunction();
1771 if (MF.livein_begin() != MF.livein_end()) {
1772 SSARegMap *RegMap = MF.getSSARegMap();
1773 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1774 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1775 E = MF.livein_end(); LI != E; ++LI)
1777 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1778 LI->first, RegMap->getRegClass(LI->second));
1781 // Finally, if the target has anything special to do, allow it to do so.
1782 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1786 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1787 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1788 FunctionLoweringInfo &FuncInfo) {
1789 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1791 std::vector<SDOperand> UnorderedChains;
1793 // Lower any arguments needed in this block if this is the entry block.
1794 if (LLVMBB == &LLVMBB->getParent()->front())
1795 LowerArguments(LLVMBB, SDL, UnorderedChains);
1797 BB = FuncInfo.MBBMap[LLVMBB];
1798 SDL.setCurrentBasicBlock(BB);
1800 // Lower all of the non-terminator instructions.
1801 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1805 // Ensure that all instructions which are used outside of their defining
1806 // blocks are available as virtual registers.
1807 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1808 if (!I->use_empty() && !isa<PHINode>(I)) {
1809 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1810 if (VMI != FuncInfo.ValueMap.end())
1811 UnorderedChains.push_back(
1812 CopyValueToVirtualRegister(SDL, I, VMI->second));
1815 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1816 // ensure constants are generated when needed. Remember the virtual registers
1817 // that need to be added to the Machine PHI nodes as input. We cannot just
1818 // directly add them, because expansion might result in multiple MBB's for one
1819 // BB. As such, the start of the BB might correspond to a different MBB than
1823 // Emit constants only once even if used by multiple PHI nodes.
1824 std::map<Constant*, unsigned> ConstantsOut;
1826 // Check successor nodes PHI nodes that expect a constant to be available from
1828 TerminatorInst *TI = LLVMBB->getTerminator();
1829 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1830 BasicBlock *SuccBB = TI->getSuccessor(succ);
1831 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1834 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1835 // nodes and Machine PHI nodes, but the incoming operands have not been
1837 for (BasicBlock::iterator I = SuccBB->begin();
1838 (PN = dyn_cast<PHINode>(I)); ++I)
1839 if (!PN->use_empty()) {
1841 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1842 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1843 unsigned &RegOut = ConstantsOut[C];
1845 RegOut = FuncInfo.CreateRegForValue(C);
1846 UnorderedChains.push_back(
1847 CopyValueToVirtualRegister(SDL, C, RegOut));
1851 Reg = FuncInfo.ValueMap[PHIOp];
1853 assert(isa<AllocaInst>(PHIOp) &&
1854 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1855 "Didn't codegen value into a register!??");
1856 Reg = FuncInfo.CreateRegForValue(PHIOp);
1857 UnorderedChains.push_back(
1858 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1862 // Remember that this register needs to added to the machine PHI node as
1863 // the input for this MBB.
1864 unsigned NumElements =
1865 TLI.getNumElements(TLI.getValueType(PN->getType()));
1866 for (unsigned i = 0, e = NumElements; i != e; ++i)
1867 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1870 ConstantsOut.clear();
1872 // Turn all of the unordered chains into one factored node.
1873 if (!UnorderedChains.empty()) {
1874 SDOperand Root = SDL.getRoot();
1875 if (Root.getOpcode() != ISD::EntryToken) {
1876 unsigned i = 0, e = UnorderedChains.size();
1877 for (; i != e; ++i) {
1878 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1879 if (UnorderedChains[i].Val->getOperand(0) == Root)
1880 break; // Don't add the root if we already indirectly depend on it.
1884 UnorderedChains.push_back(Root);
1886 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1889 // Lower the terminator after the copies are emitted.
1890 SDL.visit(*LLVMBB->getTerminator());
1892 // Make sure the root of the DAG is up-to-date.
1893 DAG.setRoot(SDL.getRoot());
1896 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1897 FunctionLoweringInfo &FuncInfo) {
1898 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
1900 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1902 // First step, lower LLVM code to some DAG. This DAG may use operations and
1903 // types that are not supported by the target.
1904 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1906 // Run the DAG combiner in pre-legalize mode.
1909 DEBUG(std::cerr << "Lowered selection DAG:\n");
1912 // Second step, hack on the DAG until it only uses operations and types that
1913 // the target supports.
1916 DEBUG(std::cerr << "Legalized selection DAG:\n");
1919 // Run the DAG combiner in post-legalize mode.
1922 if (ViewISelDAGs) DAG.viewGraph();
1924 // Third, instruction select all of the operations to machine code, adding the
1925 // code to the MachineBasicBlock.
1926 InstructionSelectBasicBlock(DAG);
1928 DEBUG(std::cerr << "Selected machine code:\n");
1931 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1932 // PHI nodes in successors.
1933 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1934 MachineInstr *PHI = PHINodesToUpdate[i].first;
1935 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1936 "This is not a machine PHI node that we are updating!");
1937 PHI->addRegOperand(PHINodesToUpdate[i].second);
1938 PHI->addMachineBasicBlockOperand(BB);
1941 // Finally, add the CFG edges from the last selected MBB to the successor
1943 TerminatorInst *TI = LLVMBB->getTerminator();
1944 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1945 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1946 BB->addSuccessor(Succ0MBB);
1950 //===----------------------------------------------------------------------===//
1951 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
1952 /// target node in the graph.
1953 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
1954 if (ViewSchedDAGs) DAG.viewGraph();
1955 ScheduleDAG *SL = NULL;
1957 switch (ISHeuristic) {
1958 default: assert(0 && "Unrecognized scheduling heuristic");
1959 case defaultScheduling:
1960 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
1961 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
1962 else /* TargetLowering::SchedulingForRegPressure */
1963 SL = createBURRListDAGScheduler(DAG, BB);
1966 case simpleScheduling:
1967 case simpleNoItinScheduling:
1968 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
1970 case listSchedulingBURR:
1971 SL = createBURRListDAGScheduler(DAG, BB);