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/IntrinsicInst.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineDebugInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/SSARegMap.h"
34 #include "llvm/Target/MRegisterInfo.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetFrameInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/Debug.h"
53 ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
56 ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
59 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
62 // Scheduling heuristics
63 enum SchedHeuristics {
64 defaultScheduling, // Let the target specify its preference.
65 noScheduling, // No scheduling, emit breadth first sequence.
66 simpleScheduling, // Two pass, min. critical path, max. utilization.
67 simpleNoItinScheduling, // Same as above exact using generic latency.
68 listSchedulingBURR, // Bottom-up reg reduction list scheduling.
69 listSchedulingTDRR, // Top-down reg reduction list scheduling.
70 listSchedulingTD // Top-down list scheduler.
74 cl::opt<SchedHeuristics>
77 cl::desc("Choose scheduling style"),
78 cl::init(defaultScheduling),
80 clEnumValN(defaultScheduling, "default",
81 "Target preferred scheduling style"),
82 clEnumValN(noScheduling, "none",
83 "No scheduling: breadth first sequencing"),
84 clEnumValN(simpleScheduling, "simple",
85 "Simple two pass scheduling: minimize critical path "
86 "and maximize processor utilization"),
87 clEnumValN(simpleNoItinScheduling, "simple-noitin",
88 "Simple two pass scheduling: Same as simple "
89 "except using generic latency"),
90 clEnumValN(listSchedulingBURR, "list-burr",
91 "Bottom-up register reduction list scheduling"),
92 clEnumValN(listSchedulingTDRR, "list-tdrr",
93 "Top-down register reduction list scheduling"),
94 clEnumValN(listSchedulingTD, "list-td",
95 "Top-down list scheduler"),
100 /// RegsForValue - This struct represents the physical registers that a
101 /// particular value is assigned and the type information about the value.
102 /// This is needed because values can be promoted into larger registers and
103 /// expanded into multiple smaller registers than the value.
104 struct RegsForValue {
105 /// Regs - This list hold the register (for legal and promoted values)
106 /// or register set (for expanded values) that the value should be assigned
108 std::vector<unsigned> Regs;
110 /// RegVT - The value type of each register.
112 MVT::ValueType RegVT;
114 /// ValueVT - The value type of the LLVM value, which may be promoted from
115 /// RegVT or made from merging the two expanded parts.
116 MVT::ValueType ValueVT;
118 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
120 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
121 : RegVT(regvt), ValueVT(valuevt) {
124 RegsForValue(const std::vector<unsigned> ®s,
125 MVT::ValueType regvt, MVT::ValueType valuevt)
126 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
129 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
130 /// this value and returns the result as a ValueVT value. This uses
131 /// Chain/Flag as the input and updates them for the output Chain/Flag.
132 SDOperand getCopyFromRegs(SelectionDAG &DAG,
133 SDOperand &Chain, SDOperand &Flag) const;
135 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
136 /// specified value into the registers specified by this object. This uses
137 /// Chain/Flag as the input and updates them for the output Chain/Flag.
138 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
139 SDOperand &Chain, SDOperand &Flag,
140 MVT::ValueType PtrVT) const;
142 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
143 /// operand list. This adds the code marker and includes the number of
144 /// values added into it.
145 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
146 std::vector<SDOperand> &Ops) const;
151 //===--------------------------------------------------------------------===//
152 /// FunctionLoweringInfo - This contains information that is global to a
153 /// function that is used when lowering a region of the function.
154 class FunctionLoweringInfo {
161 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
163 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
164 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
166 /// ValueMap - Since we emit code for the function a basic block at a time,
167 /// we must remember which virtual registers hold the values for
168 /// cross-basic-block values.
169 std::map<const Value*, unsigned> ValueMap;
171 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
172 /// the entry block. This allows the allocas to be efficiently referenced
173 /// anywhere in the function.
174 std::map<const AllocaInst*, int> StaticAllocaMap;
176 unsigned MakeReg(MVT::ValueType VT) {
177 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
180 unsigned CreateRegForValue(const Value *V);
182 unsigned InitializeRegForValue(const Value *V) {
183 unsigned &R = ValueMap[V];
184 assert(R == 0 && "Already initialized this value register!");
185 return R = CreateRegForValue(V);
190 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
191 /// PHI nodes or outside of the basic block that defines it, or used by a
192 /// switch instruction, which may expand to multiple basic blocks.
193 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
194 if (isa<PHINode>(I)) return true;
195 BasicBlock *BB = I->getParent();
196 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
197 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
198 isa<SwitchInst>(*UI))
203 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
204 /// entry block, return true. This includes arguments used by switches, since
205 /// the switch may expand into multiple basic blocks.
206 static bool isOnlyUsedInEntryBlock(Argument *A) {
207 BasicBlock *Entry = A->getParent()->begin();
208 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
209 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
210 return false; // Use not in entry block.
214 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
215 Function &fn, MachineFunction &mf)
216 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
218 // Create a vreg for each argument register that is not dead and is used
219 // outside of the entry block for the function.
220 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
222 if (!isOnlyUsedInEntryBlock(AI))
223 InitializeRegForValue(AI);
225 // Initialize the mapping of values to registers. This is only set up for
226 // instruction values that are used outside of the block that defines
228 Function::iterator BB = Fn.begin(), EB = Fn.end();
229 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
230 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
231 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
232 const Type *Ty = AI->getAllocatedType();
233 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
235 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
238 // If the alignment of the value is smaller than the size of the value,
239 // and if the size of the value is particularly small (<= 8 bytes),
240 // round up to the size of the value for potentially better performance.
242 // FIXME: This could be made better with a preferred alignment hook in
243 // TargetData. It serves primarily to 8-byte align doubles for X86.
244 if (Align < TySize && TySize <= 8) Align = TySize;
245 TySize *= CUI->getValue(); // Get total allocated size.
246 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
247 StaticAllocaMap[AI] =
248 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
251 for (; BB != EB; ++BB)
252 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
253 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
254 if (!isa<AllocaInst>(I) ||
255 !StaticAllocaMap.count(cast<AllocaInst>(I)))
256 InitializeRegForValue(I);
258 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
259 // also creates the initial PHI MachineInstrs, though none of the input
260 // operands are populated.
261 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
262 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
264 MF.getBasicBlockList().push_back(MBB);
266 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
269 for (BasicBlock::iterator I = BB->begin();
270 (PN = dyn_cast<PHINode>(I)); ++I)
271 if (!PN->use_empty()) {
272 MVT::ValueType VT = TLI.getValueType(PN->getType());
273 unsigned NumElements;
274 if (VT != MVT::Vector)
275 NumElements = TLI.getNumElements(VT);
277 MVT::ValueType VT1,VT2;
279 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
282 unsigned PHIReg = ValueMap[PN];
283 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
284 for (unsigned i = 0; i != NumElements; ++i)
285 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
290 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
291 /// the correctly promoted or expanded types. Assign these registers
292 /// consecutive vreg numbers and return the first assigned number.
293 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
294 MVT::ValueType VT = TLI.getValueType(V->getType());
296 // The number of multiples of registers that we need, to, e.g., split up
297 // a <2 x int64> -> 4 x i32 registers.
298 unsigned NumVectorRegs = 1;
300 // If this is a packed type, figure out what type it will decompose into
301 // and how many of the elements it will use.
302 if (VT == MVT::Vector) {
303 const PackedType *PTy = cast<PackedType>(V->getType());
304 unsigned NumElts = PTy->getNumElements();
305 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
307 // Divide the input until we get to a supported size. This will always
308 // end with a scalar if the target doesn't support vectors.
309 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
316 VT = getVectorType(EltTy, NumElts);
319 // The common case is that we will only create one register for this
320 // value. If we have that case, create and return the virtual register.
321 unsigned NV = TLI.getNumElements(VT);
323 // If we are promoting this value, pick the next largest supported type.
324 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
325 unsigned Reg = MakeReg(PromotedType);
326 // If this is a vector of supported or promoted types (e.g. 4 x i16),
327 // create all of the registers.
328 for (unsigned i = 1; i != NumVectorRegs; ++i)
329 MakeReg(PromotedType);
333 // If this value is represented with multiple target registers, make sure
334 // to create enough consecutive registers of the right (smaller) type.
335 unsigned NT = VT-1; // Find the type to use.
336 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
339 unsigned R = MakeReg((MVT::ValueType)NT);
340 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
341 MakeReg((MVT::ValueType)NT);
345 //===----------------------------------------------------------------------===//
346 /// SelectionDAGLowering - This is the common target-independent lowering
347 /// implementation that is parameterized by a TargetLowering object.
348 /// Also, targets can overload any lowering method.
351 class SelectionDAGLowering {
352 MachineBasicBlock *CurMBB;
354 std::map<const Value*, SDOperand> NodeMap;
356 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
357 /// them up and then emit token factor nodes when possible. This allows us to
358 /// get simple disambiguation between loads without worrying about alias
360 std::vector<SDOperand> PendingLoads;
362 /// Case - A pair of values to record the Value for a switch case, and the
363 /// case's target basic block.
364 typedef std::pair<Constant*, MachineBasicBlock*> Case;
365 typedef std::vector<Case>::iterator CaseItr;
366 typedef std::pair<CaseItr, CaseItr> CaseRange;
368 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
369 /// of conditional branches.
371 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
372 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
374 /// CaseBB - The MBB in which to emit the compare and branch
375 MachineBasicBlock *CaseBB;
376 /// LT, GE - If nonzero, we know the current case value must be less-than or
377 /// greater-than-or-equal-to these Constants.
380 /// Range - A pair of iterators representing the range of case values to be
381 /// processed at this point in the binary search tree.
385 /// The comparison function for sorting Case values.
387 bool operator () (const Case& C1, const Case& C2) {
388 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
389 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
391 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
392 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
397 // TLI - This is information that describes the available target features we
398 // need for lowering. This indicates when operations are unavailable,
399 // implemented with a libcall, etc.
402 const TargetData *TD;
404 /// SwitchCases - Vector of CaseBlock structures used to communicate
405 /// SwitchInst code generation information.
406 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
407 SelectionDAGISel::JumpTable JT;
409 /// FuncInfo - Information about the function as a whole.
411 FunctionLoweringInfo &FuncInfo;
413 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
414 FunctionLoweringInfo &funcinfo)
415 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
416 JT(0,0,0,0), FuncInfo(funcinfo) {
419 /// getRoot - Return the current virtual root of the Selection DAG.
421 SDOperand getRoot() {
422 if (PendingLoads.empty())
423 return DAG.getRoot();
425 if (PendingLoads.size() == 1) {
426 SDOperand Root = PendingLoads[0];
428 PendingLoads.clear();
432 // Otherwise, we have to make a token factor node.
433 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
434 PendingLoads.clear();
439 void visit(Instruction &I) { visit(I.getOpcode(), I); }
441 void visit(unsigned Opcode, User &I) {
443 default: assert(0 && "Unknown instruction type encountered!");
445 // Build the switch statement using the Instruction.def file.
446 #define HANDLE_INST(NUM, OPCODE, CLASS) \
447 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
448 #include "llvm/Instruction.def"
452 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
454 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
455 SDOperand SrcValue, SDOperand Root,
458 SDOperand getIntPtrConstant(uint64_t Val) {
459 return DAG.getConstant(Val, TLI.getPointerTy());
462 SDOperand getValue(const Value *V);
464 const SDOperand &setValue(const Value *V, SDOperand NewN) {
465 SDOperand &N = NodeMap[V];
466 assert(N.Val == 0 && "Already set a value for this node!");
470 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
472 bool OutReg, bool InReg,
473 std::set<unsigned> &OutputRegs,
474 std::set<unsigned> &InputRegs);
476 // Terminator instructions.
477 void visitRet(ReturnInst &I);
478 void visitBr(BranchInst &I);
479 void visitSwitch(SwitchInst &I);
480 void visitUnreachable(UnreachableInst &I) { /* noop */ }
482 // Helper for visitSwitch
483 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
484 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
486 // These all get lowered before this pass.
487 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
488 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
490 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
491 void visitShift(User &I, unsigned Opcode);
492 void visitAdd(User &I) {
493 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
495 void visitSub(User &I);
496 void visitMul(User &I) {
497 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
499 void visitDiv(User &I) {
500 const Type *Ty = I.getType();
502 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
503 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
505 void visitRem(User &I) {
506 const Type *Ty = I.getType();
507 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
509 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
510 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
511 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
512 void visitShl(User &I) { visitShift(I, ISD::SHL); }
513 void visitShr(User &I) {
514 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
517 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
518 ISD::CondCode FPOpc);
519 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
521 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
523 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
525 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
527 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
529 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
532 void visitExtractElement(User &I);
533 void visitInsertElement(User &I);
534 void visitShuffleVector(User &I);
536 void visitGetElementPtr(User &I);
537 void visitCast(User &I);
538 void visitSelect(User &I);
540 void visitMalloc(MallocInst &I);
541 void visitFree(FreeInst &I);
542 void visitAlloca(AllocaInst &I);
543 void visitLoad(LoadInst &I);
544 void visitStore(StoreInst &I);
545 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
546 void visitCall(CallInst &I);
547 void visitInlineAsm(CallInst &I);
548 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
549 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
551 void visitVAStart(CallInst &I);
552 void visitVAArg(VAArgInst &I);
553 void visitVAEnd(CallInst &I);
554 void visitVACopy(CallInst &I);
555 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
557 void visitMemIntrinsic(CallInst &I, unsigned Op);
559 void visitUserOp1(Instruction &I) {
560 assert(0 && "UserOp1 should not exist at instruction selection time!");
563 void visitUserOp2(Instruction &I) {
564 assert(0 && "UserOp2 should not exist at instruction selection time!");
568 } // end namespace llvm
570 SDOperand SelectionDAGLowering::getValue(const Value *V) {
571 SDOperand &N = NodeMap[V];
574 const Type *VTy = V->getType();
575 MVT::ValueType VT = TLI.getValueType(VTy);
576 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
577 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
578 visit(CE->getOpcode(), *CE);
579 assert(N.Val && "visit didn't populate the ValueMap!");
581 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
582 return N = DAG.getGlobalAddress(GV, VT);
583 } else if (isa<ConstantPointerNull>(C)) {
584 return N = DAG.getConstant(0, TLI.getPointerTy());
585 } else if (isa<UndefValue>(C)) {
586 if (!isa<PackedType>(VTy))
587 return N = DAG.getNode(ISD::UNDEF, VT);
589 // Create a VBUILD_VECTOR of undef nodes.
590 const PackedType *PTy = cast<PackedType>(VTy);
591 unsigned NumElements = PTy->getNumElements();
592 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
594 std::vector<SDOperand> Ops;
595 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
597 // Create a VConstant node with generic Vector type.
598 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
599 Ops.push_back(DAG.getValueType(PVT));
600 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
601 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
602 return N = DAG.getConstantFP(CFP->getValue(), VT);
603 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
604 unsigned NumElements = PTy->getNumElements();
605 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
607 // Now that we know the number and type of the elements, push a
608 // Constant or ConstantFP node onto the ops list for each element of
609 // the packed constant.
610 std::vector<SDOperand> Ops;
611 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
612 for (unsigned i = 0; i != NumElements; ++i)
613 Ops.push_back(getValue(CP->getOperand(i)));
615 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
617 if (MVT::isFloatingPoint(PVT))
618 Op = DAG.getConstantFP(0, PVT);
620 Op = DAG.getConstant(0, PVT);
621 Ops.assign(NumElements, Op);
624 // Create a VBUILD_VECTOR node with generic Vector type.
625 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
626 Ops.push_back(DAG.getValueType(PVT));
627 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
629 // Canonicalize all constant ints to be unsigned.
630 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
634 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
635 std::map<const AllocaInst*, int>::iterator SI =
636 FuncInfo.StaticAllocaMap.find(AI);
637 if (SI != FuncInfo.StaticAllocaMap.end())
638 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
641 std::map<const Value*, unsigned>::const_iterator VMI =
642 FuncInfo.ValueMap.find(V);
643 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
645 unsigned InReg = VMI->second;
647 // If this type is not legal, make it so now.
648 if (VT != MVT::Vector) {
649 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
651 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
653 // Source must be expanded. This input value is actually coming from the
654 // register pair VMI->second and VMI->second+1.
655 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
656 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
657 } else if (DestVT > VT) { // Promotion case
658 if (MVT::isFloatingPoint(VT))
659 N = DAG.getNode(ISD::FP_ROUND, VT, N);
661 N = DAG.getNode(ISD::TRUNCATE, VT, N);
664 // Otherwise, if this is a vector, make it available as a generic vector
666 MVT::ValueType PTyElementVT, PTyLegalElementVT;
667 const PackedType *PTy = cast<PackedType>(VTy);
668 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
671 // Build a VBUILD_VECTOR with the input registers.
672 std::vector<SDOperand> Ops;
673 if (PTyElementVT == PTyLegalElementVT) {
674 // If the value types are legal, just VBUILD the CopyFromReg nodes.
675 for (unsigned i = 0; i != NE; ++i)
676 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
678 } else if (PTyElementVT < PTyLegalElementVT) {
679 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
680 for (unsigned i = 0; i != NE; ++i) {
681 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
683 if (MVT::isFloatingPoint(PTyElementVT))
684 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
686 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
690 // If the register was expanded, use BUILD_PAIR.
691 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
692 for (unsigned i = 0; i != NE/2; ++i) {
693 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
695 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
697 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
701 Ops.push_back(DAG.getConstant(NE, MVT::i32));
702 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
703 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
705 // Finally, use a VBIT_CONVERT to make this available as the appropriate
707 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
708 DAG.getConstant(PTy->getNumElements(),
710 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
717 void SelectionDAGLowering::visitRet(ReturnInst &I) {
718 if (I.getNumOperands() == 0) {
719 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
722 std::vector<SDOperand> NewValues;
723 NewValues.push_back(getRoot());
724 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
725 SDOperand RetOp = getValue(I.getOperand(i));
726 bool isSigned = I.getOperand(i)->getType()->isSigned();
728 // If this is an integer return value, we need to promote it ourselves to
729 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
731 // FIXME: C calling convention requires the return type to be promoted to
732 // at least 32-bit. But this is not necessary for non-C calling conventions.
733 if (MVT::isInteger(RetOp.getValueType()) &&
734 RetOp.getValueType() < MVT::i64) {
735 MVT::ValueType TmpVT;
736 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
737 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
742 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
744 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
746 NewValues.push_back(RetOp);
747 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
749 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
752 void SelectionDAGLowering::visitBr(BranchInst &I) {
753 // Update machine-CFG edges.
754 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
755 CurMBB->addSuccessor(Succ0MBB);
757 // Figure out which block is immediately after the current one.
758 MachineBasicBlock *NextBlock = 0;
759 MachineFunction::iterator BBI = CurMBB;
760 if (++BBI != CurMBB->getParent()->end())
763 if (I.isUnconditional()) {
764 // If this is not a fall-through branch, emit the branch.
765 if (Succ0MBB != NextBlock)
766 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
767 DAG.getBasicBlock(Succ0MBB)));
769 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
770 CurMBB->addSuccessor(Succ1MBB);
772 SDOperand Cond = getValue(I.getCondition());
773 if (Succ1MBB == NextBlock) {
774 // If the condition is false, fall through. This means we should branch
775 // if the condition is true to Succ #0.
776 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
777 Cond, DAG.getBasicBlock(Succ0MBB)));
778 } else if (Succ0MBB == NextBlock) {
779 // If the condition is true, fall through. This means we should branch if
780 // the condition is false to Succ #1. Invert the condition first.
781 SDOperand True = DAG.getConstant(1, Cond.getValueType());
782 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
783 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
784 Cond, DAG.getBasicBlock(Succ1MBB)));
786 std::vector<SDOperand> Ops;
787 Ops.push_back(getRoot());
788 // If the false case is the current basic block, then this is a self
789 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
790 // adds an extra instruction in the loop. Instead, invert the
791 // condition and emit "Loop: ... br!cond Loop; br Out.
792 if (CurMBB == Succ1MBB) {
793 std::swap(Succ0MBB, Succ1MBB);
794 SDOperand True = DAG.getConstant(1, Cond.getValueType());
795 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
797 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
798 DAG.getBasicBlock(Succ0MBB));
799 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
800 DAG.getBasicBlock(Succ1MBB)));
805 /// visitSwitchCase - Emits the necessary code to represent a single node in
806 /// the binary search tree resulting from lowering a switch instruction.
807 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
808 SDOperand SwitchOp = getValue(CB.SwitchV);
809 SDOperand CaseOp = getValue(CB.CaseC);
810 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
812 // Set NextBlock to be the MBB immediately after the current one, if any.
813 // This is used to avoid emitting unnecessary branches to the next block.
814 MachineBasicBlock *NextBlock = 0;
815 MachineFunction::iterator BBI = CurMBB;
816 if (++BBI != CurMBB->getParent()->end())
819 // If the lhs block is the next block, invert the condition so that we can
820 // fall through to the lhs instead of the rhs block.
821 if (CB.LHSBB == NextBlock) {
822 std::swap(CB.LHSBB, CB.RHSBB);
823 SDOperand True = DAG.getConstant(1, Cond.getValueType());
824 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
826 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
827 DAG.getBasicBlock(CB.LHSBB));
828 if (CB.RHSBB == NextBlock)
831 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
832 DAG.getBasicBlock(CB.RHSBB)));
833 // Update successor info
834 CurMBB->addSuccessor(CB.LHSBB);
835 CurMBB->addSuccessor(CB.RHSBB);
838 /// visitSwitchCase - Emits the necessary code to represent a single node in
839 /// the binary search tree resulting from lowering a switch instruction.
840 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
841 // FIXME: Need to emit different code for PIC vs. Non-PIC, specifically,
842 // we need to add the address of the jump table to the value loaded, since
843 // the entries in the jump table will be differences rather than absolute
846 // Emit the code for the jump table
847 MVT::ValueType PTy = TLI.getPointerTy();
848 unsigned PTyBytes = MVT::getSizeInBits(PTy)/8;
849 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
850 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
851 DAG.getConstant(PTyBytes, PTy));
852 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, DAG.getJumpTable(JT.JTI,PTy));
853 SDOperand LD = DAG.getLoad(PTy, Copy.getValue(1), ADD, DAG.getSrcValue(0));
854 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
857 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
858 // Figure out which block is immediately after the current one.
859 MachineBasicBlock *NextBlock = 0;
860 MachineFunction::iterator BBI = CurMBB;
861 if (++BBI != CurMBB->getParent()->end())
864 // If there is only the default destination, branch to it if it is not the
865 // next basic block. Otherwise, just fall through.
866 if (I.getNumOperands() == 2) {
867 // Update machine-CFG edges.
868 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
869 // If this is not a fall-through branch, emit the branch.
870 if (DefaultMBB != NextBlock)
871 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
872 DAG.getBasicBlock(DefaultMBB)));
873 CurMBB->addSuccessor(DefaultMBB);
877 // If there are any non-default case statements, create a vector of Cases
878 // representing each one, and sort the vector so that we can efficiently
879 // create a binary search tree from them.
880 std::vector<Case> Cases;
881 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
882 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
883 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
885 std::sort(Cases.begin(), Cases.end(), CaseCmp());
887 // Get the Value to be switched on and default basic blocks, which will be
888 // inserted into CaseBlock records, representing basic blocks in the binary
890 Value *SV = I.getOperand(0);
891 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
893 // Get the MachineFunction which holds the current MBB. This is used during
894 // emission of jump tables, and when inserting any additional MBBs necessary
895 // to represent the switch.
896 MachineFunction *CurMF = CurMBB->getParent();
897 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
898 Reloc::Model Relocs = TLI.getTargetMachine().getRelocationModel();
900 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
901 // target supports indirect branches, then emit a jump table rather than
902 // lowering the switch to a binary tree of conditional branches.
903 // FIXME: Make this work with PIC code
904 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
905 (Relocs == Reloc::Static || Relocs == Reloc::DynamicNoPIC) &&
907 uint64_t First = cast<ConstantIntegral>(Cases.front().first)->getRawValue();
908 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getRawValue();
909 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
911 if (Density >= 0.3125) {
912 // Create a new basic block to hold the code for loading the address
913 // of the jump table, and jumping to it. Update successor information;
914 // we will either branch to the default case for the switch, or the jump
916 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
917 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
918 CurMBB->addSuccessor(Default);
919 CurMBB->addSuccessor(JumpTableBB);
921 // Subtract the lowest switch case value from the value being switched on
922 // and conditional branch to default mbb if the result is greater than the
923 // difference between smallest and largest cases.
924 SDOperand SwitchOp = getValue(SV);
925 MVT::ValueType VT = SwitchOp.getValueType();
926 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
927 DAG.getConstant(First, VT));
929 // The SDNode we just created, which holds the value being switched on
930 // minus the the smallest case value, needs to be copied to a virtual
931 // register so it can be used as an index into the jump table in a
932 // subsequent basic block. This value may be smaller or larger than the
933 // target's pointer type, and therefore require extension or truncating.
934 if (VT > TLI.getPointerTy())
935 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
937 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
938 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
939 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
941 // Emit the range check for the jump table, and branch to the default
942 // block for the switch statement if the value being switched on exceeds
943 // the largest case in the switch.
944 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
945 DAG.getConstant(Last-First,VT), ISD::SETUGT);
946 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
947 DAG.getBasicBlock(Default)));
949 // Build a vector of destination BBs, corresponding to each target
950 // of the jump table. If the value of the jump table slot corresponds to
951 // a case statement, push the case's BB onto the vector, otherwise, push
953 std::set<MachineBasicBlock*> UniqueBBs;
954 std::vector<MachineBasicBlock*> DestBBs;
955 uint64_t TEI = First;
956 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI) {
957 if (cast<ConstantIntegral>(ii->first)->getRawValue() == TEI) {
958 DestBBs.push_back(ii->second);
959 UniqueBBs.insert(ii->second);
962 DestBBs.push_back(Default);
963 UniqueBBs.insert(Default);
967 // Update successor info
968 for (std::set<MachineBasicBlock*>::iterator ii = UniqueBBs.begin(),
969 ee = UniqueBBs.end(); ii != ee; ++ii)
970 JumpTableBB->addSuccessor(*ii);
972 // Create a jump table index for this jump table, or return an existing
974 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
976 // Set the jump table information so that we can codegen it as a second
978 JT.Reg = JumpTableReg;
980 JT.MBB = JumpTableBB;
981 JT.Default = Default;
986 // Push the initial CaseRec onto the worklist
987 std::vector<CaseRec> CaseVec;
988 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
990 while (!CaseVec.empty()) {
991 // Grab a record representing a case range to process off the worklist
992 CaseRec CR = CaseVec.back();
995 // Size is the number of Cases represented by this range. If Size is 1,
996 // then we are processing a leaf of the binary search tree. Otherwise,
997 // we need to pick a pivot, and push left and right ranges onto the
999 unsigned Size = CR.Range.second - CR.Range.first;
1002 // Create a CaseBlock record representing a conditional branch to
1003 // the Case's target mbb if the value being switched on SV is equal
1004 // to C. Otherwise, branch to default.
1005 Constant *C = CR.Range.first->first;
1006 MachineBasicBlock *Target = CR.Range.first->second;
1007 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1009 // If the MBB representing the leaf node is the current MBB, then just
1010 // call visitSwitchCase to emit the code into the current block.
1011 // Otherwise, push the CaseBlock onto the vector to be later processed
1012 // by SDISel, and insert the node's MBB before the next MBB.
1013 if (CR.CaseBB == CurMBB)
1014 visitSwitchCase(CB);
1016 SwitchCases.push_back(CB);
1017 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
1020 // split case range at pivot
1021 CaseItr Pivot = CR.Range.first + (Size / 2);
1022 CaseRange LHSR(CR.Range.first, Pivot);
1023 CaseRange RHSR(Pivot, CR.Range.second);
1024 Constant *C = Pivot->first;
1025 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
1026 // We know that we branch to the LHS if the Value being switched on is
1027 // less than the Pivot value, C. We use this to optimize our binary
1028 // tree a bit, by recognizing that if SV is greater than or equal to the
1029 // LHS's Case Value, and that Case Value is exactly one less than the
1030 // Pivot's Value, then we can branch directly to the LHS's Target,
1031 // rather than creating a leaf node for it.
1032 if ((LHSR.second - LHSR.first) == 1 &&
1033 LHSR.first->first == CR.GE &&
1034 cast<ConstantIntegral>(C)->getRawValue() ==
1035 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
1036 LHSBB = LHSR.first->second;
1038 LHSBB = new MachineBasicBlock(LLVMBB);
1039 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
1041 // Similar to the optimization above, if the Value being switched on is
1042 // known to be less than the Constant CR.LT, and the current Case Value
1043 // is CR.LT - 1, then we can branch directly to the target block for
1044 // the current Case Value, rather than emitting a RHS leaf node for it.
1045 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1046 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
1047 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
1048 RHSBB = RHSR.first->second;
1050 RHSBB = new MachineBasicBlock(LLVMBB);
1051 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
1053 // Create a CaseBlock record representing a conditional branch to
1054 // the LHS node if the value being switched on SV is less than C.
1055 // Otherwise, branch to LHS.
1056 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1057 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
1058 if (CR.CaseBB == CurMBB)
1059 visitSwitchCase(CB);
1061 SwitchCases.push_back(CB);
1062 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
1068 void SelectionDAGLowering::visitSub(User &I) {
1069 // -0.0 - X --> fneg
1070 if (I.getType()->isFloatingPoint()) {
1071 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1072 if (CFP->isExactlyValue(-0.0)) {
1073 SDOperand Op2 = getValue(I.getOperand(1));
1074 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1078 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
1081 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
1083 const Type *Ty = I.getType();
1084 SDOperand Op1 = getValue(I.getOperand(0));
1085 SDOperand Op2 = getValue(I.getOperand(1));
1087 if (Ty->isIntegral()) {
1088 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1089 } else if (Ty->isFloatingPoint()) {
1090 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1092 const PackedType *PTy = cast<PackedType>(Ty);
1093 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1094 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1095 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1099 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1100 SDOperand Op1 = getValue(I.getOperand(0));
1101 SDOperand Op2 = getValue(I.getOperand(1));
1103 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1105 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1108 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
1109 ISD::CondCode UnsignedOpcode,
1110 ISD::CondCode FPOpcode) {
1111 SDOperand Op1 = getValue(I.getOperand(0));
1112 SDOperand Op2 = getValue(I.getOperand(1));
1113 ISD::CondCode Opcode = SignedOpcode;
1114 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
1116 else if (I.getOperand(0)->getType()->isUnsigned())
1117 Opcode = UnsignedOpcode;
1118 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1121 void SelectionDAGLowering::visitSelect(User &I) {
1122 SDOperand Cond = getValue(I.getOperand(0));
1123 SDOperand TrueVal = getValue(I.getOperand(1));
1124 SDOperand FalseVal = getValue(I.getOperand(2));
1125 if (!isa<PackedType>(I.getType())) {
1126 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1127 TrueVal, FalseVal));
1129 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1130 *(TrueVal.Val->op_end()-2),
1131 *(TrueVal.Val->op_end()-1)));
1135 void SelectionDAGLowering::visitCast(User &I) {
1136 SDOperand N = getValue(I.getOperand(0));
1137 MVT::ValueType SrcVT = N.getValueType();
1138 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1140 if (DestVT == MVT::Vector) {
1141 // This is a cast to a vector from something else. This is always a bit
1142 // convert. Get information about the input vector.
1143 const PackedType *DestTy = cast<PackedType>(I.getType());
1144 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1145 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1146 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1147 DAG.getValueType(EltVT)));
1148 } else if (SrcVT == DestVT) {
1149 setValue(&I, N); // noop cast.
1150 } else if (DestVT == MVT::i1) {
1151 // Cast to bool is a comparison against zero, not truncation to zero.
1152 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
1153 DAG.getConstantFP(0.0, N.getValueType());
1154 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
1155 } else if (isInteger(SrcVT)) {
1156 if (isInteger(DestVT)) { // Int -> Int cast
1157 if (DestVT < SrcVT) // Truncating cast?
1158 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1159 else if (I.getOperand(0)->getType()->isSigned())
1160 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1162 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1163 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
1164 if (I.getOperand(0)->getType()->isSigned())
1165 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1167 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1169 assert(0 && "Unknown cast!");
1171 } else if (isFloatingPoint(SrcVT)) {
1172 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1173 if (DestVT < SrcVT) // Rounding cast?
1174 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1176 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1177 } else if (isInteger(DestVT)) { // FP -> Int cast.
1178 if (I.getType()->isSigned())
1179 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1181 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1183 assert(0 && "Unknown cast!");
1186 assert(SrcVT == MVT::Vector && "Unknown cast!");
1187 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1188 // This is a cast from a vector to something else. This is always a bit
1189 // convert. Get information about the input vector.
1190 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1194 void SelectionDAGLowering::visitInsertElement(User &I) {
1195 SDOperand InVec = getValue(I.getOperand(0));
1196 SDOperand InVal = getValue(I.getOperand(1));
1197 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1198 getValue(I.getOperand(2)));
1200 SDOperand Num = *(InVec.Val->op_end()-2);
1201 SDOperand Typ = *(InVec.Val->op_end()-1);
1202 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1203 InVec, InVal, InIdx, Num, Typ));
1206 void SelectionDAGLowering::visitExtractElement(User &I) {
1207 SDOperand InVec = getValue(I.getOperand(0));
1208 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1209 getValue(I.getOperand(1)));
1210 SDOperand Typ = *(InVec.Val->op_end()-1);
1211 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1212 TLI.getValueType(I.getType()), InVec, InIdx));
1215 void SelectionDAGLowering::visitShuffleVector(User &I) {
1216 SDOperand V1 = getValue(I.getOperand(0));
1217 SDOperand V2 = getValue(I.getOperand(1));
1218 SDOperand Mask = getValue(I.getOperand(2));
1220 SDOperand Num = *(V1.Val->op_end()-2);
1221 SDOperand Typ = *(V2.Val->op_end()-1);
1222 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1223 V1, V2, Mask, Num, Typ));
1227 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1228 SDOperand N = getValue(I.getOperand(0));
1229 const Type *Ty = I.getOperand(0)->getType();
1231 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1234 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1235 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1238 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1239 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1240 getIntPtrConstant(Offset));
1242 Ty = StTy->getElementType(Field);
1244 Ty = cast<SequentialType>(Ty)->getElementType();
1246 // If this is a constant subscript, handle it quickly.
1247 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1248 if (CI->getRawValue() == 0) continue;
1251 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1252 Offs = (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
1254 Offs = TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1255 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1259 // N = N + Idx * ElementSize;
1260 uint64_t ElementSize = TD->getTypeSize(Ty);
1261 SDOperand IdxN = getValue(Idx);
1263 // If the index is smaller or larger than intptr_t, truncate or extend
1265 if (IdxN.getValueType() < N.getValueType()) {
1266 if (Idx->getType()->isSigned())
1267 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1269 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1270 } else if (IdxN.getValueType() > N.getValueType())
1271 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1273 // If this is a multiply by a power of two, turn it into a shl
1274 // immediately. This is a very common case.
1275 if (isPowerOf2_64(ElementSize)) {
1276 unsigned Amt = Log2_64(ElementSize);
1277 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1278 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1279 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1283 SDOperand Scale = getIntPtrConstant(ElementSize);
1284 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1285 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1291 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1292 // If this is a fixed sized alloca in the entry block of the function,
1293 // allocate it statically on the stack.
1294 if (FuncInfo.StaticAllocaMap.count(&I))
1295 return; // getValue will auto-populate this.
1297 const Type *Ty = I.getAllocatedType();
1298 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1299 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
1302 SDOperand AllocSize = getValue(I.getArraySize());
1303 MVT::ValueType IntPtr = TLI.getPointerTy();
1304 if (IntPtr < AllocSize.getValueType())
1305 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1306 else if (IntPtr > AllocSize.getValueType())
1307 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1309 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1310 getIntPtrConstant(TySize));
1312 // Handle alignment. If the requested alignment is less than or equal to the
1313 // stack alignment, ignore it and round the size of the allocation up to the
1314 // stack alignment size. If the size is greater than the stack alignment, we
1315 // note this in the DYNAMIC_STACKALLOC node.
1316 unsigned StackAlign =
1317 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1318 if (Align <= StackAlign) {
1320 // Add SA-1 to the size.
1321 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1322 getIntPtrConstant(StackAlign-1));
1323 // Mask out the low bits for alignment purposes.
1324 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1325 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1328 std::vector<MVT::ValueType> VTs;
1329 VTs.push_back(AllocSize.getValueType());
1330 VTs.push_back(MVT::Other);
1331 std::vector<SDOperand> Ops;
1332 Ops.push_back(getRoot());
1333 Ops.push_back(AllocSize);
1334 Ops.push_back(getIntPtrConstant(Align));
1335 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
1336 DAG.setRoot(setValue(&I, DSA).getValue(1));
1338 // Inform the Frame Information that we have just allocated a variable-sized
1340 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1343 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1344 SDOperand Ptr = getValue(I.getOperand(0));
1350 // Do not serialize non-volatile loads against each other.
1351 Root = DAG.getRoot();
1354 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1355 Root, I.isVolatile()));
1358 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1359 SDOperand SrcValue, SDOperand Root,
1362 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1363 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1364 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
1366 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
1370 DAG.setRoot(L.getValue(1));
1372 PendingLoads.push_back(L.getValue(1));
1378 void SelectionDAGLowering::visitStore(StoreInst &I) {
1379 Value *SrcV = I.getOperand(0);
1380 SDOperand Src = getValue(SrcV);
1381 SDOperand Ptr = getValue(I.getOperand(1));
1382 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1383 DAG.getSrcValue(I.getOperand(1))));
1386 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1387 /// access memory and has no other side effects at all.
1388 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1389 #define GET_NO_MEMORY_INTRINSICS
1390 #include "llvm/Intrinsics.gen"
1391 #undef GET_NO_MEMORY_INTRINSICS
1395 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1396 // have any side-effects or if it only reads memory.
1397 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1398 #define GET_SIDE_EFFECT_INFO
1399 #include "llvm/Intrinsics.gen"
1400 #undef GET_SIDE_EFFECT_INFO
1404 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1406 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1407 unsigned Intrinsic) {
1408 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1409 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1411 // Build the operand list.
1412 std::vector<SDOperand> Ops;
1413 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1415 // We don't need to serialize loads against other loads.
1416 Ops.push_back(DAG.getRoot());
1418 Ops.push_back(getRoot());
1422 // Add the intrinsic ID as an integer operand.
1423 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1425 // Add all operands of the call to the operand list.
1426 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1427 SDOperand Op = getValue(I.getOperand(i));
1429 // If this is a vector type, force it to the right packed type.
1430 if (Op.getValueType() == MVT::Vector) {
1431 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1432 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1434 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1435 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1436 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1439 assert(TLI.isTypeLegal(Op.getValueType()) &&
1440 "Intrinsic uses a non-legal type?");
1444 std::vector<MVT::ValueType> VTs;
1445 if (I.getType() != Type::VoidTy) {
1446 MVT::ValueType VT = TLI.getValueType(I.getType());
1447 if (VT == MVT::Vector) {
1448 const PackedType *DestTy = cast<PackedType>(I.getType());
1449 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1451 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1452 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1455 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1459 VTs.push_back(MVT::Other);
1464 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1465 else if (I.getType() != Type::VoidTy)
1466 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1468 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1471 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1473 PendingLoads.push_back(Chain);
1477 if (I.getType() != Type::VoidTy) {
1478 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1479 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1480 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1481 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1482 DAG.getValueType(EVT));
1484 setValue(&I, Result);
1488 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1489 /// we want to emit this as a call to a named external function, return the name
1490 /// otherwise lower it and return null.
1492 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1493 switch (Intrinsic) {
1495 // By default, turn this into a target intrinsic node.
1496 visitTargetIntrinsic(I, Intrinsic);
1498 case Intrinsic::vastart: visitVAStart(I); return 0;
1499 case Intrinsic::vaend: visitVAEnd(I); return 0;
1500 case Intrinsic::vacopy: visitVACopy(I); return 0;
1501 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1502 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1503 case Intrinsic::setjmp:
1504 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1506 case Intrinsic::longjmp:
1507 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1509 case Intrinsic::memcpy_i32:
1510 case Intrinsic::memcpy_i64:
1511 visitMemIntrinsic(I, ISD::MEMCPY);
1513 case Intrinsic::memset_i32:
1514 case Intrinsic::memset_i64:
1515 visitMemIntrinsic(I, ISD::MEMSET);
1517 case Intrinsic::memmove_i32:
1518 case Intrinsic::memmove_i64:
1519 visitMemIntrinsic(I, ISD::MEMMOVE);
1522 case Intrinsic::dbg_stoppoint: {
1523 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1524 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1525 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1526 std::vector<SDOperand> Ops;
1528 Ops.push_back(getRoot());
1529 Ops.push_back(getValue(SPI.getLineValue()));
1530 Ops.push_back(getValue(SPI.getColumnValue()));
1532 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1533 assert(DD && "Not a debug information descriptor");
1534 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1536 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1537 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1539 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
1544 case Intrinsic::dbg_region_start: {
1545 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1546 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1547 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1548 std::vector<SDOperand> Ops;
1550 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1552 Ops.push_back(getRoot());
1553 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1555 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1560 case Intrinsic::dbg_region_end: {
1561 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1562 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1563 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1564 std::vector<SDOperand> Ops;
1566 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1568 Ops.push_back(getRoot());
1569 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1571 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1576 case Intrinsic::dbg_func_start: {
1577 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1578 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1579 if (DebugInfo && FSI.getSubprogram() &&
1580 DebugInfo->Verify(FSI.getSubprogram())) {
1581 std::vector<SDOperand> Ops;
1583 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1585 Ops.push_back(getRoot());
1586 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1588 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1593 case Intrinsic::dbg_declare: {
1594 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1595 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1596 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1597 std::vector<SDOperand> Ops;
1599 SDOperand AddressOp = getValue(DI.getAddress());
1600 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
1601 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1608 case Intrinsic::isunordered_f32:
1609 case Intrinsic::isunordered_f64:
1610 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1611 getValue(I.getOperand(2)), ISD::SETUO));
1614 case Intrinsic::sqrt_f32:
1615 case Intrinsic::sqrt_f64:
1616 setValue(&I, DAG.getNode(ISD::FSQRT,
1617 getValue(I.getOperand(1)).getValueType(),
1618 getValue(I.getOperand(1))));
1620 case Intrinsic::pcmarker: {
1621 SDOperand Tmp = getValue(I.getOperand(1));
1622 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1625 case Intrinsic::readcyclecounter: {
1626 std::vector<MVT::ValueType> VTs;
1627 VTs.push_back(MVT::i64);
1628 VTs.push_back(MVT::Other);
1629 std::vector<SDOperand> Ops;
1630 Ops.push_back(getRoot());
1631 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1633 DAG.setRoot(Tmp.getValue(1));
1636 case Intrinsic::bswap_i16:
1637 case Intrinsic::bswap_i32:
1638 case Intrinsic::bswap_i64:
1639 setValue(&I, DAG.getNode(ISD::BSWAP,
1640 getValue(I.getOperand(1)).getValueType(),
1641 getValue(I.getOperand(1))));
1643 case Intrinsic::cttz_i8:
1644 case Intrinsic::cttz_i16:
1645 case Intrinsic::cttz_i32:
1646 case Intrinsic::cttz_i64:
1647 setValue(&I, DAG.getNode(ISD::CTTZ,
1648 getValue(I.getOperand(1)).getValueType(),
1649 getValue(I.getOperand(1))));
1651 case Intrinsic::ctlz_i8:
1652 case Intrinsic::ctlz_i16:
1653 case Intrinsic::ctlz_i32:
1654 case Intrinsic::ctlz_i64:
1655 setValue(&I, DAG.getNode(ISD::CTLZ,
1656 getValue(I.getOperand(1)).getValueType(),
1657 getValue(I.getOperand(1))));
1659 case Intrinsic::ctpop_i8:
1660 case Intrinsic::ctpop_i16:
1661 case Intrinsic::ctpop_i32:
1662 case Intrinsic::ctpop_i64:
1663 setValue(&I, DAG.getNode(ISD::CTPOP,
1664 getValue(I.getOperand(1)).getValueType(),
1665 getValue(I.getOperand(1))));
1667 case Intrinsic::stacksave: {
1668 std::vector<MVT::ValueType> VTs;
1669 VTs.push_back(TLI.getPointerTy());
1670 VTs.push_back(MVT::Other);
1671 std::vector<SDOperand> Ops;
1672 Ops.push_back(getRoot());
1673 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1675 DAG.setRoot(Tmp.getValue(1));
1678 case Intrinsic::stackrestore: {
1679 SDOperand Tmp = getValue(I.getOperand(1));
1680 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1683 case Intrinsic::prefetch:
1684 // FIXME: Currently discarding prefetches.
1690 void SelectionDAGLowering::visitCall(CallInst &I) {
1691 const char *RenameFn = 0;
1692 if (Function *F = I.getCalledFunction()) {
1693 if (F->isExternal())
1694 if (unsigned IID = F->getIntrinsicID()) {
1695 RenameFn = visitIntrinsicCall(I, IID);
1698 } else { // Not an LLVM intrinsic.
1699 const std::string &Name = F->getName();
1700 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1701 if (I.getNumOperands() == 3 && // Basic sanity checks.
1702 I.getOperand(1)->getType()->isFloatingPoint() &&
1703 I.getType() == I.getOperand(1)->getType() &&
1704 I.getType() == I.getOperand(2)->getType()) {
1705 SDOperand LHS = getValue(I.getOperand(1));
1706 SDOperand RHS = getValue(I.getOperand(2));
1707 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1711 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1712 if (I.getNumOperands() == 2 && // Basic sanity checks.
1713 I.getOperand(1)->getType()->isFloatingPoint() &&
1714 I.getType() == I.getOperand(1)->getType()) {
1715 SDOperand Tmp = getValue(I.getOperand(1));
1716 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1719 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1720 if (I.getNumOperands() == 2 && // Basic sanity checks.
1721 I.getOperand(1)->getType()->isFloatingPoint() &&
1722 I.getType() == I.getOperand(1)->getType()) {
1723 SDOperand Tmp = getValue(I.getOperand(1));
1724 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1727 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1728 if (I.getNumOperands() == 2 && // Basic sanity checks.
1729 I.getOperand(1)->getType()->isFloatingPoint() &&
1730 I.getType() == I.getOperand(1)->getType()) {
1731 SDOperand Tmp = getValue(I.getOperand(1));
1732 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1737 } else if (isa<InlineAsm>(I.getOperand(0))) {
1744 Callee = getValue(I.getOperand(0));
1746 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1747 std::vector<std::pair<SDOperand, const Type*> > Args;
1748 Args.reserve(I.getNumOperands());
1749 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1750 Value *Arg = I.getOperand(i);
1751 SDOperand ArgNode = getValue(Arg);
1752 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1755 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1756 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1758 std::pair<SDOperand,SDOperand> Result =
1759 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1760 I.isTailCall(), Callee, Args, DAG);
1761 if (I.getType() != Type::VoidTy)
1762 setValue(&I, Result.first);
1763 DAG.setRoot(Result.second);
1766 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1767 SDOperand &Chain, SDOperand &Flag)const{
1768 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1769 Chain = Val.getValue(1);
1770 Flag = Val.getValue(2);
1772 // If the result was expanded, copy from the top part.
1773 if (Regs.size() > 1) {
1774 assert(Regs.size() == 2 &&
1775 "Cannot expand to more than 2 elts yet!");
1776 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1777 Chain = Val.getValue(1);
1778 Flag = Val.getValue(2);
1779 if (DAG.getTargetLoweringInfo().isLittleEndian())
1780 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1782 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
1785 // Otherwise, if the return value was promoted or extended, truncate it to the
1786 // appropriate type.
1787 if (RegVT == ValueVT)
1790 if (MVT::isInteger(RegVT)) {
1791 if (ValueVT < RegVT)
1792 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1794 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1796 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1800 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1801 /// specified value into the registers specified by this object. This uses
1802 /// Chain/Flag as the input and updates them for the output Chain/Flag.
1803 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1804 SDOperand &Chain, SDOperand &Flag,
1805 MVT::ValueType PtrVT) const {
1806 if (Regs.size() == 1) {
1807 // If there is a single register and the types differ, this must be
1809 if (RegVT != ValueVT) {
1810 if (MVT::isInteger(RegVT)) {
1811 if (RegVT < ValueVT)
1812 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
1814 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1816 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1818 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1819 Flag = Chain.getValue(1);
1821 std::vector<unsigned> R(Regs);
1822 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1823 std::reverse(R.begin(), R.end());
1825 for (unsigned i = 0, e = R.size(); i != e; ++i) {
1826 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1827 DAG.getConstant(i, PtrVT));
1828 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
1829 Flag = Chain.getValue(1);
1834 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
1835 /// operand list. This adds the code marker and includes the number of
1836 /// values added into it.
1837 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1838 std::vector<SDOperand> &Ops) const {
1839 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1840 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1841 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1844 /// isAllocatableRegister - If the specified register is safe to allocate,
1845 /// i.e. it isn't a stack pointer or some other special register, return the
1846 /// register class for the register. Otherwise, return null.
1847 static const TargetRegisterClass *
1848 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1849 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1850 MVT::ValueType FoundVT = MVT::Other;
1851 const TargetRegisterClass *FoundRC = 0;
1852 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1853 E = MRI->regclass_end(); RCI != E; ++RCI) {
1854 MVT::ValueType ThisVT = MVT::Other;
1856 const TargetRegisterClass *RC = *RCI;
1857 // If none of the the value types for this register class are valid, we
1858 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1859 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1861 if (TLI.isTypeLegal(*I)) {
1862 // If we have already found this register in a different register class,
1863 // choose the one with the largest VT specified. For example, on
1864 // PowerPC, we favor f64 register classes over f32.
1865 if (FoundVT == MVT::Other ||
1866 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1873 if (ThisVT == MVT::Other) continue;
1875 // NOTE: This isn't ideal. In particular, this might allocate the
1876 // frame pointer in functions that need it (due to them not being taken
1877 // out of allocation, because a variable sized allocation hasn't been seen
1878 // yet). This is a slight code pessimization, but should still work.
1879 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1880 E = RC->allocation_order_end(MF); I != E; ++I)
1882 // We found a matching register class. Keep looking at others in case
1883 // we find one with larger registers that this physreg is also in.
1892 RegsForValue SelectionDAGLowering::
1893 GetRegistersForValue(const std::string &ConstrCode,
1894 MVT::ValueType VT, bool isOutReg, bool isInReg,
1895 std::set<unsigned> &OutputRegs,
1896 std::set<unsigned> &InputRegs) {
1897 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1898 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1899 std::vector<unsigned> Regs;
1901 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1902 MVT::ValueType RegVT;
1903 MVT::ValueType ValueVT = VT;
1905 if (PhysReg.first) {
1906 if (VT == MVT::Other)
1907 ValueVT = *PhysReg.second->vt_begin();
1909 // Get the actual register value type. This is important, because the user
1910 // may have asked for (e.g.) the AX register in i32 type. We need to
1911 // remember that AX is actually i16 to get the right extension.
1912 RegVT = *PhysReg.second->vt_begin();
1914 // This is a explicit reference to a physical register.
1915 Regs.push_back(PhysReg.first);
1917 // If this is an expanded reference, add the rest of the regs to Regs.
1919 TargetRegisterClass::iterator I = PhysReg.second->begin();
1920 TargetRegisterClass::iterator E = PhysReg.second->end();
1921 for (; *I != PhysReg.first; ++I)
1922 assert(I != E && "Didn't find reg!");
1924 // Already added the first reg.
1926 for (; NumRegs; --NumRegs, ++I) {
1927 assert(I != E && "Ran out of registers to allocate!");
1931 return RegsForValue(Regs, RegVT, ValueVT);
1934 // This is a reference to a register class. Allocate NumRegs consecutive,
1935 // available, registers from the class.
1936 std::vector<unsigned> RegClassRegs =
1937 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1939 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1940 MachineFunction &MF = *CurMBB->getParent();
1941 unsigned NumAllocated = 0;
1942 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1943 unsigned Reg = RegClassRegs[i];
1944 // See if this register is available.
1945 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1946 (isInReg && InputRegs.count(Reg))) { // Already used.
1947 // Make sure we find consecutive registers.
1952 // Check to see if this register is allocatable (i.e. don't give out the
1954 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
1956 // Make sure we find consecutive registers.
1961 // Okay, this register is good, we can use it.
1964 // If we allocated enough consecutive
1965 if (NumAllocated == NumRegs) {
1966 unsigned RegStart = (i-NumAllocated)+1;
1967 unsigned RegEnd = i+1;
1968 // Mark all of the allocated registers used.
1969 for (unsigned i = RegStart; i != RegEnd; ++i) {
1970 unsigned Reg = RegClassRegs[i];
1971 Regs.push_back(Reg);
1972 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1973 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1976 return RegsForValue(Regs, *RC->vt_begin(), VT);
1980 // Otherwise, we couldn't allocate enough registers for this.
1981 return RegsForValue();
1985 /// visitInlineAsm - Handle a call to an InlineAsm object.
1987 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1988 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1990 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1993 // Note, we treat inline asms both with and without side-effects as the same.
1994 // If an inline asm doesn't have side effects and doesn't access memory, we
1995 // could not choose to not chain it.
1996 bool hasSideEffects = IA->hasSideEffects();
1998 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1999 std::vector<MVT::ValueType> ConstraintVTs;
2001 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2002 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2003 /// if it is a def of that register.
2004 std::vector<SDOperand> AsmNodeOperands;
2005 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2006 AsmNodeOperands.push_back(AsmStr);
2008 SDOperand Chain = getRoot();
2011 // We fully assign registers here at isel time. This is not optimal, but
2012 // should work. For register classes that correspond to LLVM classes, we
2013 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2014 // over the constraints, collecting fixed registers that we know we can't use.
2015 std::set<unsigned> OutputRegs, InputRegs;
2017 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2018 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2019 std::string &ConstraintCode = Constraints[i].Codes[0];
2021 MVT::ValueType OpVT;
2023 // Compute the value type for each operand and add it to ConstraintVTs.
2024 switch (Constraints[i].Type) {
2025 case InlineAsm::isOutput:
2026 if (!Constraints[i].isIndirectOutput) {
2027 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2028 OpVT = TLI.getValueType(I.getType());
2030 const Type *OpTy = I.getOperand(OpNum)->getType();
2031 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2032 OpNum++; // Consumes a call operand.
2035 case InlineAsm::isInput:
2036 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2037 OpNum++; // Consumes a call operand.
2039 case InlineAsm::isClobber:
2044 ConstraintVTs.push_back(OpVT);
2046 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2047 continue; // Not assigned a fixed reg.
2049 // Build a list of regs that this operand uses. This always has a single
2050 // element for promoted/expanded operands.
2051 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2053 OutputRegs, InputRegs);
2055 switch (Constraints[i].Type) {
2056 case InlineAsm::isOutput:
2057 // We can't assign any other output to this register.
2058 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2059 // If this is an early-clobber output, it cannot be assigned to the same
2060 // value as the input reg.
2061 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2062 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2064 case InlineAsm::isInput:
2065 // We can't assign any other input to this register.
2066 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2068 case InlineAsm::isClobber:
2069 // Clobbered regs cannot be used as inputs or outputs.
2070 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2071 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2076 // Loop over all of the inputs, copying the operand values into the
2077 // appropriate registers and processing the output regs.
2078 RegsForValue RetValRegs;
2079 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2082 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2083 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2084 std::string &ConstraintCode = Constraints[i].Codes[0];
2086 switch (Constraints[i].Type) {
2087 case InlineAsm::isOutput: {
2088 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2089 if (ConstraintCode.size() == 1) // not a physreg name.
2090 CTy = TLI.getConstraintType(ConstraintCode[0]);
2092 if (CTy == TargetLowering::C_Memory) {
2094 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2096 // Check that the operand (the address to store to) isn't a float.
2097 if (!MVT::isInteger(InOperandVal.getValueType()))
2098 assert(0 && "MATCH FAIL!");
2100 if (!Constraints[i].isIndirectOutput)
2101 assert(0 && "MATCH FAIL!");
2103 OpNum++; // Consumes a call operand.
2105 // Extend/truncate to the right pointer type if needed.
2106 MVT::ValueType PtrType = TLI.getPointerTy();
2107 if (InOperandVal.getValueType() < PtrType)
2108 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2109 else if (InOperandVal.getValueType() > PtrType)
2110 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2112 // Add information to the INLINEASM node to know about this output.
2113 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2114 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2115 AsmNodeOperands.push_back(InOperandVal);
2119 // Otherwise, this is a register output.
2120 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2122 // If this is an early-clobber output, or if there is an input
2123 // constraint that matches this, we need to reserve the input register
2124 // so no other inputs allocate to it.
2125 bool UsesInputRegister = false;
2126 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2127 UsesInputRegister = true;
2129 // Copy the output from the appropriate register. Find a register that
2132 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2133 true, UsesInputRegister,
2134 OutputRegs, InputRegs);
2135 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
2137 if (!Constraints[i].isIndirectOutput) {
2138 assert(RetValRegs.Regs.empty() &&
2139 "Cannot have multiple output constraints yet!");
2140 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2143 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2144 I.getOperand(OpNum)));
2145 OpNum++; // Consumes a call operand.
2148 // Add information to the INLINEASM node to know that this register is
2150 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2153 case InlineAsm::isInput: {
2154 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2155 OpNum++; // Consumes a call operand.
2157 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2158 // If this is required to match an output register we have already set,
2159 // just use its register.
2160 unsigned OperandNo = atoi(ConstraintCode.c_str());
2162 // Scan until we find the definition we already emitted of this operand.
2163 // When we find it, create a RegsForValue operand.
2164 unsigned CurOp = 2; // The first operand.
2165 for (; OperandNo; --OperandNo) {
2166 // Advance to the next operand.
2168 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2169 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2170 "Skipped past definitions?");
2171 CurOp += (NumOps>>3)+1;
2175 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2176 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2177 "Skipped past definitions?");
2179 // Add NumOps>>3 registers to MatchedRegs.
2180 RegsForValue MatchedRegs;
2181 MatchedRegs.ValueVT = InOperandVal.getValueType();
2182 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2183 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2184 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2185 MatchedRegs.Regs.push_back(Reg);
2188 // Use the produced MatchedRegs object to
2189 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2190 TLI.getPointerTy());
2191 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2195 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2196 if (ConstraintCode.size() == 1) // not a physreg name.
2197 CTy = TLI.getConstraintType(ConstraintCode[0]);
2199 if (CTy == TargetLowering::C_Other) {
2200 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2201 assert(0 && "MATCH FAIL!");
2203 // Add information to the INLINEASM node to know about this input.
2204 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2205 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2206 AsmNodeOperands.push_back(InOperandVal);
2208 } else if (CTy == TargetLowering::C_Memory) {
2211 // Check that the operand isn't a float.
2212 if (!MVT::isInteger(InOperandVal.getValueType()))
2213 assert(0 && "MATCH FAIL!");
2215 // Extend/truncate to the right pointer type if needed.
2216 MVT::ValueType PtrType = TLI.getPointerTy();
2217 if (InOperandVal.getValueType() < PtrType)
2218 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2219 else if (InOperandVal.getValueType() > PtrType)
2220 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2222 // Add information to the INLINEASM node to know about this input.
2223 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2224 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2225 AsmNodeOperands.push_back(InOperandVal);
2229 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2231 // Copy the input into the appropriate registers.
2232 RegsForValue InRegs =
2233 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2234 false, true, OutputRegs, InputRegs);
2235 // FIXME: should be match fail.
2236 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2238 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
2240 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2243 case InlineAsm::isClobber: {
2244 RegsForValue ClobberedRegs =
2245 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2246 OutputRegs, InputRegs);
2247 // Add the clobbered value to the operand list, so that the register
2248 // allocator is aware that the physreg got clobbered.
2249 if (!ClobberedRegs.Regs.empty())
2250 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2256 // Finish up input operands.
2257 AsmNodeOperands[0] = Chain;
2258 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2260 std::vector<MVT::ValueType> VTs;
2261 VTs.push_back(MVT::Other);
2262 VTs.push_back(MVT::Flag);
2263 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2264 Flag = Chain.getValue(1);
2266 // If this asm returns a register value, copy the result from that register
2267 // and set it as the value of the call.
2268 if (!RetValRegs.Regs.empty())
2269 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2271 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2273 // Process indirect outputs, first output all of the flagged copies out of
2275 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2276 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2277 Value *Ptr = IndirectStoresToEmit[i].second;
2278 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2279 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2282 // Emit the non-flagged stores from the physregs.
2283 std::vector<SDOperand> OutChains;
2284 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2285 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2286 StoresToEmit[i].first,
2287 getValue(StoresToEmit[i].second),
2288 DAG.getSrcValue(StoresToEmit[i].second)));
2289 if (!OutChains.empty())
2290 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
2295 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2296 SDOperand Src = getValue(I.getOperand(0));
2298 MVT::ValueType IntPtr = TLI.getPointerTy();
2300 if (IntPtr < Src.getValueType())
2301 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2302 else if (IntPtr > Src.getValueType())
2303 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2305 // Scale the source by the type size.
2306 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2307 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2308 Src, getIntPtrConstant(ElementSize));
2310 std::vector<std::pair<SDOperand, const Type*> > Args;
2311 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
2313 std::pair<SDOperand,SDOperand> Result =
2314 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2315 DAG.getExternalSymbol("malloc", IntPtr),
2317 setValue(&I, Result.first); // Pointers always fit in registers
2318 DAG.setRoot(Result.second);
2321 void SelectionDAGLowering::visitFree(FreeInst &I) {
2322 std::vector<std::pair<SDOperand, const Type*> > Args;
2323 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2324 TLI.getTargetData()->getIntPtrType()));
2325 MVT::ValueType IntPtr = TLI.getPointerTy();
2326 std::pair<SDOperand,SDOperand> Result =
2327 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2328 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2329 DAG.setRoot(Result.second);
2332 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2333 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2334 // instructions are special in various ways, which require special support to
2335 // insert. The specified MachineInstr is created but not inserted into any
2336 // basic blocks, and the scheduler passes ownership of it to this method.
2337 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2338 MachineBasicBlock *MBB) {
2339 std::cerr << "If a target marks an instruction with "
2340 "'usesCustomDAGSchedInserter', it must implement "
2341 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2346 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2347 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2348 getValue(I.getOperand(1)),
2349 DAG.getSrcValue(I.getOperand(1))));
2352 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2353 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2354 getValue(I.getOperand(0)),
2355 DAG.getSrcValue(I.getOperand(0)));
2357 DAG.setRoot(V.getValue(1));
2360 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2361 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2362 getValue(I.getOperand(1)),
2363 DAG.getSrcValue(I.getOperand(1))));
2366 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2367 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2368 getValue(I.getOperand(1)),
2369 getValue(I.getOperand(2)),
2370 DAG.getSrcValue(I.getOperand(1)),
2371 DAG.getSrcValue(I.getOperand(2))));
2374 /// TargetLowering::LowerArguments - This is the default LowerArguments
2375 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
2376 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2377 /// integrated into SDISel.
2378 std::vector<SDOperand>
2379 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2380 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2381 std::vector<SDOperand> Ops;
2382 Ops.push_back(DAG.getRoot());
2383 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2384 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2386 // Add one result value for each formal argument.
2387 std::vector<MVT::ValueType> RetVals;
2388 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2389 MVT::ValueType VT = getValueType(I->getType());
2391 switch (getTypeAction(VT)) {
2392 default: assert(0 && "Unknown type action!");
2394 RetVals.push_back(VT);
2397 RetVals.push_back(getTypeToTransformTo(VT));
2400 if (VT != MVT::Vector) {
2401 // If this is a large integer, it needs to be broken up into small
2402 // integers. Figure out what the destination type is and how many small
2403 // integers it turns into.
2404 MVT::ValueType NVT = getTypeToTransformTo(VT);
2405 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2406 for (unsigned i = 0; i != NumVals; ++i)
2407 RetVals.push_back(NVT);
2409 // Otherwise, this is a vector type. We only support legal vectors
2411 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2412 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2414 // Figure out if there is a Packed type corresponding to this Vector
2415 // type. If so, convert to the packed type.
2416 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2417 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2418 RetVals.push_back(TVT);
2420 assert(0 && "Don't support illegal by-val vector arguments yet!");
2427 RetVals.push_back(MVT::Other);
2430 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, RetVals, Ops).Val;
2432 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
2434 // Set up the return result vector.
2437 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2438 MVT::ValueType VT = getValueType(I->getType());
2440 switch (getTypeAction(VT)) {
2441 default: assert(0 && "Unknown type action!");
2443 Ops.push_back(SDOperand(Result, i++));
2446 SDOperand Op(Result, i++);
2447 if (MVT::isInteger(VT)) {
2448 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2450 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2451 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2453 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2454 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2460 if (VT != MVT::Vector) {
2461 // If this is a large integer, it needs to be reassembled from small
2462 // integers. Figure out what the source elt type is and how many small
2464 MVT::ValueType NVT = getTypeToTransformTo(VT);
2465 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2467 SDOperand Lo = SDOperand(Result, i++);
2468 SDOperand Hi = SDOperand(Result, i++);
2470 if (!isLittleEndian())
2473 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2475 // Value scalarized into many values. Unimp for now.
2476 assert(0 && "Cannot expand i64 -> i16 yet!");
2479 // Otherwise, this is a vector type. We only support legal vectors
2481 const PackedType *PTy = cast<PackedType>(I->getType());
2482 unsigned NumElems = PTy->getNumElements();
2483 const Type *EltTy = PTy->getElementType();
2485 // Figure out if there is a Packed type corresponding to this Vector
2486 // type. If so, convert to the packed type.
2487 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2488 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2489 SDOperand N = SDOperand(Result, i++);
2490 // Handle copies from generic vectors to registers.
2491 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2492 DAG.getConstant(NumElems, MVT::i32),
2493 DAG.getValueType(getValueType(EltTy)));
2496 assert(0 && "Don't support illegal by-val vector arguments yet!");
2507 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
2508 /// implementation, which just inserts an ISD::CALL node, which is later custom
2509 /// lowered by the target to something concrete. FIXME: When all targets are
2510 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2511 std::pair<SDOperand, SDOperand>
2512 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2513 unsigned CallingConv, bool isTailCall,
2515 ArgListTy &Args, SelectionDAG &DAG) {
2516 std::vector<SDOperand> Ops;
2517 Ops.push_back(Chain); // Op#0 - Chain
2518 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2519 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2520 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2521 Ops.push_back(Callee);
2523 // Handle all of the outgoing arguments.
2524 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2525 MVT::ValueType VT = getValueType(Args[i].second);
2526 SDOperand Op = Args[i].first;
2527 bool isSigned = Args[i].second->isSigned();
2528 switch (getTypeAction(VT)) {
2529 default: assert(0 && "Unknown type action!");
2532 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2535 if (MVT::isInteger(VT)) {
2536 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2537 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2539 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2540 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2543 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2546 if (VT != MVT::Vector) {
2547 // If this is a large integer, it needs to be broken down into small
2548 // integers. Figure out what the source elt type is and how many small
2550 MVT::ValueType NVT = getTypeToTransformTo(VT);
2551 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2553 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2554 DAG.getConstant(0, getPointerTy()));
2555 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2556 DAG.getConstant(1, getPointerTy()));
2557 if (!isLittleEndian())
2561 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2563 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2565 // Value scalarized into many values. Unimp for now.
2566 assert(0 && "Cannot expand i64 -> i16 yet!");
2569 // Otherwise, this is a vector type. We only support legal vectors
2571 const PackedType *PTy = cast<PackedType>(Args[i].second);
2572 unsigned NumElems = PTy->getNumElements();
2573 const Type *EltTy = PTy->getElementType();
2575 // Figure out if there is a Packed type corresponding to this Vector
2576 // type. If so, convert to the packed type.
2577 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2578 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2579 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2580 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2582 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2584 assert(0 && "Don't support illegal by-val vector call args yet!");
2592 // Figure out the result value types.
2593 std::vector<MVT::ValueType> RetTys;
2595 if (RetTy != Type::VoidTy) {
2596 MVT::ValueType VT = getValueType(RetTy);
2597 switch (getTypeAction(VT)) {
2598 default: assert(0 && "Unknown type action!");
2600 RetTys.push_back(VT);
2603 RetTys.push_back(getTypeToTransformTo(VT));
2606 if (VT != MVT::Vector) {
2607 // If this is a large integer, it needs to be reassembled from small
2608 // integers. Figure out what the source elt type is and how many small
2610 MVT::ValueType NVT = getTypeToTransformTo(VT);
2611 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2612 for (unsigned i = 0; i != NumVals; ++i)
2613 RetTys.push_back(NVT);
2615 // Otherwise, this is a vector type. We only support legal vectors
2617 const PackedType *PTy = cast<PackedType>(RetTy);
2618 unsigned NumElems = PTy->getNumElements();
2619 const Type *EltTy = PTy->getElementType();
2621 // Figure out if there is a Packed type corresponding to this Vector
2622 // type. If so, convert to the packed type.
2623 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2624 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2625 RetTys.push_back(TVT);
2627 assert(0 && "Don't support illegal by-val vector call results yet!");
2634 RetTys.push_back(MVT::Other); // Always has a chain.
2636 // Finally, create the CALL node.
2637 SDOperand Res = DAG.getNode(ISD::CALL, RetTys, Ops);
2639 // This returns a pair of operands. The first element is the
2640 // return value for the function (if RetTy is not VoidTy). The second
2641 // element is the outgoing token chain.
2643 if (RetTys.size() != 1) {
2644 MVT::ValueType VT = getValueType(RetTy);
2645 if (RetTys.size() == 2) {
2648 // If this value was promoted, truncate it down.
2649 if (ResVal.getValueType() != VT) {
2650 if (VT == MVT::Vector) {
2651 // Insert a VBITCONVERT to convert from the packed result type to the
2652 // MVT::Vector type.
2653 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2654 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2656 // Figure out if there is a Packed type corresponding to this Vector
2657 // type. If so, convert to the packed type.
2658 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2659 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2660 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2661 // "N x PTyElementVT" MVT::Vector type.
2662 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
2663 DAG.getConstant(NumElems, MVT::i32),
2664 DAG.getValueType(getValueType(EltTy)));
2668 } else if (MVT::isInteger(VT)) {
2669 unsigned AssertOp = RetTy->isSigned() ?
2670 ISD::AssertSext : ISD::AssertZext;
2671 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2672 DAG.getValueType(VT));
2673 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2675 assert(MVT::isFloatingPoint(VT));
2676 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2679 } else if (RetTys.size() == 3) {
2680 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2681 Res.getValue(0), Res.getValue(1));
2684 assert(0 && "Case not handled yet!");
2688 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2693 // It is always conservatively correct for llvm.returnaddress and
2694 // llvm.frameaddress to return 0.
2696 // FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2697 // expanded to 0 if the target wants.
2698 std::pair<SDOperand, SDOperand>
2699 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2700 unsigned Depth, SelectionDAG &DAG) {
2701 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
2704 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
2705 assert(0 && "LowerOperation not implemented for this target!");
2710 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2711 SelectionDAG &DAG) {
2712 assert(0 && "CustomPromoteOperation not implemented for this target!");
2717 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2718 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2719 std::pair<SDOperand,SDOperand> Result =
2720 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
2721 setValue(&I, Result.first);
2722 DAG.setRoot(Result.second);
2725 /// getMemsetValue - Vectorized representation of the memset value
2727 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2728 SelectionDAG &DAG) {
2729 MVT::ValueType CurVT = VT;
2730 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2731 uint64_t Val = C->getValue() & 255;
2733 while (CurVT != MVT::i8) {
2734 Val = (Val << Shift) | Val;
2736 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2738 return DAG.getConstant(Val, VT);
2740 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2742 while (CurVT != MVT::i8) {
2744 DAG.getNode(ISD::OR, VT,
2745 DAG.getNode(ISD::SHL, VT, Value,
2746 DAG.getConstant(Shift, MVT::i8)), Value);
2748 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2755 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2756 /// used when a memcpy is turned into a memset when the source is a constant
2758 static SDOperand getMemsetStringVal(MVT::ValueType VT,
2759 SelectionDAG &DAG, TargetLowering &TLI,
2760 std::string &Str, unsigned Offset) {
2761 MVT::ValueType CurVT = VT;
2763 unsigned MSB = getSizeInBits(VT) / 8;
2764 if (TLI.isLittleEndian())
2765 Offset = Offset + MSB - 1;
2766 for (unsigned i = 0; i != MSB; ++i) {
2767 Val = (Val << 8) | Str[Offset];
2768 Offset += TLI.isLittleEndian() ? -1 : 1;
2770 return DAG.getConstant(Val, VT);
2773 /// getMemBasePlusOffset - Returns base and offset node for the
2774 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2775 SelectionDAG &DAG, TargetLowering &TLI) {
2776 MVT::ValueType VT = Base.getValueType();
2777 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2780 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2781 /// to replace the memset / memcpy is below the threshold. It also returns the
2782 /// types of the sequence of memory ops to perform memset / memcpy.
2783 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2784 unsigned Limit, uint64_t Size,
2785 unsigned Align, TargetLowering &TLI) {
2788 if (TLI.allowsUnalignedMemoryAccesses()) {
2791 switch (Align & 7) {
2807 MVT::ValueType LVT = MVT::i64;
2808 while (!TLI.isTypeLegal(LVT))
2809 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2810 assert(MVT::isInteger(LVT));
2815 unsigned NumMemOps = 0;
2817 unsigned VTSize = getSizeInBits(VT) / 8;
2818 while (VTSize > Size) {
2819 VT = (MVT::ValueType)((unsigned)VT - 1);
2822 assert(MVT::isInteger(VT));
2824 if (++NumMemOps > Limit)
2826 MemOps.push_back(VT);
2833 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
2834 SDOperand Op1 = getValue(I.getOperand(1));
2835 SDOperand Op2 = getValue(I.getOperand(2));
2836 SDOperand Op3 = getValue(I.getOperand(3));
2837 SDOperand Op4 = getValue(I.getOperand(4));
2838 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2839 if (Align == 0) Align = 1;
2841 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2842 std::vector<MVT::ValueType> MemOps;
2844 // Expand memset / memcpy to a series of load / store ops
2845 // if the size operand falls below a certain threshold.
2846 std::vector<SDOperand> OutChains;
2848 default: break; // Do nothing for now.
2850 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2851 Size->getValue(), Align, TLI)) {
2852 unsigned NumMemOps = MemOps.size();
2853 unsigned Offset = 0;
2854 for (unsigned i = 0; i < NumMemOps; i++) {
2855 MVT::ValueType VT = MemOps[i];
2856 unsigned VTSize = getSizeInBits(VT) / 8;
2857 SDOperand Value = getMemsetValue(Op2, VT, DAG);
2858 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2860 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2861 DAG.getSrcValue(I.getOperand(1), Offset));
2862 OutChains.push_back(Store);
2869 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2870 Size->getValue(), Align, TLI)) {
2871 unsigned NumMemOps = MemOps.size();
2872 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
2873 GlobalAddressSDNode *G = NULL;
2875 bool CopyFromStr = false;
2877 if (Op2.getOpcode() == ISD::GlobalAddress)
2878 G = cast<GlobalAddressSDNode>(Op2);
2879 else if (Op2.getOpcode() == ISD::ADD &&
2880 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2881 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2882 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
2883 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
2886 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2888 Str = GV->getStringValue(false);
2896 for (unsigned i = 0; i < NumMemOps; i++) {
2897 MVT::ValueType VT = MemOps[i];
2898 unsigned VTSize = getSizeInBits(VT) / 8;
2899 SDOperand Value, Chain, Store;
2902 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2905 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2906 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2907 DAG.getSrcValue(I.getOperand(1), DstOff));
2909 Value = DAG.getLoad(VT, getRoot(),
2910 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2911 DAG.getSrcValue(I.getOperand(2), SrcOff));
2912 Chain = Value.getValue(1);
2914 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2915 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2916 DAG.getSrcValue(I.getOperand(1), DstOff));
2918 OutChains.push_back(Store);
2927 if (!OutChains.empty()) {
2928 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2933 std::vector<SDOperand> Ops;
2934 Ops.push_back(getRoot());
2939 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
2942 //===----------------------------------------------------------------------===//
2943 // SelectionDAGISel code
2944 //===----------------------------------------------------------------------===//
2946 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2947 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2950 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
2951 // FIXME: we only modify the CFG to split critical edges. This
2952 // updates dom and loop info.
2956 /// OptimizeNoopCopyExpression - We have determined that the specified cast
2957 /// instruction is a noop copy (e.g. it's casting from one pointer type to
2958 /// another, int->uint, or int->sbyte on PPC.
2960 /// Return true if any changes are made.
2961 static bool OptimizeNoopCopyExpression(CastInst *CI) {
2962 BasicBlock *DefBB = CI->getParent();
2964 /// InsertedCasts - Only insert a cast in each block once.
2965 std::map<BasicBlock*, CastInst*> InsertedCasts;
2967 bool MadeChange = false;
2968 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
2970 Use &TheUse = UI.getUse();
2971 Instruction *User = cast<Instruction>(*UI);
2973 // Figure out which BB this cast is used in. For PHI's this is the
2974 // appropriate predecessor block.
2975 BasicBlock *UserBB = User->getParent();
2976 if (PHINode *PN = dyn_cast<PHINode>(User)) {
2977 unsigned OpVal = UI.getOperandNo()/2;
2978 UserBB = PN->getIncomingBlock(OpVal);
2981 // Preincrement use iterator so we don't invalidate it.
2984 // If this user is in the same block as the cast, don't change the cast.
2985 if (UserBB == DefBB) continue;
2987 // If we have already inserted a cast into this block, use it.
2988 CastInst *&InsertedCast = InsertedCasts[UserBB];
2990 if (!InsertedCast) {
2991 BasicBlock::iterator InsertPt = UserBB->begin();
2992 while (isa<PHINode>(InsertPt)) ++InsertPt;
2995 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2999 // Replace a use of the cast with a use of the new casat.
3000 TheUse = InsertedCast;
3003 // If we removed all uses, nuke the cast.
3004 if (CI->use_empty())
3005 CI->eraseFromParent();
3010 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3011 /// casting to the type of GEPI.
3012 static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3013 Instruction *GEPI, Value *Ptr,
3015 if (V) return V; // Already computed.
3017 BasicBlock::iterator InsertPt;
3018 if (BB == GEPI->getParent()) {
3019 // If insert into the GEP's block, insert right after the GEP.
3023 // Otherwise, insert at the top of BB, after any PHI nodes
3024 InsertPt = BB->begin();
3025 while (isa<PHINode>(InsertPt)) ++InsertPt;
3028 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3029 // BB so that there is only one value live across basic blocks (the cast
3031 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3032 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3033 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3035 // Add the offset, cast it to the right type.
3036 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
3037 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
3040 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3041 /// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3042 /// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3043 /// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3044 /// sink PtrOffset into user blocks where doing so will likely allow us to fold
3045 /// the constant add into a load or store instruction. Additionally, if a user
3046 /// is a pointer-pointer cast, we look through it to find its users.
3047 static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3048 Constant *PtrOffset, BasicBlock *DefBB,
3049 GetElementPtrInst *GEPI,
3050 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
3051 while (!RepPtr->use_empty()) {
3052 Instruction *User = cast<Instruction>(RepPtr->use_back());
3054 // If the user is a Pointer-Pointer cast, recurse.
3055 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3056 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3058 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3059 // could invalidate an iterator.
3060 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3064 // If this is a load of the pointer, or a store through the pointer, emit
3065 // the increment into the load/store block.
3066 Instruction *NewVal;
3067 if (isa<LoadInst>(User) ||
3068 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3069 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3070 User->getParent(), GEPI,
3073 // If this use is not foldable into the addressing mode, use a version
3074 // emitted in the GEP block.
3075 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3079 if (GEPI->getType() != RepPtr->getType()) {
3080 BasicBlock::iterator IP = NewVal;
3082 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3084 User->replaceUsesOfWith(RepPtr, NewVal);
3089 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3090 /// selection, we want to be a bit careful about some things. In particular, if
3091 /// we have a GEP instruction that is used in a different block than it is
3092 /// defined, the addressing expression of the GEP cannot be folded into loads or
3093 /// stores that use it. In this case, decompose the GEP and move constant
3094 /// indices into blocks that use it.
3095 static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
3096 const TargetData *TD) {
3097 // If this GEP is only used inside the block it is defined in, there is no
3098 // need to rewrite it.
3099 bool isUsedOutsideDefBB = false;
3100 BasicBlock *DefBB = GEPI->getParent();
3101 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3103 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3104 isUsedOutsideDefBB = true;
3108 if (!isUsedOutsideDefBB) return false;
3110 // If this GEP has no non-zero constant indices, there is nothing we can do,
3112 bool hasConstantIndex = false;
3113 bool hasVariableIndex = false;
3114 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3115 E = GEPI->op_end(); OI != E; ++OI) {
3116 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
3117 if (CI->getRawValue()) {
3118 hasConstantIndex = true;
3122 hasVariableIndex = true;
3126 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3127 if (!hasConstantIndex && !hasVariableIndex) {
3128 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3129 GEPI->getName(), GEPI);
3130 GEPI->replaceAllUsesWith(NC);
3131 GEPI->eraseFromParent();
3135 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
3136 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3139 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3140 // constant offset (which we now know is non-zero) and deal with it later.
3141 uint64_t ConstantOffset = 0;
3142 const Type *UIntPtrTy = TD->getIntPtrType();
3143 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3144 const Type *Ty = GEPI->getOperand(0)->getType();
3146 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3147 E = GEPI->op_end(); OI != E; ++OI) {
3149 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3150 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
3152 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
3153 Ty = StTy->getElementType(Field);
3155 Ty = cast<SequentialType>(Ty)->getElementType();
3157 // Handle constant subscripts.
3158 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3159 if (CI->getRawValue() == 0) continue;
3161 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
3162 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
3164 ConstantOffset+=TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
3168 // Ptr = Ptr + Idx * ElementSize;
3170 // Cast Idx to UIntPtrTy if needed.
3171 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3173 uint64_t ElementSize = TD->getTypeSize(Ty);
3174 // Mask off bits that should not be set.
3175 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3176 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
3178 // Multiply by the element size and add to the base.
3179 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3180 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3184 // Make sure that the offset fits in uintptr_t.
3185 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3186 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
3188 // Okay, we have now emitted all of the variable index parts to the BB that
3189 // the GEP is defined in. Loop over all of the using instructions, inserting
3190 // an "add Ptr, ConstantOffset" into each block that uses it and update the
3191 // instruction to use the newly computed value, making GEPI dead. When the
3192 // user is a load or store instruction address, we emit the add into the user
3193 // block, otherwise we use a canonical version right next to the gep (these
3194 // won't be foldable as addresses, so we might as well share the computation).
3196 std::map<BasicBlock*,Instruction*> InsertedExprs;
3197 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3199 // Finally, the GEP is dead, remove it.
3200 GEPI->eraseFromParent();
3205 bool SelectionDAGISel::runOnFunction(Function &Fn) {
3206 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3207 RegMap = MF.getSSARegMap();
3208 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3210 // First, split all critical edges for PHI nodes with incoming values that are
3211 // constants, this way the load of the constant into a vreg will not be placed
3212 // into MBBs that are used some other way.
3214 // In this pass we also look for GEP and cast instructions that are used
3215 // across basic blocks and rewrite them to improve basic-block-at-a-time
3219 bool MadeChange = true;
3220 while (MadeChange) {
3222 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
3224 BasicBlock::iterator BBI;
3225 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
3226 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3227 if (isa<Constant>(PN->getIncomingValue(i)))
3228 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3230 for (BasicBlock::iterator E = BB->end(); BBI != E; ) {
3231 Instruction *I = BBI++;
3232 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3233 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3234 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3235 // If this is a noop copy, sink it into user blocks to reduce the number
3236 // of virtual registers that must be created and coallesced.
3237 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3238 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3240 // This is an fp<->int conversion?
3241 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3244 // If this is an extension, it will be a zero or sign extension, which
3246 if (SrcVT < DstVT) continue;
3248 // If these values will be promoted, find out what they will be promoted
3249 // to. This helps us consider truncates on PPC as noop copies when they
3251 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3252 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3253 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3254 DstVT = TLI.getTypeToTransformTo(DstVT);
3256 // If, after promotion, these are the same types, this is a noop copy.
3258 MadeChange |= OptimizeNoopCopyExpression(CI);
3264 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3266 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3267 SelectBasicBlock(I, MF, FuncInfo);
3273 SDOperand SelectionDAGISel::
3274 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
3275 SDOperand Op = SDL.getValue(V);
3276 assert((Op.getOpcode() != ISD::CopyFromReg ||
3277 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3278 "Copy from a reg to the same reg!");
3280 // If this type is not legal, we must make sure to not create an invalid
3282 MVT::ValueType SrcVT = Op.getValueType();
3283 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3284 SelectionDAG &DAG = SDL.DAG;
3285 if (SrcVT == DestVT) {
3286 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3287 } else if (SrcVT == MVT::Vector) {
3288 // Handle copies from generic vectors to registers.
3289 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3290 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3291 PTyElementVT, PTyLegalElementVT);
3293 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3294 // MVT::Vector type.
3295 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3296 DAG.getConstant(NE, MVT::i32),
3297 DAG.getValueType(PTyElementVT));
3299 // Loop over all of the elements of the resultant vector,
3300 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3301 // copying them into output registers.
3302 std::vector<SDOperand> OutChains;
3303 SDOperand Root = SDL.getRoot();
3304 for (unsigned i = 0; i != NE; ++i) {
3305 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3306 Op, DAG.getConstant(i, TLI.getPointerTy()));
3307 if (PTyElementVT == PTyLegalElementVT) {
3308 // Elements are legal.
3309 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3310 } else if (PTyLegalElementVT > PTyElementVT) {
3311 // Elements are promoted.
3312 if (MVT::isFloatingPoint(PTyLegalElementVT))
3313 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3315 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3316 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3318 // Elements are expanded.
3319 // The src value is expanded into multiple registers.
3320 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3321 Elt, DAG.getConstant(0, TLI.getPointerTy()));
3322 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3323 Elt, DAG.getConstant(1, TLI.getPointerTy()));
3324 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3325 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3328 return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
3329 } else if (SrcVT < DestVT) {
3330 // The src value is promoted to the register.
3331 if (MVT::isFloatingPoint(SrcVT))
3332 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3334 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3335 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3337 // The src value is expanded into multiple registers.
3338 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3339 Op, DAG.getConstant(0, TLI.getPointerTy()));
3340 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3341 Op, DAG.getConstant(1, TLI.getPointerTy()));
3342 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
3343 return DAG.getCopyToReg(Op, Reg+1, Hi);
3347 void SelectionDAGISel::
3348 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3349 std::vector<SDOperand> &UnorderedChains) {
3350 // If this is the entry block, emit arguments.
3351 Function &F = *BB->getParent();
3352 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3353 SDOperand OldRoot = SDL.DAG.getRoot();
3354 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3357 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3359 if (!AI->use_empty()) {
3360 SDL.setValue(AI, Args[a]);
3362 // If this argument is live outside of the entry block, insert a copy from
3363 // whereever we got it to the vreg that other BB's will reference it as.
3364 if (FuncInfo.ValueMap.count(AI)) {
3366 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
3367 UnorderedChains.push_back(Copy);
3371 // Finally, if the target has anything special to do, allow it to do so.
3372 // FIXME: this should insert code into the DAG!
3373 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3376 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3377 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3378 FunctionLoweringInfo &FuncInfo) {
3379 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3381 std::vector<SDOperand> UnorderedChains;
3383 // Lower any arguments needed in this block if this is the entry block.
3384 if (LLVMBB == &LLVMBB->getParent()->front())
3385 LowerArguments(LLVMBB, SDL, UnorderedChains);
3387 BB = FuncInfo.MBBMap[LLVMBB];
3388 SDL.setCurrentBasicBlock(BB);
3390 // Lower all of the non-terminator instructions.
3391 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3395 // Ensure that all instructions which are used outside of their defining
3396 // blocks are available as virtual registers.
3397 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3398 if (!I->use_empty() && !isa<PHINode>(I)) {
3399 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3400 if (VMI != FuncInfo.ValueMap.end())
3401 UnorderedChains.push_back(
3402 CopyValueToVirtualRegister(SDL, I, VMI->second));
3405 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3406 // ensure constants are generated when needed. Remember the virtual registers
3407 // that need to be added to the Machine PHI nodes as input. We cannot just
3408 // directly add them, because expansion might result in multiple MBB's for one
3409 // BB. As such, the start of the BB might correspond to a different MBB than
3413 // Emit constants only once even if used by multiple PHI nodes.
3414 std::map<Constant*, unsigned> ConstantsOut;
3416 // Check successor nodes PHI nodes that expect a constant to be available from
3418 TerminatorInst *TI = LLVMBB->getTerminator();
3419 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3420 BasicBlock *SuccBB = TI->getSuccessor(succ);
3421 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3424 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3425 // nodes and Machine PHI nodes, but the incoming operands have not been
3427 for (BasicBlock::iterator I = SuccBB->begin();
3428 (PN = dyn_cast<PHINode>(I)); ++I)
3429 if (!PN->use_empty()) {
3431 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3432 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3433 unsigned &RegOut = ConstantsOut[C];
3435 RegOut = FuncInfo.CreateRegForValue(C);
3436 UnorderedChains.push_back(
3437 CopyValueToVirtualRegister(SDL, C, RegOut));
3441 Reg = FuncInfo.ValueMap[PHIOp];
3443 assert(isa<AllocaInst>(PHIOp) &&
3444 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3445 "Didn't codegen value into a register!??");
3446 Reg = FuncInfo.CreateRegForValue(PHIOp);
3447 UnorderedChains.push_back(
3448 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
3452 // Remember that this register needs to added to the machine PHI node as
3453 // the input for this MBB.
3454 MVT::ValueType VT = TLI.getValueType(PN->getType());
3455 unsigned NumElements;
3456 if (VT != MVT::Vector)
3457 NumElements = TLI.getNumElements(VT);
3459 MVT::ValueType VT1,VT2;
3461 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3464 for (unsigned i = 0, e = NumElements; i != e; ++i)
3465 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3468 ConstantsOut.clear();
3470 // Turn all of the unordered chains into one factored node.
3471 if (!UnorderedChains.empty()) {
3472 SDOperand Root = SDL.getRoot();
3473 if (Root.getOpcode() != ISD::EntryToken) {
3474 unsigned i = 0, e = UnorderedChains.size();
3475 for (; i != e; ++i) {
3476 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3477 if (UnorderedChains[i].Val->getOperand(0) == Root)
3478 break; // Don't add the root if we already indirectly depend on it.
3482 UnorderedChains.push_back(Root);
3484 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
3487 // Lower the terminator after the copies are emitted.
3488 SDL.visit(*LLVMBB->getTerminator());
3490 // Copy over any CaseBlock records that may now exist due to SwitchInst
3491 // lowering, as well as any jump table information.
3492 SwitchCases.clear();
3493 SwitchCases = SDL.SwitchCases;
3496 // Make sure the root of the DAG is up-to-date.
3497 DAG.setRoot(SDL.getRoot());
3500 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
3501 // Run the DAG combiner in pre-legalize mode.
3504 DEBUG(std::cerr << "Lowered selection DAG:\n");
3507 // Second step, hack on the DAG until it only uses operations and types that
3508 // the target supports.
3511 DEBUG(std::cerr << "Legalized selection DAG:\n");
3514 // Run the DAG combiner in post-legalize mode.
3517 if (ViewISelDAGs) DAG.viewGraph();
3519 // Third, instruction select all of the operations to machine code, adding the
3520 // code to the MachineBasicBlock.
3521 InstructionSelectBasicBlock(DAG);
3523 DEBUG(std::cerr << "Selected machine code:\n");
3527 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3528 FunctionLoweringInfo &FuncInfo) {
3529 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3531 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3534 // First step, lower LLVM code to some DAG. This DAG may use operations and
3535 // types that are not supported by the target.
3536 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3538 // Second step, emit the lowered DAG as machine code.
3539 CodeGenAndEmitDAG(DAG);
3542 // Next, now that we know what the last MBB the LLVM BB expanded is, update
3543 // PHI nodes in successors.
3544 if (SwitchCases.empty() && JT.Reg == 0) {
3545 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3546 MachineInstr *PHI = PHINodesToUpdate[i].first;
3547 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3548 "This is not a machine PHI node that we are updating!");
3549 PHI->addRegOperand(PHINodesToUpdate[i].second);
3550 PHI->addMachineBasicBlockOperand(BB);
3555 // If the JumpTable record is filled in, then we need to emit a jump table.
3556 // Updating the PHI nodes is tricky in this case, since we need to determine
3557 // whether the PHI is a successor of the range check MBB or the jump table MBB
3559 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3560 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3562 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3563 MachineBasicBlock *RangeBB = BB;
3564 // Set the current basic block to the mbb we wish to insert the code into
3566 SDL.setCurrentBasicBlock(BB);
3568 SDL.visitJumpTable(JT);
3569 SDAG.setRoot(SDL.getRoot());
3570 CodeGenAndEmitDAG(SDAG);
3572 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3573 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3574 MachineBasicBlock *PHIBB = PHI->getParent();
3575 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3576 "This is not a machine PHI node that we are updating!");
3577 if (PHIBB == JT.Default) {
3578 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3579 PHI->addMachineBasicBlockOperand(RangeBB);
3581 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
3582 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3583 PHI->addMachineBasicBlockOperand(BB);
3589 // If we generated any switch lowering information, build and codegen any
3590 // additional DAGs necessary.
3591 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
3592 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3594 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3595 // Set the current basic block to the mbb we wish to insert the code into
3596 BB = SwitchCases[i].ThisBB;
3597 SDL.setCurrentBasicBlock(BB);
3599 SDL.visitSwitchCase(SwitchCases[i]);
3600 SDAG.setRoot(SDL.getRoot());
3601 CodeGenAndEmitDAG(SDAG);
3602 // Iterate over the phi nodes, if there is a phi node in a successor of this
3603 // block (for instance, the default block), then add a pair of operands to
3604 // the phi node for this block, as if we were coming from the original
3605 // BB before switch expansion.
3606 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3607 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3608 MachineBasicBlock *PHIBB = PHI->getParent();
3609 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3610 "This is not a machine PHI node that we are updating!");
3611 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
3612 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3613 PHI->addMachineBasicBlockOperand(BB);
3619 //===----------------------------------------------------------------------===//
3620 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3621 /// target node in the graph.
3622 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3623 if (ViewSchedDAGs) DAG.viewGraph();
3624 ScheduleDAG *SL = NULL;
3626 switch (ISHeuristic) {
3627 default: assert(0 && "Unrecognized scheduling heuristic");
3628 case defaultScheduling:
3629 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
3630 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
3632 assert(TLI.getSchedulingPreference() ==
3633 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
3634 SL = createBURRListDAGScheduler(DAG, BB);
3638 SL = createBFS_DAGScheduler(DAG, BB);
3640 case simpleScheduling:
3641 SL = createSimpleDAGScheduler(false, DAG, BB);
3643 case simpleNoItinScheduling:
3644 SL = createSimpleDAGScheduler(true, DAG, BB);
3646 case listSchedulingBURR:
3647 SL = createBURRListDAGScheduler(DAG, BB);
3649 case listSchedulingTDRR:
3650 SL = createTDRRListDAGScheduler(DAG, BB);
3652 case listSchedulingTD:
3653 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
3660 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3661 return new HazardRecognizer();
3664 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3665 /// by tblgen. Others should not call it.
3666 void SelectionDAGISel::
3667 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3668 std::vector<SDOperand> InOps;
3669 std::swap(InOps, Ops);
3671 Ops.push_back(InOps[0]); // input chain.
3672 Ops.push_back(InOps[1]); // input asm string.
3674 unsigned i = 2, e = InOps.size();
3675 if (InOps[e-1].getValueType() == MVT::Flag)
3676 --e; // Don't process a flag operand if it is here.
3679 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3680 if ((Flags & 7) != 4 /*MEM*/) {
3681 // Just skip over this operand, copying the operands verbatim.
3682 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3683 i += (Flags >> 3) + 1;
3685 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3686 // Otherwise, this is a memory operand. Ask the target to select it.
3687 std::vector<SDOperand> SelOps;
3688 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3689 std::cerr << "Could not match memory address. Inline asm failure!\n";
3693 // Add this to the output node.
3694 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3695 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3700 // Add the flag input back if present.
3701 if (e != InOps.size())
3702 Ops.push_back(InOps.back());