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/GlobalVariable.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/CodeGen/IntrinsicLowering.h"
24 #include "llvm/CodeGen/MachineDebugInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/SSARegMap.h"
30 #include "llvm/Target/MRegisterInfo.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetFrameInfo.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/Debug.h"
46 ViewDAGs("view-isel-dags", cl::Hidden,
47 cl::desc("Pop up a window to show isel dags as they are selected"));
49 static const bool ViewDAGs = 0;
53 //===--------------------------------------------------------------------===//
54 /// FunctionLoweringInfo - This contains information that is global to a
55 /// function that is used when lowering a region of the function.
56 class FunctionLoweringInfo {
63 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
65 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
66 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
68 /// ValueMap - Since we emit code for the function a basic block at a time,
69 /// we must remember which virtual registers hold the values for
70 /// cross-basic-block values.
71 std::map<const Value*, unsigned> ValueMap;
73 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
74 /// the entry block. This allows the allocas to be efficiently referenced
75 /// anywhere in the function.
76 std::map<const AllocaInst*, int> StaticAllocaMap;
78 unsigned MakeReg(MVT::ValueType VT) {
79 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
82 unsigned CreateRegForValue(const Value *V) {
83 MVT::ValueType VT = TLI.getValueType(V->getType());
84 // The common case is that we will only create one register for this
85 // value. If we have that case, create and return the virtual register.
86 unsigned NV = TLI.getNumElements(VT);
88 // If we are promoting this value, pick the next largest supported type.
89 return MakeReg(TLI.getTypeToTransformTo(VT));
92 // If this value is represented with multiple target registers, make sure
93 // to create enough consequtive registers of the right (smaller) type.
94 unsigned NT = VT-1; // Find the type to use.
95 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
98 unsigned R = MakeReg((MVT::ValueType)NT);
99 for (unsigned i = 1; i != NV; ++i)
100 MakeReg((MVT::ValueType)NT);
104 unsigned InitializeRegForValue(const Value *V) {
105 unsigned &R = ValueMap[V];
106 assert(R == 0 && "Already initialized this value register!");
107 return R = CreateRegForValue(V);
112 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
113 /// PHI nodes or outside of the basic block that defines it.
114 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
115 if (isa<PHINode>(I)) return true;
116 BasicBlock *BB = I->getParent();
117 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
118 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
123 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
124 /// entry block, return true.
125 static bool isOnlyUsedInEntryBlock(Argument *A) {
126 BasicBlock *Entry = A->getParent()->begin();
127 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
128 if (cast<Instruction>(*UI)->getParent() != Entry)
129 return false; // Use not in entry block.
133 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
134 Function &fn, MachineFunction &mf)
135 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
137 // Create a vreg for each argument register that is not dead and is used
138 // outside of the entry block for the function.
139 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
141 if (!isOnlyUsedInEntryBlock(AI))
142 InitializeRegForValue(AI);
144 // Initialize the mapping of values to registers. This is only set up for
145 // instruction values that are used outside of the block that defines
147 Function::iterator BB = Fn.begin(), EB = Fn.end();
148 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
149 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
150 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
151 const Type *Ty = AI->getAllocatedType();
152 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
154 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
157 // If the alignment of the value is smaller than the size of the value,
158 // and if the size of the value is particularly small (<= 8 bytes),
159 // round up to the size of the value for potentially better performance.
161 // FIXME: This could be made better with a preferred alignment hook in
162 // TargetData. It serves primarily to 8-byte align doubles for X86.
163 if (Align < TySize && TySize <= 8) Align = TySize;
164 TySize *= CUI->getValue(); // Get total allocated size.
165 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
166 StaticAllocaMap[AI] =
167 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
170 for (; BB != EB; ++BB)
171 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
172 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
173 if (!isa<AllocaInst>(I) ||
174 !StaticAllocaMap.count(cast<AllocaInst>(I)))
175 InitializeRegForValue(I);
177 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
178 // also creates the initial PHI MachineInstrs, though none of the input
179 // operands are populated.
180 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
181 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
183 MF.getBasicBlockList().push_back(MBB);
185 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
188 for (BasicBlock::iterator I = BB->begin();
189 (PN = dyn_cast<PHINode>(I)); ++I)
190 if (!PN->use_empty()) {
191 unsigned NumElements =
192 TLI.getNumElements(TLI.getValueType(PN->getType()));
193 unsigned PHIReg = ValueMap[PN];
194 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
195 for (unsigned i = 0; i != NumElements; ++i)
196 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
203 //===----------------------------------------------------------------------===//
204 /// SelectionDAGLowering - This is the common target-independent lowering
205 /// implementation that is parameterized by a TargetLowering object.
206 /// Also, targets can overload any lowering method.
209 class SelectionDAGLowering {
210 MachineBasicBlock *CurMBB;
212 std::map<const Value*, SDOperand> NodeMap;
214 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
215 /// them up and then emit token factor nodes when possible. This allows us to
216 /// get simple disambiguation between loads without worrying about alias
218 std::vector<SDOperand> PendingLoads;
221 // TLI - This is information that describes the available target features we
222 // need for lowering. This indicates when operations are unavailable,
223 // implemented with a libcall, etc.
226 const TargetData &TD;
228 /// FuncInfo - Information about the function as a whole.
230 FunctionLoweringInfo &FuncInfo;
232 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
233 FunctionLoweringInfo &funcinfo)
234 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
238 /// getRoot - Return the current virtual root of the Selection DAG.
240 SDOperand getRoot() {
241 if (PendingLoads.empty())
242 return DAG.getRoot();
244 if (PendingLoads.size() == 1) {
245 SDOperand Root = PendingLoads[0];
247 PendingLoads.clear();
251 // Otherwise, we have to make a token factor node.
252 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
253 PendingLoads.clear();
258 void visit(Instruction &I) { visit(I.getOpcode(), I); }
260 void visit(unsigned Opcode, User &I) {
262 default: assert(0 && "Unknown instruction type encountered!");
264 // Build the switch statement using the Instruction.def file.
265 #define HANDLE_INST(NUM, OPCODE, CLASS) \
266 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
267 #include "llvm/Instruction.def"
271 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
274 SDOperand getIntPtrConstant(uint64_t Val) {
275 return DAG.getConstant(Val, TLI.getPointerTy());
278 SDOperand getValue(const Value *V) {
279 SDOperand &N = NodeMap[V];
282 const Type *VTy = V->getType();
283 MVT::ValueType VT = TLI.getValueType(VTy);
284 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
285 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
286 visit(CE->getOpcode(), *CE);
287 assert(N.Val && "visit didn't populate the ValueMap!");
289 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
290 return N = DAG.getGlobalAddress(GV, VT);
291 } else if (isa<ConstantPointerNull>(C)) {
292 return N = DAG.getConstant(0, TLI.getPointerTy());
293 } else if (isa<UndefValue>(C)) {
294 return N = DAG.getNode(ISD::UNDEF, VT);
295 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
296 return N = DAG.getConstantFP(CFP->getValue(), VT);
297 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
298 unsigned NumElements = PTy->getNumElements();
299 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
300 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
302 // Now that we know the number and type of the elements, push a
303 // Constant or ConstantFP node onto the ops list for each element of
304 // the packed constant.
305 std::vector<SDOperand> Ops;
306 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
307 if (MVT::isFloatingPoint(PVT)) {
308 for (unsigned i = 0; i != NumElements; ++i) {
309 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
310 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
313 for (unsigned i = 0; i != NumElements; ++i) {
314 const ConstantIntegral *El =
315 cast<ConstantIntegral>(CP->getOperand(i));
316 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
320 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
322 if (MVT::isFloatingPoint(PVT))
323 Op = DAG.getConstantFP(0, PVT);
325 Op = DAG.getConstant(0, PVT);
326 Ops.assign(NumElements, Op);
329 // Handle the case where we have a 1-element vector, in which
330 // case we want to immediately turn it into a scalar constant.
331 if (Ops.size() == 1) {
333 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
334 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
336 // If the packed type isn't legal, then create a ConstantVec node with
337 // generic Vector type instead.
338 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
341 // Canonicalize all constant ints to be unsigned.
342 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
345 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
346 std::map<const AllocaInst*, int>::iterator SI =
347 FuncInfo.StaticAllocaMap.find(AI);
348 if (SI != FuncInfo.StaticAllocaMap.end())
349 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
352 std::map<const Value*, unsigned>::const_iterator VMI =
353 FuncInfo.ValueMap.find(V);
354 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
356 unsigned InReg = VMI->second;
358 // If this type is not legal, make it so now.
359 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
361 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
363 // Source must be expanded. This input value is actually coming from the
364 // register pair VMI->second and VMI->second+1.
365 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
366 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
368 if (DestVT > VT) { // Promotion case
369 if (MVT::isFloatingPoint(VT))
370 N = DAG.getNode(ISD::FP_ROUND, VT, N);
372 N = DAG.getNode(ISD::TRUNCATE, VT, N);
379 const SDOperand &setValue(const Value *V, SDOperand NewN) {
380 SDOperand &N = NodeMap[V];
381 assert(N.Val == 0 && "Already set a value for this node!");
385 // Terminator instructions.
386 void visitRet(ReturnInst &I);
387 void visitBr(BranchInst &I);
388 void visitUnreachable(UnreachableInst &I) { /* noop */ }
390 // These all get lowered before this pass.
391 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
392 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
393 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
394 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
395 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
398 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
399 void visitShift(User &I, unsigned Opcode);
400 void visitAdd(User &I) {
401 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
403 void visitSub(User &I);
404 void visitMul(User &I) {
405 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
407 void visitDiv(User &I) {
408 const Type *Ty = I.getType();
409 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
411 void visitRem(User &I) {
412 const Type *Ty = I.getType();
413 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
415 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
416 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
417 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
418 void visitShl(User &I) { visitShift(I, ISD::SHL); }
419 void visitShr(User &I) {
420 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
423 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
424 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
425 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
426 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
427 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
428 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
429 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
431 void visitGetElementPtr(User &I);
432 void visitCast(User &I);
433 void visitSelect(User &I);
436 void visitMalloc(MallocInst &I);
437 void visitFree(FreeInst &I);
438 void visitAlloca(AllocaInst &I);
439 void visitLoad(LoadInst &I);
440 void visitStore(StoreInst &I);
441 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
442 void visitCall(CallInst &I);
443 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
445 void visitVAStart(CallInst &I);
446 void visitVAArg(VAArgInst &I);
447 void visitVAEnd(CallInst &I);
448 void visitVACopy(CallInst &I);
449 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
451 void visitMemIntrinsic(CallInst &I, unsigned Op);
453 void visitUserOp1(Instruction &I) {
454 assert(0 && "UserOp1 should not exist at instruction selection time!");
457 void visitUserOp2(Instruction &I) {
458 assert(0 && "UserOp2 should not exist at instruction selection time!");
462 } // end namespace llvm
464 void SelectionDAGLowering::visitRet(ReturnInst &I) {
465 if (I.getNumOperands() == 0) {
466 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
470 SDOperand Op1 = getValue(I.getOperand(0));
471 MVT::ValueType TmpVT;
473 switch (Op1.getValueType()) {
474 default: assert(0 && "Unknown value type!");
479 // If this is a machine where 32-bits is legal or expanded, promote to
480 // 32-bits, otherwise, promote to 64-bits.
481 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
482 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
486 // Extend integer types to result type.
487 if (I.getOperand(0)->getType()->isSigned())
488 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
490 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
495 break; // No extension needed!
497 // Allow targets to lower this further to meet ABI requirements
498 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
501 void SelectionDAGLowering::visitBr(BranchInst &I) {
502 // Update machine-CFG edges.
503 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
505 // Figure out which block is immediately after the current one.
506 MachineBasicBlock *NextBlock = 0;
507 MachineFunction::iterator BBI = CurMBB;
508 if (++BBI != CurMBB->getParent()->end())
511 if (I.isUnconditional()) {
512 // If this is not a fall-through branch, emit the branch.
513 if (Succ0MBB != NextBlock)
514 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
515 DAG.getBasicBlock(Succ0MBB)));
517 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
519 SDOperand Cond = getValue(I.getCondition());
520 if (Succ1MBB == NextBlock) {
521 // If the condition is false, fall through. This means we should branch
522 // if the condition is true to Succ #0.
523 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
524 Cond, DAG.getBasicBlock(Succ0MBB)));
525 } else if (Succ0MBB == NextBlock) {
526 // If the condition is true, fall through. This means we should branch if
527 // the condition is false to Succ #1. Invert the condition first.
528 SDOperand True = DAG.getConstant(1, Cond.getValueType());
529 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
530 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
531 Cond, DAG.getBasicBlock(Succ1MBB)));
533 std::vector<SDOperand> Ops;
534 Ops.push_back(getRoot());
536 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
537 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
538 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
543 void SelectionDAGLowering::visitSub(User &I) {
545 if (I.getType()->isFloatingPoint()) {
546 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
547 if (CFP->isExactlyValue(-0.0)) {
548 SDOperand Op2 = getValue(I.getOperand(1));
549 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
553 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
556 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
558 const Type *Ty = I.getType();
559 SDOperand Op1 = getValue(I.getOperand(0));
560 SDOperand Op2 = getValue(I.getOperand(1));
562 if (Ty->isIntegral()) {
563 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
564 } else if (Ty->isFloatingPoint()) {
565 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
567 const PackedType *PTy = cast<PackedType>(Ty);
568 unsigned NumElements = PTy->getNumElements();
569 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
570 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
572 // Immediately scalarize packed types containing only one element, so that
573 // the Legalize pass does not have to deal with them. Similarly, if the
574 // abstract vector is going to turn into one that the target natively
575 // supports, generate that type now so that Legalize doesn't have to deal
576 // with that either. These steps ensure that Legalize only has to handle
577 // vector types in its Expand case.
578 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
579 if (NumElements == 1) {
580 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
581 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
582 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
584 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
585 SDOperand Typ = DAG.getValueType(PVT);
586 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
591 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
592 SDOperand Op1 = getValue(I.getOperand(0));
593 SDOperand Op2 = getValue(I.getOperand(1));
595 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
597 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
600 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
601 ISD::CondCode UnsignedOpcode) {
602 SDOperand Op1 = getValue(I.getOperand(0));
603 SDOperand Op2 = getValue(I.getOperand(1));
604 ISD::CondCode Opcode = SignedOpcode;
605 if (I.getOperand(0)->getType()->isUnsigned())
606 Opcode = UnsignedOpcode;
607 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
610 void SelectionDAGLowering::visitSelect(User &I) {
611 SDOperand Cond = getValue(I.getOperand(0));
612 SDOperand TrueVal = getValue(I.getOperand(1));
613 SDOperand FalseVal = getValue(I.getOperand(2));
614 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
618 void SelectionDAGLowering::visitCast(User &I) {
619 SDOperand N = getValue(I.getOperand(0));
620 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
621 MVT::ValueType DestTy = TLI.getValueType(I.getType());
623 if (N.getValueType() == DestTy) {
624 setValue(&I, N); // noop cast.
625 } else if (DestTy == MVT::i1) {
626 // Cast to bool is a comparison against zero, not truncation to zero.
627 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
628 DAG.getConstantFP(0.0, N.getValueType());
629 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
630 } else if (isInteger(SrcTy)) {
631 if (isInteger(DestTy)) { // Int -> Int cast
632 if (DestTy < SrcTy) // Truncating cast?
633 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
634 else if (I.getOperand(0)->getType()->isSigned())
635 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
637 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
638 } else { // Int -> FP cast
639 if (I.getOperand(0)->getType()->isSigned())
640 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
642 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
645 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
646 if (isFloatingPoint(DestTy)) { // FP -> FP cast
647 if (DestTy < SrcTy) // Rounding cast?
648 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
650 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
651 } else { // FP -> Int cast.
652 if (I.getType()->isSigned())
653 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
655 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
660 void SelectionDAGLowering::visitGetElementPtr(User &I) {
661 SDOperand N = getValue(I.getOperand(0));
662 const Type *Ty = I.getOperand(0)->getType();
663 const Type *UIntPtrTy = TD.getIntPtrType();
665 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
668 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
669 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
672 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
673 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
674 getIntPtrConstant(Offset));
676 Ty = StTy->getElementType(Field);
678 Ty = cast<SequentialType>(Ty)->getElementType();
680 // If this is a constant subscript, handle it quickly.
681 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
682 if (CI->getRawValue() == 0) continue;
685 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
686 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
688 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
689 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
693 // N = N + Idx * ElementSize;
694 uint64_t ElementSize = TD.getTypeSize(Ty);
695 SDOperand IdxN = getValue(Idx);
697 // If the index is smaller or larger than intptr_t, truncate or extend
699 if (IdxN.getValueType() < N.getValueType()) {
700 if (Idx->getType()->isSigned())
701 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
703 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
704 } else if (IdxN.getValueType() > N.getValueType())
705 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
707 // If this is a multiply by a power of two, turn it into a shl
708 // immediately. This is a very common case.
709 if (isPowerOf2_64(ElementSize)) {
710 unsigned Amt = Log2_64(ElementSize);
711 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
712 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
713 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
717 SDOperand Scale = getIntPtrConstant(ElementSize);
718 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
719 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
725 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
726 // If this is a fixed sized alloca in the entry block of the function,
727 // allocate it statically on the stack.
728 if (FuncInfo.StaticAllocaMap.count(&I))
729 return; // getValue will auto-populate this.
731 const Type *Ty = I.getAllocatedType();
732 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
733 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
736 SDOperand AllocSize = getValue(I.getArraySize());
737 MVT::ValueType IntPtr = TLI.getPointerTy();
738 if (IntPtr < AllocSize.getValueType())
739 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
740 else if (IntPtr > AllocSize.getValueType())
741 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
743 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
744 getIntPtrConstant(TySize));
746 // Handle alignment. If the requested alignment is less than or equal to the
747 // stack alignment, ignore it and round the size of the allocation up to the
748 // stack alignment size. If the size is greater than the stack alignment, we
749 // note this in the DYNAMIC_STACKALLOC node.
750 unsigned StackAlign =
751 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
752 if (Align <= StackAlign) {
754 // Add SA-1 to the size.
755 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
756 getIntPtrConstant(StackAlign-1));
757 // Mask out the low bits for alignment purposes.
758 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
759 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
762 std::vector<MVT::ValueType> VTs;
763 VTs.push_back(AllocSize.getValueType());
764 VTs.push_back(MVT::Other);
765 std::vector<SDOperand> Ops;
766 Ops.push_back(getRoot());
767 Ops.push_back(AllocSize);
768 Ops.push_back(getIntPtrConstant(Align));
769 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
770 DAG.setRoot(setValue(&I, DSA).getValue(1));
772 // Inform the Frame Information that we have just allocated a variable-sized
774 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
777 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
778 /// global into a string value. Return an empty string if we can't do it.
780 static std::string getStringValue(Value *V, unsigned Offset = 0) {
781 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
782 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
783 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
784 if (Init->isString()) {
785 std::string Result = Init->getAsString();
786 if (Offset < Result.size()) {
787 // If we are pointing INTO The string, erase the beginning...
788 Result.erase(Result.begin(), Result.begin()+Offset);
790 // Take off the null terminator, and any string fragments after it.
791 std::string::size_type NullPos = Result.find_first_of((char)0);
792 if (NullPos != std::string::npos)
793 Result.erase(Result.begin()+NullPos, Result.end());
798 } else if (Constant *C = dyn_cast<Constant>(V)) {
799 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
800 return getStringValue(GV, Offset);
801 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
802 if (CE->getOpcode() == Instruction::GetElementPtr) {
803 // Turn a gep into the specified offset.
804 if (CE->getNumOperands() == 3 &&
805 cast<Constant>(CE->getOperand(1))->isNullValue() &&
806 isa<ConstantInt>(CE->getOperand(2))) {
807 return getStringValue(CE->getOperand(0),
808 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
816 void SelectionDAGLowering::visitLoad(LoadInst &I) {
817 SDOperand Ptr = getValue(I.getOperand(0));
823 // Do not serialize non-volatile loads against each other.
824 Root = DAG.getRoot();
827 const Type *Ty = I.getType();
830 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
831 unsigned NumElements = PTy->getNumElements();
832 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
833 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
835 // Immediately scalarize packed types containing only one element, so that
836 // the Legalize pass does not have to deal with them.
837 if (NumElements == 1) {
838 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
839 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
840 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
842 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
843 DAG.getSrcValue(I.getOperand(0)));
846 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
847 DAG.getSrcValue(I.getOperand(0)));
852 DAG.setRoot(L.getValue(1));
854 PendingLoads.push_back(L.getValue(1));
858 void SelectionDAGLowering::visitStore(StoreInst &I) {
859 Value *SrcV = I.getOperand(0);
860 SDOperand Src = getValue(SrcV);
861 SDOperand Ptr = getValue(I.getOperand(1));
862 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
863 DAG.getSrcValue(I.getOperand(1))));
866 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
867 /// we want to emit this as a call to a named external function, return the name
868 /// otherwise lower it and return null.
870 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
872 case Intrinsic::vastart: visitVAStart(I); return 0;
873 case Intrinsic::vaend: visitVAEnd(I); return 0;
874 case Intrinsic::vacopy: visitVACopy(I); return 0;
875 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
876 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
877 case Intrinsic::setjmp:
878 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
880 case Intrinsic::longjmp:
881 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
883 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
884 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
885 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
887 case Intrinsic::readport:
888 case Intrinsic::readio: {
889 std::vector<MVT::ValueType> VTs;
890 VTs.push_back(TLI.getValueType(I.getType()));
891 VTs.push_back(MVT::Other);
892 std::vector<SDOperand> Ops;
893 Ops.push_back(getRoot());
894 Ops.push_back(getValue(I.getOperand(1)));
895 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
896 ISD::READPORT : ISD::READIO, VTs, Ops);
899 DAG.setRoot(Tmp.getValue(1));
902 case Intrinsic::writeport:
903 case Intrinsic::writeio:
904 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
905 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
906 getRoot(), getValue(I.getOperand(1)),
907 getValue(I.getOperand(2))));
910 case Intrinsic::dbg_stoppoint: {
911 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
912 return "llvm_debugger_stop";
914 std::string fname = "<unknown>";
915 std::vector<SDOperand> Ops;
918 Ops.push_back(getRoot());
921 Ops.push_back(getValue(I.getOperand(2)));
924 Ops.push_back(getValue(I.getOperand(3)));
926 // filename/working dir
927 // Pull the filename out of the the compilation unit.
928 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
929 if (cunit && cunit->hasInitializer()) {
930 if (ConstantStruct *CS =
931 dyn_cast<ConstantStruct>(cunit->getInitializer())) {
932 if (CS->getNumOperands() > 0) {
933 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
934 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
939 if (Ops.size() == 5) // Found filename/workingdir.
940 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
941 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
944 case Intrinsic::dbg_region_start:
945 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
946 return "llvm_dbg_region_start";
947 if (I.getType() != Type::VoidTy)
948 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
950 case Intrinsic::dbg_region_end:
951 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
952 return "llvm_dbg_region_end";
953 if (I.getType() != Type::VoidTy)
954 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
956 case Intrinsic::dbg_func_start:
957 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
958 return "llvm_dbg_subprogram";
959 if (I.getType() != Type::VoidTy)
960 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
962 case Intrinsic::dbg_declare:
963 if (I.getType() != Type::VoidTy)
964 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
967 case Intrinsic::isunordered_f32:
968 case Intrinsic::isunordered_f64:
969 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
970 getValue(I.getOperand(2)), ISD::SETUO));
973 case Intrinsic::sqrt_f32:
974 case Intrinsic::sqrt_f64:
975 setValue(&I, DAG.getNode(ISD::FSQRT,
976 getValue(I.getOperand(1)).getValueType(),
977 getValue(I.getOperand(1))));
979 case Intrinsic::pcmarker: {
980 SDOperand Tmp = getValue(I.getOperand(1));
981 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
984 case Intrinsic::readcyclecounter: {
985 std::vector<MVT::ValueType> VTs;
986 VTs.push_back(MVT::i64);
987 VTs.push_back(MVT::Other);
988 std::vector<SDOperand> Ops;
989 Ops.push_back(getRoot());
990 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
992 DAG.setRoot(Tmp.getValue(1));
995 case Intrinsic::bswap_i16:
996 case Intrinsic::bswap_i32:
997 case Intrinsic::bswap_i64:
998 setValue(&I, DAG.getNode(ISD::BSWAP,
999 getValue(I.getOperand(1)).getValueType(),
1000 getValue(I.getOperand(1))));
1002 case Intrinsic::cttz_i8:
1003 case Intrinsic::cttz_i16:
1004 case Intrinsic::cttz_i32:
1005 case Intrinsic::cttz_i64:
1006 setValue(&I, DAG.getNode(ISD::CTTZ,
1007 getValue(I.getOperand(1)).getValueType(),
1008 getValue(I.getOperand(1))));
1010 case Intrinsic::ctlz_i8:
1011 case Intrinsic::ctlz_i16:
1012 case Intrinsic::ctlz_i32:
1013 case Intrinsic::ctlz_i64:
1014 setValue(&I, DAG.getNode(ISD::CTLZ,
1015 getValue(I.getOperand(1)).getValueType(),
1016 getValue(I.getOperand(1))));
1018 case Intrinsic::ctpop_i8:
1019 case Intrinsic::ctpop_i16:
1020 case Intrinsic::ctpop_i32:
1021 case Intrinsic::ctpop_i64:
1022 setValue(&I, DAG.getNode(ISD::CTPOP,
1023 getValue(I.getOperand(1)).getValueType(),
1024 getValue(I.getOperand(1))));
1026 case Intrinsic::stacksave: {
1027 std::vector<MVT::ValueType> VTs;
1028 VTs.push_back(TLI.getPointerTy());
1029 VTs.push_back(MVT::Other);
1030 std::vector<SDOperand> Ops;
1031 Ops.push_back(getRoot());
1032 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1034 DAG.setRoot(Tmp.getValue(1));
1037 case Intrinsic::stackrestore:
1038 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, DAG.getRoot(),
1039 getValue(I.getOperand(1))));
1041 case Intrinsic::prefetch:
1042 // FIXME: Currently discarding prefetches.
1046 assert(0 && "This intrinsic is not implemented yet!");
1052 void SelectionDAGLowering::visitCall(CallInst &I) {
1053 const char *RenameFn = 0;
1054 if (Function *F = I.getCalledFunction()) {
1055 if (F->isExternal())
1056 if (unsigned IID = F->getIntrinsicID()) {
1057 RenameFn = visitIntrinsicCall(I, IID);
1060 } else { // Not an LLVM intrinsic.
1061 const std::string &Name = F->getName();
1062 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1063 if (I.getNumOperands() == 2 && // Basic sanity checks.
1064 I.getOperand(1)->getType()->isFloatingPoint() &&
1065 I.getType() == I.getOperand(1)->getType()) {
1066 SDOperand Tmp = getValue(I.getOperand(1));
1067 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1070 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1071 if (I.getNumOperands() == 2 && // Basic sanity checks.
1072 I.getOperand(1)->getType()->isFloatingPoint() &&
1073 I.getType() == I.getOperand(1)->getType() &&
1074 TLI.isOperationLegal(ISD::FSIN,
1075 TLI.getValueType(I.getOperand(1)->getType()))) {
1076 SDOperand Tmp = getValue(I.getOperand(1));
1077 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1080 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1081 if (I.getNumOperands() == 2 && // Basic sanity checks.
1082 I.getOperand(1)->getType()->isFloatingPoint() &&
1083 I.getType() == I.getOperand(1)->getType() &&
1084 TLI.isOperationLegal(ISD::FCOS,
1085 TLI.getValueType(I.getOperand(1)->getType()))) {
1086 SDOperand Tmp = getValue(I.getOperand(1));
1087 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1096 Callee = getValue(I.getOperand(0));
1098 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1099 std::vector<std::pair<SDOperand, const Type*> > Args;
1100 Args.reserve(I.getNumOperands());
1101 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1102 Value *Arg = I.getOperand(i);
1103 SDOperand ArgNode = getValue(Arg);
1104 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1107 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1108 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1110 std::pair<SDOperand,SDOperand> Result =
1111 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1112 I.isTailCall(), Callee, Args, DAG);
1113 if (I.getType() != Type::VoidTy)
1114 setValue(&I, Result.first);
1115 DAG.setRoot(Result.second);
1118 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1119 SDOperand Src = getValue(I.getOperand(0));
1121 MVT::ValueType IntPtr = TLI.getPointerTy();
1123 if (IntPtr < Src.getValueType())
1124 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1125 else if (IntPtr > Src.getValueType())
1126 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
1128 // Scale the source by the type size.
1129 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1130 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1131 Src, getIntPtrConstant(ElementSize));
1133 std::vector<std::pair<SDOperand, const Type*> > Args;
1134 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
1136 std::pair<SDOperand,SDOperand> Result =
1137 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
1138 DAG.getExternalSymbol("malloc", IntPtr),
1140 setValue(&I, Result.first); // Pointers always fit in registers
1141 DAG.setRoot(Result.second);
1144 void SelectionDAGLowering::visitFree(FreeInst &I) {
1145 std::vector<std::pair<SDOperand, const Type*> > Args;
1146 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1147 TLI.getTargetData().getIntPtrType()));
1148 MVT::ValueType IntPtr = TLI.getPointerTy();
1149 std::pair<SDOperand,SDOperand> Result =
1150 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
1151 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1152 DAG.setRoot(Result.second);
1155 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
1156 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1157 // instructions are special in various ways, which require special support to
1158 // insert. The specified MachineInstr is created but not inserted into any
1159 // basic blocks, and the scheduler passes ownership of it to this method.
1160 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1161 MachineBasicBlock *MBB) {
1162 std::cerr << "If a target marks an instruction with "
1163 "'usesCustomDAGSchedInserter', it must implement "
1164 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1169 SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1170 SelectionDAG &DAG) {
1171 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1174 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1175 SDOperand VAListP, Value *VAListV,
1176 SelectionDAG &DAG) {
1177 // We have no sane default behavior, just emit a useful error message and bail
1179 std::cerr << "Variable arguments handling not implemented on this target!\n";
1184 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
1185 SelectionDAG &DAG) {
1186 // Default to a noop.
1190 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1191 SDOperand SrcP, Value *SrcV,
1192 SDOperand DestP, Value *DestV,
1193 SelectionDAG &DAG) {
1194 // Default to copying the input list.
1195 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1196 SrcP, DAG.getSrcValue(SrcV));
1197 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
1198 Val, DestP, DAG.getSrcValue(DestV));
1202 std::pair<SDOperand,SDOperand>
1203 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1204 const Type *ArgTy, SelectionDAG &DAG) {
1205 // We have no sane default behavior, just emit a useful error message and bail
1207 std::cerr << "Variable arguments handling not implemented on this target!\n";
1209 return std::make_pair(SDOperand(), SDOperand());
1213 void SelectionDAGLowering::visitVAStart(CallInst &I) {
1214 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1215 I.getOperand(1), DAG));
1218 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1219 std::pair<SDOperand,SDOperand> Result =
1220 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
1222 setValue(&I, Result.first);
1223 DAG.setRoot(Result.second);
1226 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
1227 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
1228 I.getOperand(1), DAG));
1231 void SelectionDAGLowering::visitVACopy(CallInst &I) {
1233 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1234 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1235 DAG.setRoot(Result);
1239 // It is always conservatively correct for llvm.returnaddress and
1240 // llvm.frameaddress to return 0.
1241 std::pair<SDOperand, SDOperand>
1242 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1243 unsigned Depth, SelectionDAG &DAG) {
1244 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
1247 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1248 assert(0 && "LowerOperation not implemented for this target!");
1253 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1254 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1255 std::pair<SDOperand,SDOperand> Result =
1256 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
1257 setValue(&I, Result.first);
1258 DAG.setRoot(Result.second);
1261 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1263 // If the size of the cpy/move/set is constant (known)
1264 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1265 uint64_t size = op3->getValue();
1268 if (size <= TLI.getMaxStoresPerMemSet()) {
1269 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1270 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1271 uint64_t align = op4.getValue();
1272 while (size > align) {
1275 Value *SrcV = I.getOperand(0);
1276 SDOperand Src = getValue(SrcV);
1277 SDOperand Ptr = getValue(I.getOperand(1));
1278 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1279 DAG.getSrcValue(I.getOperand(1))));
1283 break; // don't do this optimization, use a normal memset
1286 break; // FIXME: not implemented yet
1291 // Non-optimized version
1292 std::vector<SDOperand> Ops;
1293 Ops.push_back(getRoot());
1294 Ops.push_back(getValue(I.getOperand(1)));
1295 Ops.push_back(getValue(I.getOperand(2)));
1296 Ops.push_back(getValue(I.getOperand(3)));
1297 Ops.push_back(getValue(I.getOperand(4)));
1298 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1301 //===----------------------------------------------------------------------===//
1302 // SelectionDAGISel code
1303 //===----------------------------------------------------------------------===//
1305 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1306 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1309 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1310 // FIXME: we only modify the CFG to split critical edges. This
1311 // updates dom and loop info.
1315 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1316 /// casting to the type of GEPI.
1317 static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1318 Value *Ptr, Value *PtrOffset) {
1319 if (V) return V; // Already computed.
1321 BasicBlock::iterator InsertPt;
1322 if (BB == GEPI->getParent()) {
1323 // If insert into the GEP's block, insert right after the GEP.
1327 // Otherwise, insert at the top of BB, after any PHI nodes
1328 InsertPt = BB->begin();
1329 while (isa<PHINode>(InsertPt)) ++InsertPt;
1332 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1333 // BB so that there is only one value live across basic blocks (the cast
1335 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1336 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1337 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1339 // Add the offset, cast it to the right type.
1340 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1341 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1346 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1347 /// selection, we want to be a bit careful about some things. In particular, if
1348 /// we have a GEP instruction that is used in a different block than it is
1349 /// defined, the addressing expression of the GEP cannot be folded into loads or
1350 /// stores that use it. In this case, decompose the GEP and move constant
1351 /// indices into blocks that use it.
1352 static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1353 const TargetData &TD) {
1354 // If this GEP is only used inside the block it is defined in, there is no
1355 // need to rewrite it.
1356 bool isUsedOutsideDefBB = false;
1357 BasicBlock *DefBB = GEPI->getParent();
1358 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1360 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1361 isUsedOutsideDefBB = true;
1365 if (!isUsedOutsideDefBB) return;
1367 // If this GEP has no non-zero constant indices, there is nothing we can do,
1369 bool hasConstantIndex = false;
1370 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1371 E = GEPI->op_end(); OI != E; ++OI) {
1372 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1373 if (CI->getRawValue()) {
1374 hasConstantIndex = true;
1378 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1379 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
1381 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1382 // constant offset (which we now know is non-zero) and deal with it later.
1383 uint64_t ConstantOffset = 0;
1384 const Type *UIntPtrTy = TD.getIntPtrType();
1385 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1386 const Type *Ty = GEPI->getOperand(0)->getType();
1388 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1389 E = GEPI->op_end(); OI != E; ++OI) {
1391 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1392 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1394 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1395 Ty = StTy->getElementType(Field);
1397 Ty = cast<SequentialType>(Ty)->getElementType();
1399 // Handle constant subscripts.
1400 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1401 if (CI->getRawValue() == 0) continue;
1403 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1404 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1406 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1410 // Ptr = Ptr + Idx * ElementSize;
1412 // Cast Idx to UIntPtrTy if needed.
1413 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1415 uint64_t ElementSize = TD.getTypeSize(Ty);
1416 // Mask off bits that should not be set.
1417 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1418 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1420 // Multiply by the element size and add to the base.
1421 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1422 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1426 // Make sure that the offset fits in uintptr_t.
1427 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1428 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1430 // Okay, we have now emitted all of the variable index parts to the BB that
1431 // the GEP is defined in. Loop over all of the using instructions, inserting
1432 // an "add Ptr, ConstantOffset" into each block that uses it and update the
1433 // instruction to use the newly computed value, making GEPI dead. When the
1434 // user is a load or store instruction address, we emit the add into the user
1435 // block, otherwise we use a canonical version right next to the gep (these
1436 // won't be foldable as addresses, so we might as well share the computation).
1438 std::map<BasicBlock*,Value*> InsertedExprs;
1439 while (!GEPI->use_empty()) {
1440 Instruction *User = cast<Instruction>(GEPI->use_back());
1442 // If this use is not foldable into the addressing mode, use a version
1443 // emitted in the GEP block.
1445 if (!isa<LoadInst>(User) &&
1446 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1447 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1450 // Otherwise, insert the code in the User's block so it can be folded into
1451 // any users in that block.
1452 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
1453 User->getParent(), GEPI,
1456 User->replaceUsesOfWith(GEPI, NewVal);
1459 // Finally, the GEP is dead, remove it.
1460 GEPI->eraseFromParent();
1463 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1464 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1465 RegMap = MF.getSSARegMap();
1466 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1468 // First, split all critical edges for PHI nodes with incoming values that are
1469 // constants, this way the load of the constant into a vreg will not be placed
1470 // into MBBs that are used some other way.
1472 // In this pass we also look for GEP instructions that are used across basic
1473 // blocks and rewrites them to improve basic-block-at-a-time selection.
1475 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1477 BasicBlock::iterator BBI;
1478 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1479 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1480 if (isa<Constant>(PN->getIncomingValue(i)))
1481 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1483 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1484 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1485 OptimizeGEPExpression(GEPI, TLI.getTargetData());
1488 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1490 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1491 SelectBasicBlock(I, MF, FuncInfo);
1497 SDOperand SelectionDAGISel::
1498 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1499 SDOperand Op = SDL.getValue(V);
1500 assert((Op.getOpcode() != ISD::CopyFromReg ||
1501 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1502 "Copy from a reg to the same reg!");
1504 // If this type is not legal, we must make sure to not create an invalid
1506 MVT::ValueType SrcVT = Op.getValueType();
1507 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1508 SelectionDAG &DAG = SDL.DAG;
1509 if (SrcVT == DestVT) {
1510 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1511 } else if (SrcVT < DestVT) {
1512 // The src value is promoted to the register.
1513 if (MVT::isFloatingPoint(SrcVT))
1514 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1516 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1517 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1519 // The src value is expanded into multiple registers.
1520 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1521 Op, DAG.getConstant(0, MVT::i32));
1522 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1523 Op, DAG.getConstant(1, MVT::i32));
1524 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1525 return DAG.getCopyToReg(Op, Reg+1, Hi);
1529 void SelectionDAGISel::
1530 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1531 std::vector<SDOperand> &UnorderedChains) {
1532 // If this is the entry block, emit arguments.
1533 Function &F = *BB->getParent();
1534 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1535 SDOperand OldRoot = SDL.DAG.getRoot();
1536 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1539 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1541 if (!AI->use_empty()) {
1542 SDL.setValue(AI, Args[a]);
1544 // If this argument is live outside of the entry block, insert a copy from
1545 // whereever we got it to the vreg that other BB's will reference it as.
1546 if (FuncInfo.ValueMap.count(AI)) {
1548 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1549 UnorderedChains.push_back(Copy);
1553 // Next, if the function has live ins that need to be copied into vregs,
1554 // emit the copies now, into the top of the block.
1555 MachineFunction &MF = SDL.DAG.getMachineFunction();
1556 if (MF.livein_begin() != MF.livein_end()) {
1557 SSARegMap *RegMap = MF.getSSARegMap();
1558 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1559 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1560 E = MF.livein_end(); LI != E; ++LI)
1562 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1563 LI->first, RegMap->getRegClass(LI->second));
1566 // Finally, if the target has anything special to do, allow it to do so.
1567 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1571 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1572 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1573 FunctionLoweringInfo &FuncInfo) {
1574 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1576 std::vector<SDOperand> UnorderedChains;
1578 // Lower any arguments needed in this block if this is the entry block.
1579 if (LLVMBB == &LLVMBB->getParent()->front())
1580 LowerArguments(LLVMBB, SDL, UnorderedChains);
1582 BB = FuncInfo.MBBMap[LLVMBB];
1583 SDL.setCurrentBasicBlock(BB);
1585 // Lower all of the non-terminator instructions.
1586 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1590 // Ensure that all instructions which are used outside of their defining
1591 // blocks are available as virtual registers.
1592 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1593 if (!I->use_empty() && !isa<PHINode>(I)) {
1594 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1595 if (VMI != FuncInfo.ValueMap.end())
1596 UnorderedChains.push_back(
1597 CopyValueToVirtualRegister(SDL, I, VMI->second));
1600 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1601 // ensure constants are generated when needed. Remember the virtual registers
1602 // that need to be added to the Machine PHI nodes as input. We cannot just
1603 // directly add them, because expansion might result in multiple MBB's for one
1604 // BB. As such, the start of the BB might correspond to a different MBB than
1608 // Emit constants only once even if used by multiple PHI nodes.
1609 std::map<Constant*, unsigned> ConstantsOut;
1611 // Check successor nodes PHI nodes that expect a constant to be available from
1613 TerminatorInst *TI = LLVMBB->getTerminator();
1614 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1615 BasicBlock *SuccBB = TI->getSuccessor(succ);
1616 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1619 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1620 // nodes and Machine PHI nodes, but the incoming operands have not been
1622 for (BasicBlock::iterator I = SuccBB->begin();
1623 (PN = dyn_cast<PHINode>(I)); ++I)
1624 if (!PN->use_empty()) {
1626 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1627 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1628 unsigned &RegOut = ConstantsOut[C];
1630 RegOut = FuncInfo.CreateRegForValue(C);
1631 UnorderedChains.push_back(
1632 CopyValueToVirtualRegister(SDL, C, RegOut));
1636 Reg = FuncInfo.ValueMap[PHIOp];
1638 assert(isa<AllocaInst>(PHIOp) &&
1639 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1640 "Didn't codegen value into a register!??");
1641 Reg = FuncInfo.CreateRegForValue(PHIOp);
1642 UnorderedChains.push_back(
1643 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1647 // Remember that this register needs to added to the machine PHI node as
1648 // the input for this MBB.
1649 unsigned NumElements =
1650 TLI.getNumElements(TLI.getValueType(PN->getType()));
1651 for (unsigned i = 0, e = NumElements; i != e; ++i)
1652 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1655 ConstantsOut.clear();
1657 // Turn all of the unordered chains into one factored node.
1658 if (!UnorderedChains.empty()) {
1659 SDOperand Root = SDL.getRoot();
1660 if (Root.getOpcode() != ISD::EntryToken) {
1661 unsigned i = 0, e = UnorderedChains.size();
1662 for (; i != e; ++i) {
1663 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1664 if (UnorderedChains[i].Val->getOperand(0) == Root)
1665 break; // Don't add the root if we already indirectly depend on it.
1669 UnorderedChains.push_back(Root);
1671 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1674 // Lower the terminator after the copies are emitted.
1675 SDL.visit(*LLVMBB->getTerminator());
1677 // Make sure the root of the DAG is up-to-date.
1678 DAG.setRoot(SDL.getRoot());
1681 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1682 FunctionLoweringInfo &FuncInfo) {
1683 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
1685 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1687 // First step, lower LLVM code to some DAG. This DAG may use operations and
1688 // types that are not supported by the target.
1689 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1691 // Run the DAG combiner in pre-legalize mode.
1694 DEBUG(std::cerr << "Lowered selection DAG:\n");
1697 // Second step, hack on the DAG until it only uses operations and types that
1698 // the target supports.
1701 DEBUG(std::cerr << "Legalized selection DAG:\n");
1704 // Run the DAG combiner in post-legalize mode.
1707 if (ViewDAGs) DAG.viewGraph();
1709 // Third, instruction select all of the operations to machine code, adding the
1710 // code to the MachineBasicBlock.
1711 InstructionSelectBasicBlock(DAG);
1713 DEBUG(std::cerr << "Selected machine code:\n");
1716 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1717 // PHI nodes in successors.
1718 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1719 MachineInstr *PHI = PHINodesToUpdate[i].first;
1720 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1721 "This is not a machine PHI node that we are updating!");
1722 PHI->addRegOperand(PHINodesToUpdate[i].second);
1723 PHI->addMachineBasicBlockOperand(BB);
1726 // Finally, add the CFG edges from the last selected MBB to the successor
1728 TerminatorInst *TI = LLVMBB->getTerminator();
1729 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1730 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1731 BB->addSuccessor(Succ0MBB);