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/ADT/BitVector.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/ParameterAttributes.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/SchedulerRegistry.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/SSARegMap.h"
37 #include "llvm/Target/MRegisterInfo.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Target/TargetFrameInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/Compiler.h"
52 ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
55 ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
58 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
61 //===---------------------------------------------------------------------===//
63 /// RegisterScheduler class - Track the registration of instruction schedulers.
65 //===---------------------------------------------------------------------===//
66 MachinePassRegistry RegisterScheduler::Registry;
68 //===---------------------------------------------------------------------===//
70 /// ISHeuristic command line option for instruction schedulers.
72 //===---------------------------------------------------------------------===//
74 cl::opt<RegisterScheduler::FunctionPassCtor, false,
75 RegisterPassParser<RegisterScheduler> >
77 cl::init(&createDefaultScheduler),
78 cl::desc("Instruction schedulers available:"));
80 static RegisterScheduler
81 defaultListDAGScheduler("default", " Best scheduler for the target",
82 createDefaultScheduler);
86 /// RegsForValue - This struct represents the physical registers that a
87 /// particular value is assigned and the type information about the value.
88 /// This is needed because values can be promoted into larger registers and
89 /// expanded into multiple smaller registers than the value.
90 struct VISIBILITY_HIDDEN RegsForValue {
91 /// Regs - This list hold the register (for legal and promoted values)
92 /// or register set (for expanded values) that the value should be assigned
94 std::vector<unsigned> Regs;
96 /// RegVT - The value type of each register.
100 /// ValueVT - The value type of the LLVM value, which may be promoted from
101 /// RegVT or made from merging the two expanded parts.
102 MVT::ValueType ValueVT;
104 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
107 : RegVT(regvt), ValueVT(valuevt) {
110 RegsForValue(const std::vector<unsigned> ®s,
111 MVT::ValueType regvt, MVT::ValueType valuevt)
112 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
116 /// this value and returns the result as a ValueVT value. This uses
117 /// Chain/Flag as the input and updates them for the output Chain/Flag.
118 SDOperand getCopyFromRegs(SelectionDAG &DAG,
119 SDOperand &Chain, SDOperand &Flag) const;
121 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
122 /// specified value into the registers specified by this object. This uses
123 /// Chain/Flag as the input and updates them for the output Chain/Flag.
124 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
125 SDOperand &Chain, SDOperand &Flag,
126 MVT::ValueType PtrVT) const;
128 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
129 /// operand list. This adds the code marker and includes the number of
130 /// values added into it.
131 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
132 std::vector<SDOperand> &Ops) const;
137 //===--------------------------------------------------------------------===//
138 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 MachineBasicBlock *BB) {
143 TargetLowering &TLI = IS->getTargetLowering();
145 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
146 return createTDListDAGScheduler(IS, DAG, BB);
148 assert(TLI.getSchedulingPreference() ==
149 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
150 return createBURRListDAGScheduler(IS, DAG, BB);
155 //===--------------------------------------------------------------------===//
156 /// FunctionLoweringInfo - This contains information that is global to a
157 /// function that is used when lowering a region of the function.
158 class FunctionLoweringInfo {
165 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
168 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170 /// ValueMap - Since we emit code for the function a basic block at a time,
171 /// we must remember which virtual registers hold the values for
172 /// cross-basic-block values.
173 DenseMap<const Value*, unsigned> ValueMap;
175 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
176 /// the entry block. This allows the allocas to be efficiently referenced
177 /// anywhere in the function.
178 std::map<const AllocaInst*, int> StaticAllocaMap;
180 unsigned MakeReg(MVT::ValueType VT) {
181 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
184 /// isExportedInst - Return true if the specified value is an instruction
185 /// exported from its block.
186 bool isExportedInst(const Value *V) {
187 return ValueMap.count(V);
190 unsigned CreateRegForValue(const Value *V);
192 unsigned InitializeRegForValue(const Value *V) {
193 unsigned &R = ValueMap[V];
194 assert(R == 0 && "Already initialized this value register!");
195 return R = CreateRegForValue(V);
200 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
201 /// PHI nodes or outside of the basic block that defines it, or used by a
202 /// switch instruction, which may expand to multiple basic blocks.
203 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
204 if (isa<PHINode>(I)) return true;
205 BasicBlock *BB = I->getParent();
206 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
207 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
208 // FIXME: Remove switchinst special case.
209 isa<SwitchInst>(*UI))
214 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
215 /// entry block, return true. This includes arguments used by switches, since
216 /// the switch may expand into multiple basic blocks.
217 static bool isOnlyUsedInEntryBlock(Argument *A) {
218 BasicBlock *Entry = A->getParent()->begin();
219 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
220 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
221 return false; // Use not in entry block.
225 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
226 Function &fn, MachineFunction &mf)
227 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229 // Create a vreg for each argument register that is not dead and is used
230 // outside of the entry block for the function.
231 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 if (!isOnlyUsedInEntryBlock(AI))
234 InitializeRegForValue(AI);
236 // Initialize the mapping of values to registers. This is only set up for
237 // instruction values that are used outside of the block that defines
239 Function::iterator BB = Fn.begin(), EB = Fn.end();
240 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
241 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
242 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
243 const Type *Ty = AI->getAllocatedType();
244 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
246 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
249 TySize *= CUI->getZExtValue(); // Get total allocated size.
250 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
251 StaticAllocaMap[AI] =
252 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
255 for (; BB != EB; ++BB)
256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
257 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
258 if (!isa<AllocaInst>(I) ||
259 !StaticAllocaMap.count(cast<AllocaInst>(I)))
260 InitializeRegForValue(I);
262 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
263 // also creates the initial PHI MachineInstrs, though none of the input
264 // operands are populated.
265 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
266 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
268 MF.getBasicBlockList().push_back(MBB);
270 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
273 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
274 if (PN->use_empty()) continue;
276 MVT::ValueType VT = TLI.getValueType(PN->getType());
277 unsigned NumElements;
278 if (VT != MVT::Vector)
279 NumElements = TLI.getNumElements(VT);
281 MVT::ValueType VT1,VT2;
283 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
286 unsigned PHIReg = ValueMap[PN];
287 assert(PHIReg && "PHI node does not have an assigned virtual register!");
288 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
289 for (unsigned i = 0; i != NumElements; ++i)
290 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
295 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
296 /// the correctly promoted or expanded types. Assign these registers
297 /// consecutive vreg numbers and return the first assigned number.
298 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
299 MVT::ValueType VT = TLI.getValueType(V->getType());
301 // The number of multiples of registers that we need, to, e.g., split up
302 // a <2 x int64> -> 4 x i32 registers.
303 unsigned NumVectorRegs = 1;
305 // If this is a vector type, figure out what type it will decompose into
306 // and how many of the elements it will use.
307 if (VT == MVT::Vector) {
308 const VectorType *PTy = cast<VectorType>(V->getType());
309 unsigned NumElts = PTy->getNumElements();
310 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
312 // Divide the input until we get to a supported size. This will always
313 // end with a scalar if the target doesn't support vectors.
314 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
321 VT = getVectorType(EltTy, NumElts);
324 // The common case is that we will only create one register for this
325 // value. If we have that case, create and return the virtual register.
326 unsigned NV = TLI.getNumElements(VT);
328 // If we are promoting this value, pick the next largest supported type.
329 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
330 unsigned Reg = MakeReg(PromotedType);
331 // If this is a vector of supported or promoted types (e.g. 4 x i16),
332 // create all of the registers.
333 for (unsigned i = 1; i != NumVectorRegs; ++i)
334 MakeReg(PromotedType);
338 // If this value is represented with multiple target registers, make sure
339 // to create enough consecutive registers of the right (smaller) type.
340 VT = TLI.getTypeToExpandTo(VT);
341 unsigned R = MakeReg(VT);
342 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
347 //===----------------------------------------------------------------------===//
348 /// SelectionDAGLowering - This is the common target-independent lowering
349 /// implementation that is parameterized by a TargetLowering object.
350 /// Also, targets can overload any lowering method.
353 class SelectionDAGLowering {
354 MachineBasicBlock *CurMBB;
356 DenseMap<const Value*, SDOperand> NodeMap;
358 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
359 /// them up and then emit token factor nodes when possible. This allows us to
360 /// get simple disambiguation between loads without worrying about alias
362 std::vector<SDOperand> PendingLoads;
364 /// Case - A struct to record the Value for a switch case, and the
365 /// case's target basic block.
369 MachineBasicBlock* BB;
371 Case() : Low(0), High(0), BB(0) { }
372 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
373 Low(low), High(high), BB(bb) { }
374 uint64_t size() const {
375 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
376 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
377 return (rHigh - rLow + 1ULL);
383 MachineBasicBlock* BB;
386 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
387 Mask(mask), BB(bb), Bits(bits) { }
390 typedef std::vector<Case> CaseVector;
391 typedef std::vector<CaseBits> CaseBitsVector;
392 typedef CaseVector::iterator CaseItr;
393 typedef std::pair<CaseItr, CaseItr> CaseRange;
395 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
396 /// of conditional branches.
398 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
399 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
401 /// CaseBB - The MBB in which to emit the compare and branch
402 MachineBasicBlock *CaseBB;
403 /// LT, GE - If nonzero, we know the current case value must be less-than or
404 /// greater-than-or-equal-to these Constants.
407 /// Range - A pair of iterators representing the range of case values to be
408 /// processed at this point in the binary search tree.
412 typedef std::vector<CaseRec> CaseRecVector;
414 /// The comparison function for sorting the switch case values in the vector.
415 /// WARNING: Case ranges should be disjoint!
417 bool operator () (const Case& C1, const Case& C2) {
418 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
419 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
420 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
421 return CI1->getValue().slt(CI2->getValue());
426 bool operator () (const CaseBits& C1, const CaseBits& C2) {
427 return C1.Bits > C2.Bits;
431 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
434 // TLI - This is information that describes the available target features we
435 // need for lowering. This indicates when operations are unavailable,
436 // implemented with a libcall, etc.
439 const TargetData *TD;
441 /// SwitchCases - Vector of CaseBlock structures used to communicate
442 /// SwitchInst code generation information.
443 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
444 /// JTCases - Vector of JumpTable structures used to communicate
445 /// SwitchInst code generation information.
446 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
447 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
449 /// FuncInfo - Information about the function as a whole.
451 FunctionLoweringInfo &FuncInfo;
453 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
454 FunctionLoweringInfo &funcinfo)
455 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
459 /// getRoot - Return the current virtual root of the Selection DAG.
461 SDOperand getRoot() {
462 if (PendingLoads.empty())
463 return DAG.getRoot();
465 if (PendingLoads.size() == 1) {
466 SDOperand Root = PendingLoads[0];
468 PendingLoads.clear();
472 // Otherwise, we have to make a token factor node.
473 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
474 &PendingLoads[0], PendingLoads.size());
475 PendingLoads.clear();
480 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
482 void visit(Instruction &I) { visit(I.getOpcode(), I); }
484 void visit(unsigned Opcode, User &I) {
485 // Note: this doesn't use InstVisitor, because it has to work with
486 // ConstantExpr's in addition to instructions.
488 default: assert(0 && "Unknown instruction type encountered!");
490 // Build the switch statement using the Instruction.def file.
491 #define HANDLE_INST(NUM, OPCODE, CLASS) \
492 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
493 #include "llvm/Instruction.def"
497 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
499 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
500 const Value *SV, SDOperand Root,
503 SDOperand getIntPtrConstant(uint64_t Val) {
504 return DAG.getConstant(Val, TLI.getPointerTy());
507 SDOperand getValue(const Value *V);
509 void setValue(const Value *V, SDOperand NewN) {
510 SDOperand &N = NodeMap[V];
511 assert(N.Val == 0 && "Already set a value for this node!");
515 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
517 bool OutReg, bool InReg,
518 std::set<unsigned> &OutputRegs,
519 std::set<unsigned> &InputRegs);
521 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
522 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
524 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
525 void ExportFromCurrentBlock(Value *V);
526 void LowerCallTo(Instruction &I,
527 const Type *CalledValueTy, unsigned CallingConv,
528 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
530 // Terminator instructions.
531 void visitRet(ReturnInst &I);
532 void visitBr(BranchInst &I);
533 void visitSwitch(SwitchInst &I);
534 void visitUnreachable(UnreachableInst &I) { /* noop */ }
536 // Helpers for visitSwitch
537 bool handleSmallSwitchRange(CaseRec& CR,
538 CaseRecVector& WorkList,
540 MachineBasicBlock* Default);
541 bool handleJTSwitchCase(CaseRec& CR,
542 CaseRecVector& WorkList,
544 MachineBasicBlock* Default);
545 bool handleBTSplitSwitchCase(CaseRec& CR,
546 CaseRecVector& WorkList,
548 MachineBasicBlock* Default);
549 bool handleBitTestsSwitchCase(CaseRec& CR,
550 CaseRecVector& WorkList,
552 MachineBasicBlock* Default);
553 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
554 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
555 void visitBitTestCase(MachineBasicBlock* NextMBB,
557 SelectionDAGISel::BitTestCase &B);
558 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
559 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
560 SelectionDAGISel::JumpTableHeader &JTH);
562 // These all get lowered before this pass.
563 void visitInvoke(InvokeInst &I);
564 void visitInvoke(InvokeInst &I, bool AsTerminator);
565 void visitUnwind(UnwindInst &I);
567 void visitScalarBinary(User &I, unsigned OpCode);
568 void visitVectorBinary(User &I, unsigned OpCode);
569 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
570 void visitShift(User &I, unsigned Opcode);
571 void visitAdd(User &I) {
572 if (isa<VectorType>(I.getType()))
573 visitVectorBinary(I, ISD::VADD);
574 else if (I.getType()->isFloatingPoint())
575 visitScalarBinary(I, ISD::FADD);
577 visitScalarBinary(I, ISD::ADD);
579 void visitSub(User &I);
580 void visitMul(User &I) {
581 if (isa<VectorType>(I.getType()))
582 visitVectorBinary(I, ISD::VMUL);
583 else if (I.getType()->isFloatingPoint())
584 visitScalarBinary(I, ISD::FMUL);
586 visitScalarBinary(I, ISD::MUL);
588 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
589 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
590 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
591 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
592 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
593 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
594 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
595 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
596 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
597 void visitShl (User &I) { visitShift(I, ISD::SHL); }
598 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
599 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
600 void visitICmp(User &I);
601 void visitFCmp(User &I);
602 // Visit the conversion instructions
603 void visitTrunc(User &I);
604 void visitZExt(User &I);
605 void visitSExt(User &I);
606 void visitFPTrunc(User &I);
607 void visitFPExt(User &I);
608 void visitFPToUI(User &I);
609 void visitFPToSI(User &I);
610 void visitUIToFP(User &I);
611 void visitSIToFP(User &I);
612 void visitPtrToInt(User &I);
613 void visitIntToPtr(User &I);
614 void visitBitCast(User &I);
616 void visitExtractElement(User &I);
617 void visitInsertElement(User &I);
618 void visitShuffleVector(User &I);
620 void visitGetElementPtr(User &I);
621 void visitSelect(User &I);
623 void visitMalloc(MallocInst &I);
624 void visitFree(FreeInst &I);
625 void visitAlloca(AllocaInst &I);
626 void visitLoad(LoadInst &I);
627 void visitStore(StoreInst &I);
628 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
629 void visitCall(CallInst &I);
630 void visitInlineAsm(CallInst &I);
631 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
632 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
634 void visitVAStart(CallInst &I);
635 void visitVAArg(VAArgInst &I);
636 void visitVAEnd(CallInst &I);
637 void visitVACopy(CallInst &I);
639 void visitMemIntrinsic(CallInst &I, unsigned Op);
641 void visitUserOp1(Instruction &I) {
642 assert(0 && "UserOp1 should not exist at instruction selection time!");
645 void visitUserOp2(Instruction &I) {
646 assert(0 && "UserOp2 should not exist at instruction selection time!");
650 } // end namespace llvm
652 SDOperand SelectionDAGLowering::getValue(const Value *V) {
653 SDOperand &N = NodeMap[V];
656 const Type *VTy = V->getType();
657 MVT::ValueType VT = TLI.getValueType(VTy);
658 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
659 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
660 visit(CE->getOpcode(), *CE);
661 SDOperand N1 = NodeMap[V];
662 assert(N1.Val && "visit didn't populate the ValueMap!");
664 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
665 return N = DAG.getGlobalAddress(GV, VT);
666 } else if (isa<ConstantPointerNull>(C)) {
667 return N = DAG.getConstant(0, TLI.getPointerTy());
668 } else if (isa<UndefValue>(C)) {
669 if (!isa<VectorType>(VTy))
670 return N = DAG.getNode(ISD::UNDEF, VT);
672 // Create a VBUILD_VECTOR of undef nodes.
673 const VectorType *PTy = cast<VectorType>(VTy);
674 unsigned NumElements = PTy->getNumElements();
675 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
677 SmallVector<SDOperand, 8> Ops;
678 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
680 // Create a VConstant node with generic Vector type.
681 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
682 Ops.push_back(DAG.getValueType(PVT));
683 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
684 &Ops[0], Ops.size());
685 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
686 return N = DAG.getConstantFP(CFP->getValue(), VT);
687 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
688 unsigned NumElements = PTy->getNumElements();
689 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
691 // Now that we know the number and type of the elements, push a
692 // Constant or ConstantFP node onto the ops list for each element of
693 // the packed constant.
694 SmallVector<SDOperand, 8> Ops;
695 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
696 for (unsigned i = 0; i != NumElements; ++i)
697 Ops.push_back(getValue(CP->getOperand(i)));
699 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
701 if (MVT::isFloatingPoint(PVT))
702 Op = DAG.getConstantFP(0, PVT);
704 Op = DAG.getConstant(0, PVT);
705 Ops.assign(NumElements, Op);
708 // Create a VBUILD_VECTOR node with generic Vector type.
709 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
710 Ops.push_back(DAG.getValueType(PVT));
711 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
714 // Canonicalize all constant ints to be unsigned.
715 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
719 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
720 std::map<const AllocaInst*, int>::iterator SI =
721 FuncInfo.StaticAllocaMap.find(AI);
722 if (SI != FuncInfo.StaticAllocaMap.end())
723 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
726 unsigned InReg = FuncInfo.ValueMap[V];
727 assert(InReg && "Value not in map!");
729 // If this type is not legal, make it so now.
730 if (VT != MVT::Vector) {
731 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
732 // Source must be expanded. This input value is actually coming from the
733 // register pair InReg and InReg+1.
734 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
735 unsigned NumVals = TLI.getNumElements(VT);
736 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
738 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
740 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
741 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
742 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
745 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
746 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
747 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
748 N = MVT::isFloatingPoint(VT)
749 ? DAG.getNode(ISD::FP_ROUND, VT, N)
750 : DAG.getNode(ISD::TRUNCATE, VT, N);
753 // Otherwise, if this is a vector, make it available as a generic vector
755 MVT::ValueType PTyElementVT, PTyLegalElementVT;
756 const VectorType *PTy = cast<VectorType>(VTy);
757 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
760 // Build a VBUILD_VECTOR with the input registers.
761 SmallVector<SDOperand, 8> Ops;
762 if (PTyElementVT == PTyLegalElementVT) {
763 // If the value types are legal, just VBUILD the CopyFromReg nodes.
764 for (unsigned i = 0; i != NE; ++i)
765 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
767 } else if (PTyElementVT < PTyLegalElementVT) {
768 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
769 for (unsigned i = 0; i != NE; ++i) {
770 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
772 if (MVT::isFloatingPoint(PTyElementVT))
773 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
775 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
779 // If the register was expanded, use BUILD_PAIR.
780 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
781 for (unsigned i = 0; i != NE/2; ++i) {
782 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
784 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
786 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
790 Ops.push_back(DAG.getConstant(NE, MVT::i32));
791 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
792 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
794 // Finally, use a VBIT_CONVERT to make this available as the appropriate
796 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
797 DAG.getConstant(PTy->getNumElements(),
799 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
806 void SelectionDAGLowering::visitRet(ReturnInst &I) {
807 if (I.getNumOperands() == 0) {
808 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
811 SmallVector<SDOperand, 8> NewValues;
812 NewValues.push_back(getRoot());
813 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
814 SDOperand RetOp = getValue(I.getOperand(i));
816 // If this is an integer return value, we need to promote it ourselves to
817 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
819 // FIXME: C calling convention requires the return type to be promoted to
820 // at least 32-bit. But this is not necessary for non-C calling conventions.
821 if (MVT::isInteger(RetOp.getValueType()) &&
822 RetOp.getValueType() < MVT::i64) {
823 MVT::ValueType TmpVT;
824 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
825 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
828 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
829 const ParamAttrsList *Attrs = FTy->getParamAttrs();
830 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
831 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
832 ExtendKind = ISD::SIGN_EXTEND;
833 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
834 ExtendKind = ISD::ZERO_EXTEND;
835 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
837 NewValues.push_back(RetOp);
838 NewValues.push_back(DAG.getConstant(false, MVT::i32));
840 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
841 &NewValues[0], NewValues.size()));
844 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
845 /// the current basic block, add it to ValueMap now so that we'll get a
847 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
848 // No need to export constants.
849 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
852 if (FuncInfo.isExportedInst(V)) return;
854 unsigned Reg = FuncInfo.InitializeRegForValue(V);
855 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
858 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
859 const BasicBlock *FromBB) {
860 // The operands of the setcc have to be in this block. We don't know
861 // how to export them from some other block.
862 if (Instruction *VI = dyn_cast<Instruction>(V)) {
863 // Can export from current BB.
864 if (VI->getParent() == FromBB)
867 // Is already exported, noop.
868 return FuncInfo.isExportedInst(V);
871 // If this is an argument, we can export it if the BB is the entry block or
872 // if it is already exported.
873 if (isa<Argument>(V)) {
874 if (FromBB == &FromBB->getParent()->getEntryBlock())
877 // Otherwise, can only export this if it is already exported.
878 return FuncInfo.isExportedInst(V);
881 // Otherwise, constants can always be exported.
885 static bool InBlock(const Value *V, const BasicBlock *BB) {
886 if (const Instruction *I = dyn_cast<Instruction>(V))
887 return I->getParent() == BB;
891 /// FindMergedConditions - If Cond is an expression like
892 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
893 MachineBasicBlock *TBB,
894 MachineBasicBlock *FBB,
895 MachineBasicBlock *CurBB,
897 // If this node is not part of the or/and tree, emit it as a branch.
898 Instruction *BOp = dyn_cast<Instruction>(Cond);
900 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
901 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
902 BOp->getParent() != CurBB->getBasicBlock() ||
903 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
904 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
905 const BasicBlock *BB = CurBB->getBasicBlock();
907 // If the leaf of the tree is a comparison, merge the condition into
909 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
910 // The operands of the cmp have to be in this block. We don't know
911 // how to export them from some other block. If this is the first block
912 // of the sequence, no exporting is needed.
914 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
915 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
916 BOp = cast<Instruction>(Cond);
917 ISD::CondCode Condition;
918 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
919 switch (IC->getPredicate()) {
920 default: assert(0 && "Unknown icmp predicate opcode!");
921 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
922 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
923 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
924 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
925 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
926 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
927 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
928 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
929 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
930 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
932 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
933 ISD::CondCode FPC, FOC;
934 switch (FC->getPredicate()) {
935 default: assert(0 && "Unknown fcmp predicate opcode!");
936 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
937 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
938 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
939 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
940 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
941 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
942 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
943 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
944 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
945 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
946 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
947 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
948 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
949 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
950 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
951 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
953 if (FiniteOnlyFPMath())
958 Condition = ISD::SETEQ; // silence warning.
959 assert(0 && "Unknown compare instruction");
962 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
963 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
964 SwitchCases.push_back(CB);
968 // Create a CaseBlock record representing this branch.
969 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
970 NULL, TBB, FBB, CurBB);
971 SwitchCases.push_back(CB);
976 // Create TmpBB after CurBB.
977 MachineFunction::iterator BBI = CurBB;
978 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
979 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
981 if (Opc == Instruction::Or) {
990 // Emit the LHS condition.
991 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
993 // Emit the RHS condition into TmpBB.
994 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
996 assert(Opc == Instruction::And && "Unknown merge op!");
1004 // This requires creation of TmpBB after CurBB.
1006 // Emit the LHS condition.
1007 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1009 // Emit the RHS condition into TmpBB.
1010 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1014 /// If the set of cases should be emitted as a series of branches, return true.
1015 /// If we should emit this as a bunch of and/or'd together conditions, return
1018 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1019 if (Cases.size() != 2) return true;
1021 // If this is two comparisons of the same values or'd or and'd together, they
1022 // will get folded into a single comparison, so don't emit two blocks.
1023 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1024 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1025 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1026 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1033 void SelectionDAGLowering::visitBr(BranchInst &I) {
1034 // Update machine-CFG edges.
1035 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1037 // Figure out which block is immediately after the current one.
1038 MachineBasicBlock *NextBlock = 0;
1039 MachineFunction::iterator BBI = CurMBB;
1040 if (++BBI != CurMBB->getParent()->end())
1043 if (I.isUnconditional()) {
1044 // If this is not a fall-through branch, emit the branch.
1045 if (Succ0MBB != NextBlock)
1046 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1047 DAG.getBasicBlock(Succ0MBB)));
1049 // Update machine-CFG edges.
1050 CurMBB->addSuccessor(Succ0MBB);
1055 // If this condition is one of the special cases we handle, do special stuff
1057 Value *CondVal = I.getCondition();
1058 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1060 // If this is a series of conditions that are or'd or and'd together, emit
1061 // this as a sequence of branches instead of setcc's with and/or operations.
1062 // For example, instead of something like:
1075 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1076 if (BOp->hasOneUse() &&
1077 (BOp->getOpcode() == Instruction::And ||
1078 BOp->getOpcode() == Instruction::Or)) {
1079 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1080 // If the compares in later blocks need to use values not currently
1081 // exported from this block, export them now. This block should always
1082 // be the first entry.
1083 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1085 // Allow some cases to be rejected.
1086 if (ShouldEmitAsBranches(SwitchCases)) {
1087 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1088 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1089 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1092 // Emit the branch for this block.
1093 visitSwitchCase(SwitchCases[0]);
1094 SwitchCases.erase(SwitchCases.begin());
1098 // Okay, we decided not to do this, remove any inserted MBB's and clear
1100 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1101 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1103 SwitchCases.clear();
1107 // Create a CaseBlock record representing this branch.
1108 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1109 NULL, Succ0MBB, Succ1MBB, CurMBB);
1110 // Use visitSwitchCase to actually insert the fast branch sequence for this
1112 visitSwitchCase(CB);
1115 /// visitSwitchCase - Emits the necessary code to represent a single node in
1116 /// the binary search tree resulting from lowering a switch instruction.
1117 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1119 SDOperand CondLHS = getValue(CB.CmpLHS);
1121 // Build the setcc now.
1122 if (CB.CmpMHS == NULL) {
1123 // Fold "(X == true)" to X and "(X == false)" to !X to
1124 // handle common cases produced by branch lowering.
1125 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1127 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1128 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1129 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1131 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1133 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1135 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1136 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1138 SDOperand CmpOp = getValue(CB.CmpMHS);
1139 MVT::ValueType VT = CmpOp.getValueType();
1141 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1142 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1144 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1145 Cond = DAG.getSetCC(MVT::i1, SUB,
1146 DAG.getConstant(High-Low, VT), ISD::SETULE);
1151 // Set NextBlock to be the MBB immediately after the current one, if any.
1152 // This is used to avoid emitting unnecessary branches to the next block.
1153 MachineBasicBlock *NextBlock = 0;
1154 MachineFunction::iterator BBI = CurMBB;
1155 if (++BBI != CurMBB->getParent()->end())
1158 // If the lhs block is the next block, invert the condition so that we can
1159 // fall through to the lhs instead of the rhs block.
1160 if (CB.TrueBB == NextBlock) {
1161 std::swap(CB.TrueBB, CB.FalseBB);
1162 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1163 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1165 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1166 DAG.getBasicBlock(CB.TrueBB));
1167 if (CB.FalseBB == NextBlock)
1168 DAG.setRoot(BrCond);
1170 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1171 DAG.getBasicBlock(CB.FalseBB)));
1172 // Update successor info
1173 CurMBB->addSuccessor(CB.TrueBB);
1174 CurMBB->addSuccessor(CB.FalseBB);
1177 /// visitJumpTable - Emit JumpTable node in the current MBB
1178 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1179 // Emit the code for the jump table
1180 assert(JT.Reg != -1UL && "Should lower JT Header first!");
1181 MVT::ValueType PTy = TLI.getPointerTy();
1182 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1183 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1184 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1189 /// visitJumpTableHeader - This function emits necessary code to produce index
1190 /// in the JumpTable from switch case.
1191 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1192 SelectionDAGISel::JumpTableHeader &JTH) {
1193 // Subtract the lowest switch case value from the value being switched on
1194 // and conditional branch to default mbb if the result is greater than the
1195 // difference between smallest and largest cases.
1196 SDOperand SwitchOp = getValue(JTH.SValue);
1197 MVT::ValueType VT = SwitchOp.getValueType();
1198 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1199 DAG.getConstant(JTH.First, VT));
1201 // The SDNode we just created, which holds the value being switched on
1202 // minus the the smallest case value, needs to be copied to a virtual
1203 // register so it can be used as an index into the jump table in a
1204 // subsequent basic block. This value may be smaller or larger than the
1205 // target's pointer type, and therefore require extension or truncating.
1206 if (VT > TLI.getPointerTy())
1207 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1209 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1211 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1212 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1213 JT.Reg = JumpTableReg;
1215 // Emit the range check for the jump table, and branch to the default
1216 // block for the switch statement if the value being switched on exceeds
1217 // the largest case in the switch.
1218 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1219 DAG.getConstant(JTH.Last-JTH.First,VT),
1222 // Set NextBlock to be the MBB immediately after the current one, if any.
1223 // This is used to avoid emitting unnecessary branches to the next block.
1224 MachineBasicBlock *NextBlock = 0;
1225 MachineFunction::iterator BBI = CurMBB;
1226 if (++BBI != CurMBB->getParent()->end())
1229 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1230 DAG.getBasicBlock(JT.Default));
1232 if (JT.MBB == NextBlock)
1233 DAG.setRoot(BrCond);
1235 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1236 DAG.getBasicBlock(JT.MBB)));
1241 /// visitBitTestHeader - This function emits necessary code to produce value
1242 /// suitable for "bit tests"
1243 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1244 // Subtract the minimum value
1245 SDOperand SwitchOp = getValue(B.SValue);
1246 MVT::ValueType VT = SwitchOp.getValueType();
1247 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1248 DAG.getConstant(B.First, VT));
1251 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1252 DAG.getConstant(B.Range, VT),
1256 if (VT > TLI.getShiftAmountTy())
1257 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1259 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1261 // Make desired shift
1262 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1263 DAG.getConstant(1, TLI.getPointerTy()),
1266 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1267 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1270 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1271 DAG.getBasicBlock(B.Default));
1273 // Set NextBlock to be the MBB immediately after the current one, if any.
1274 // This is used to avoid emitting unnecessary branches to the next block.
1275 MachineBasicBlock *NextBlock = 0;
1276 MachineFunction::iterator BBI = CurMBB;
1277 if (++BBI != CurMBB->getParent()->end())
1280 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1281 if (MBB == NextBlock)
1282 DAG.setRoot(BrRange);
1284 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1285 DAG.getBasicBlock(MBB)));
1287 CurMBB->addSuccessor(B.Default);
1288 CurMBB->addSuccessor(MBB);
1293 /// visitBitTestCase - this function produces one "bit test"
1294 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1296 SelectionDAGISel::BitTestCase &B) {
1297 // Emit bit tests and jumps
1298 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1300 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1302 DAG.getConstant(B.Mask,
1303 TLI.getPointerTy()));
1304 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1305 DAG.getConstant(0, TLI.getPointerTy()),
1307 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1308 AndCmp, DAG.getBasicBlock(B.TargetBB));
1310 // Set NextBlock to be the MBB immediately after the current one, if any.
1311 // This is used to avoid emitting unnecessary branches to the next block.
1312 MachineBasicBlock *NextBlock = 0;
1313 MachineFunction::iterator BBI = CurMBB;
1314 if (++BBI != CurMBB->getParent()->end())
1317 if (NextMBB == NextBlock)
1320 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1321 DAG.getBasicBlock(NextMBB)));
1323 CurMBB->addSuccessor(B.TargetBB);
1324 CurMBB->addSuccessor(NextMBB);
1329 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1330 assert(0 && "Should never be visited directly");
1332 void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
1333 // Retrieve successors.
1334 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1335 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1337 if (!AsTerminator) {
1338 // Mark landing pad so that it doesn't get deleted in branch folding.
1339 LandingPad->setIsLandingPad();
1341 // Insert a label before the invoke call to mark the try range.
1342 // This can be used to detect deletion of the invoke via the
1343 // MachineModuleInfo.
1344 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1345 unsigned BeginLabel = MMI->NextLabelID();
1346 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1347 DAG.getConstant(BeginLabel, MVT::i32)));
1349 LowerCallTo(I, I.getCalledValue()->getType(),
1352 getValue(I.getOperand(0)),
1355 // Insert a label before the invoke call to mark the try range.
1356 // This can be used to detect deletion of the invoke via the
1357 // MachineModuleInfo.
1358 unsigned EndLabel = MMI->NextLabelID();
1359 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1360 DAG.getConstant(EndLabel, MVT::i32)));
1362 // Inform MachineModuleInfo of range.
1363 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1365 // Update successor info
1366 CurMBB->addSuccessor(Return);
1367 CurMBB->addSuccessor(LandingPad);
1369 // Drop into normal successor.
1370 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1371 DAG.getBasicBlock(Return)));
1375 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1378 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1379 /// small case ranges).
1380 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1381 CaseRecVector& WorkList,
1383 MachineBasicBlock* Default) {
1384 Case& BackCase = *(CR.Range.second-1);
1386 // Size is the number of Cases represented by this range.
1387 unsigned Size = CR.Range.second - CR.Range.first;
1391 // Get the MachineFunction which holds the current MBB. This is used when
1392 // inserting any additional MBBs necessary to represent the switch.
1393 MachineFunction *CurMF = CurMBB->getParent();
1395 // Figure out which block is immediately after the current one.
1396 MachineBasicBlock *NextBlock = 0;
1397 MachineFunction::iterator BBI = CR.CaseBB;
1399 if (++BBI != CurMBB->getParent()->end())
1402 // TODO: If any two of the cases has the same destination, and if one value
1403 // is the same as the other, but has one bit unset that the other has set,
1404 // use bit manipulation to do two compares at once. For example:
1405 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1407 // Rearrange the case blocks so that the last one falls through if possible.
1408 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1409 // The last case block won't fall through into 'NextBlock' if we emit the
1410 // branches in this order. See if rearranging a case value would help.
1411 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1412 if (I->BB == NextBlock) {
1413 std::swap(*I, BackCase);
1419 // Create a CaseBlock record representing a conditional branch to
1420 // the Case's target mbb if the value being switched on SV is equal
1422 MachineBasicBlock *CurBlock = CR.CaseBB;
1423 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1424 MachineBasicBlock *FallThrough;
1426 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1427 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1429 // If the last case doesn't match, go to the default block.
1430 FallThrough = Default;
1433 Value *RHS, *LHS, *MHS;
1435 if (I->High == I->Low) {
1436 // This is just small small case range :) containing exactly 1 case
1438 LHS = SV; RHS = I->High; MHS = NULL;
1441 LHS = I->Low; MHS = SV; RHS = I->High;
1443 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1444 I->BB, FallThrough, CurBlock);
1446 // If emitting the first comparison, just call visitSwitchCase to emit the
1447 // code into the current block. Otherwise, push the CaseBlock onto the
1448 // vector to be later processed by SDISel, and insert the node's MBB
1449 // before the next MBB.
1450 if (CurBlock == CurMBB)
1451 visitSwitchCase(CB);
1453 SwitchCases.push_back(CB);
1455 CurBlock = FallThrough;
1461 /// handleJTSwitchCase - Emit jumptable for current switch case range
1462 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1463 CaseRecVector& WorkList,
1465 MachineBasicBlock* Default) {
1466 Case& FrontCase = *CR.Range.first;
1467 Case& BackCase = *(CR.Range.second-1);
1469 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1470 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1473 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1477 if ((!TLI.isOperationLegal(ISD::BR_JT, MVT::Other) &&
1478 !TLI.isOperationLegal(ISD::BRIND, MVT::Other)) ||
1482 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1486 DOUT << "Lowering jump table\n"
1487 << "First entry: " << First << ". Last entry: " << Last << "\n"
1488 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1490 // Get the MachineFunction which holds the current MBB. This is used when
1491 // inserting any additional MBBs necessary to represent the switch.
1492 MachineFunction *CurMF = CurMBB->getParent();
1494 // Figure out which block is immediately after the current one.
1495 MachineBasicBlock *NextBlock = 0;
1496 MachineFunction::iterator BBI = CR.CaseBB;
1498 if (++BBI != CurMBB->getParent()->end())
1501 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1503 // Create a new basic block to hold the code for loading the address
1504 // of the jump table, and jumping to it. Update successor information;
1505 // we will either branch to the default case for the switch, or the jump
1507 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1508 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1509 CR.CaseBB->addSuccessor(Default);
1510 CR.CaseBB->addSuccessor(JumpTableBB);
1512 // Build a vector of destination BBs, corresponding to each target
1513 // of the jump table. If the value of the jump table slot corresponds to
1514 // a case statement, push the case's BB onto the vector, otherwise, push
1516 std::vector<MachineBasicBlock*> DestBBs;
1517 int64_t TEI = First;
1518 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1519 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1520 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1522 if ((Low <= TEI) && (TEI <= High)) {
1523 DestBBs.push_back(I->BB);
1527 DestBBs.push_back(Default);
1531 // Update successor info. Add one edge to each unique successor.
1532 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1533 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1534 E = DestBBs.end(); I != E; ++I) {
1535 if (!SuccsHandled[(*I)->getNumber()]) {
1536 SuccsHandled[(*I)->getNumber()] = true;
1537 JumpTableBB->addSuccessor(*I);
1541 // Create a jump table index for this jump table, or return an existing
1543 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1545 // Set the jump table information so that we can codegen it as a second
1546 // MachineBasicBlock
1547 SelectionDAGISel::JumpTable JT(-1UL, JTI, JumpTableBB, Default);
1548 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1549 (CR.CaseBB == CurMBB));
1550 if (CR.CaseBB == CurMBB)
1551 visitJumpTableHeader(JT, JTH);
1553 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1558 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1560 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1561 CaseRecVector& WorkList,
1563 MachineBasicBlock* Default) {
1564 // Get the MachineFunction which holds the current MBB. This is used when
1565 // inserting any additional MBBs necessary to represent the switch.
1566 MachineFunction *CurMF = CurMBB->getParent();
1568 // Figure out which block is immediately after the current one.
1569 MachineBasicBlock *NextBlock = 0;
1570 MachineFunction::iterator BBI = CR.CaseBB;
1572 if (++BBI != CurMBB->getParent()->end())
1575 Case& FrontCase = *CR.Range.first;
1576 Case& BackCase = *(CR.Range.second-1);
1577 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1579 // Size is the number of Cases represented by this range.
1580 unsigned Size = CR.Range.second - CR.Range.first;
1582 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1583 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1585 CaseItr Pivot = CR.Range.first + Size/2;
1587 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1588 // (heuristically) allow us to emit JumpTable's later.
1590 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1594 uint64_t LSize = FrontCase.size();
1595 uint64_t RSize = TSize-LSize;
1596 DOUT << "Selecting best pivot: \n"
1597 << "First: " << First << ", Last: " << Last <<"\n"
1598 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1599 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1601 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1602 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1603 assert((RBegin-LEnd>=1) && "Invalid case distance");
1604 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1605 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1606 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1607 // Should always split in some non-trivial place
1609 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1610 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1611 << "Metric: " << Metric << "\n";
1612 if (FMetric < Metric) {
1615 DOUT << "Current metric set to: " << FMetric << "\n";
1621 // If our case is dense we *really* should handle it earlier!
1622 assert((FMetric > 0) && "Should handle dense range earlier!");
1624 CaseRange LHSR(CR.Range.first, Pivot);
1625 CaseRange RHSR(Pivot, CR.Range.second);
1626 Constant *C = Pivot->Low;
1627 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1629 // We know that we branch to the LHS if the Value being switched on is
1630 // less than the Pivot value, C. We use this to optimize our binary
1631 // tree a bit, by recognizing that if SV is greater than or equal to the
1632 // LHS's Case Value, and that Case Value is exactly one less than the
1633 // Pivot's Value, then we can branch directly to the LHS's Target,
1634 // rather than creating a leaf node for it.
1635 if ((LHSR.second - LHSR.first) == 1 &&
1636 LHSR.first->High == CR.GE &&
1637 cast<ConstantInt>(C)->getSExtValue() ==
1638 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1639 TrueBB = LHSR.first->BB;
1641 TrueBB = new MachineBasicBlock(LLVMBB);
1642 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1643 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1646 // Similar to the optimization above, if the Value being switched on is
1647 // known to be less than the Constant CR.LT, and the current Case Value
1648 // is CR.LT - 1, then we can branch directly to the target block for
1649 // the current Case Value, rather than emitting a RHS leaf node for it.
1650 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1651 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1652 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1653 FalseBB = RHSR.first->BB;
1655 FalseBB = new MachineBasicBlock(LLVMBB);
1656 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1657 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1660 // Create a CaseBlock record representing a conditional branch to
1661 // the LHS node if the value being switched on SV is less than C.
1662 // Otherwise, branch to LHS.
1663 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1664 TrueBB, FalseBB, CR.CaseBB);
1666 if (CR.CaseBB == CurMBB)
1667 visitSwitchCase(CB);
1669 SwitchCases.push_back(CB);
1674 /// handleBitTestsSwitchCase - if current case range has few destination and
1675 /// range span less, than machine word bitwidth, encode case range into series
1676 /// of masks and emit bit tests with these masks.
1677 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1678 CaseRecVector& WorkList,
1680 MachineBasicBlock* Default) {
1681 unsigned IntPtrBits = getSizeInBits(TLI.getPointerTy());
1683 Case& FrontCase = *CR.Range.first;
1684 Case& BackCase = *(CR.Range.second-1);
1686 // Get the MachineFunction which holds the current MBB. This is used when
1687 // inserting any additional MBBs necessary to represent the switch.
1688 MachineFunction *CurMF = CurMBB->getParent();
1690 unsigned numCmps = 0;
1691 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1693 // Single case counts one, case range - two.
1694 if (I->Low == I->High)
1700 // Count unique destinations
1701 SmallSet<MachineBasicBlock*, 4> Dests;
1702 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1703 Dests.insert(I->BB);
1704 if (Dests.size() > 3)
1705 // Don't bother the code below, if there are too much unique destinations
1708 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1709 << "Total number of comparisons: " << numCmps << "\n";
1711 // Compute span of values.
1712 Constant* minValue = FrontCase.Low;
1713 Constant* maxValue = BackCase.High;
1714 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1715 cast<ConstantInt>(minValue)->getSExtValue();
1716 DOUT << "Compare range: " << range << "\n"
1717 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1718 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1720 if (range>IntPtrBits ||
1721 (!(Dests.size() == 1 && numCmps >= 3) &&
1722 !(Dests.size() == 2 && numCmps >= 5) &&
1723 !(Dests.size() >= 3 && numCmps >= 6)))
1726 DOUT << "Emitting bit tests\n";
1727 int64_t lowBound = 0;
1729 // Optimize the case where all the case values fit in a
1730 // word without having to subtract minValue. In this case,
1731 // we can optimize away the subtraction.
1732 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1733 cast<ConstantInt>(maxValue)->getSExtValue() <= IntPtrBits) {
1734 range = cast<ConstantInt>(maxValue)->getSExtValue();
1736 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1739 CaseBitsVector CasesBits;
1740 unsigned i, count = 0;
1742 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1743 MachineBasicBlock* Dest = I->BB;
1744 for (i = 0; i < count; ++i)
1745 if (Dest == CasesBits[i].BB)
1749 assert((count < 3) && "Too much destinations to test!");
1750 CasesBits.push_back(CaseBits(0, Dest, 0));
1754 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1755 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1757 for (uint64_t j = lo; j <= hi; j++) {
1758 CasesBits[i].Mask |= 1 << j;
1759 CasesBits[i].Bits++;
1763 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1765 SelectionDAGISel::BitTestInfo BTC;
1767 // Figure out which block is immediately after the current one.
1768 MachineFunction::iterator BBI = CR.CaseBB;
1771 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1774 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1775 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1776 << ", BB: " << CasesBits[i].BB << "\n";
1778 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1779 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1780 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1785 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
1786 -1U, (CR.CaseBB == CurMBB),
1787 CR.CaseBB, Default, BTC);
1789 if (CR.CaseBB == CurMBB)
1790 visitBitTestHeader(BTB);
1792 BitTestCases.push_back(BTB);
1798 // Clusterify - Transform simple list of Cases into list of CaseRange's
1799 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1800 const SwitchInst& SI) {
1801 unsigned numCmps = 0;
1803 // Start with "simple" cases
1804 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1805 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1806 Cases.push_back(Case(SI.getSuccessorValue(i),
1807 SI.getSuccessorValue(i),
1810 sort(Cases.begin(), Cases.end(), CaseCmp());
1812 // Merge case into clusters
1813 if (Cases.size()>=2)
1814 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1815 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1816 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1817 MachineBasicBlock* nextBB = J->BB;
1818 MachineBasicBlock* currentBB = I->BB;
1820 // If the two neighboring cases go to the same destination, merge them
1821 // into a single case.
1822 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1830 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1831 if (I->Low != I->High)
1832 // A range counts double, since it requires two compares.
1839 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1840 // Figure out which block is immediately after the current one.
1841 MachineBasicBlock *NextBlock = 0;
1842 MachineFunction::iterator BBI = CurMBB;
1844 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1846 // If there is only the default destination, branch to it if it is not the
1847 // next basic block. Otherwise, just fall through.
1848 if (SI.getNumOperands() == 2) {
1849 // Update machine-CFG edges.
1851 // If this is not a fall-through branch, emit the branch.
1852 if (Default != NextBlock)
1853 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1854 DAG.getBasicBlock(Default)));
1856 CurMBB->addSuccessor(Default);
1860 // If there are any non-default case statements, create a vector of Cases
1861 // representing each one, and sort the vector so that we can efficiently
1862 // create a binary search tree from them.
1864 unsigned numCmps = Clusterify(Cases, SI);
1865 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1866 << ". Total compares: " << numCmps << "\n";
1868 // Get the Value to be switched on and default basic blocks, which will be
1869 // inserted into CaseBlock records, representing basic blocks in the binary
1871 Value *SV = SI.getOperand(0);
1873 // Push the initial CaseRec onto the worklist
1874 CaseRecVector WorkList;
1875 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1877 while (!WorkList.empty()) {
1878 // Grab a record representing a case range to process off the worklist
1879 CaseRec CR = WorkList.back();
1880 WorkList.pop_back();
1882 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1885 // If the range has few cases (two or less) emit a series of specific
1887 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1890 // If the switch has more than 5 blocks, and at least 40% dense, and the
1891 // target supports indirect branches, then emit a jump table rather than
1892 // lowering the switch to a binary tree of conditional branches.
1893 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1896 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1897 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1898 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
1903 void SelectionDAGLowering::visitSub(User &I) {
1904 // -0.0 - X --> fneg
1905 const Type *Ty = I.getType();
1906 if (isa<VectorType>(Ty)) {
1907 visitVectorBinary(I, ISD::VSUB);
1908 } else if (Ty->isFloatingPoint()) {
1909 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1910 if (CFP->isExactlyValue(-0.0)) {
1911 SDOperand Op2 = getValue(I.getOperand(1));
1912 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1915 visitScalarBinary(I, ISD::FSUB);
1917 visitScalarBinary(I, ISD::SUB);
1920 void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
1921 SDOperand Op1 = getValue(I.getOperand(0));
1922 SDOperand Op2 = getValue(I.getOperand(1));
1924 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
1928 SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
1929 assert(isa<VectorType>(I.getType()));
1930 const VectorType *Ty = cast<VectorType>(I.getType());
1931 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
1933 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1934 getValue(I.getOperand(0)),
1935 getValue(I.getOperand(1)),
1936 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1940 void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1941 unsigned VectorOp) {
1942 if (isa<VectorType>(I.getType()))
1943 visitVectorBinary(I, VectorOp);
1945 visitScalarBinary(I, ScalarOp);
1948 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1949 SDOperand Op1 = getValue(I.getOperand(0));
1950 SDOperand Op2 = getValue(I.getOperand(1));
1952 if (TLI.getShiftAmountTy() < Op2.getValueType())
1953 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1954 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1955 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1957 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1960 void SelectionDAGLowering::visitICmp(User &I) {
1961 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1962 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1963 predicate = IC->getPredicate();
1964 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1965 predicate = ICmpInst::Predicate(IC->getPredicate());
1966 SDOperand Op1 = getValue(I.getOperand(0));
1967 SDOperand Op2 = getValue(I.getOperand(1));
1968 ISD::CondCode Opcode;
1969 switch (predicate) {
1970 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1971 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1972 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1973 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1974 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1975 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1976 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1977 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1978 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1979 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1981 assert(!"Invalid ICmp predicate value");
1982 Opcode = ISD::SETEQ;
1985 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1988 void SelectionDAGLowering::visitFCmp(User &I) {
1989 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1990 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1991 predicate = FC->getPredicate();
1992 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1993 predicate = FCmpInst::Predicate(FC->getPredicate());
1994 SDOperand Op1 = getValue(I.getOperand(0));
1995 SDOperand Op2 = getValue(I.getOperand(1));
1996 ISD::CondCode Condition, FOC, FPC;
1997 switch (predicate) {
1998 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1999 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2000 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2001 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2002 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2003 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2004 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2005 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2006 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2007 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2008 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2009 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2010 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2011 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2012 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2013 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2015 assert(!"Invalid FCmp predicate value");
2016 FOC = FPC = ISD::SETFALSE;
2019 if (FiniteOnlyFPMath())
2023 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2026 void SelectionDAGLowering::visitSelect(User &I) {
2027 SDOperand Cond = getValue(I.getOperand(0));
2028 SDOperand TrueVal = getValue(I.getOperand(1));
2029 SDOperand FalseVal = getValue(I.getOperand(2));
2030 if (!isa<VectorType>(I.getType())) {
2031 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2032 TrueVal, FalseVal));
2034 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
2035 *(TrueVal.Val->op_end()-2),
2036 *(TrueVal.Val->op_end()-1)));
2041 void SelectionDAGLowering::visitTrunc(User &I) {
2042 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2043 SDOperand N = getValue(I.getOperand(0));
2044 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2045 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2048 void SelectionDAGLowering::visitZExt(User &I) {
2049 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2050 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2051 SDOperand N = getValue(I.getOperand(0));
2052 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2053 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2056 void SelectionDAGLowering::visitSExt(User &I) {
2057 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2058 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2059 SDOperand N = getValue(I.getOperand(0));
2060 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2061 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2064 void SelectionDAGLowering::visitFPTrunc(User &I) {
2065 // FPTrunc is never a no-op cast, no need to check
2066 SDOperand N = getValue(I.getOperand(0));
2067 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2068 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2071 void SelectionDAGLowering::visitFPExt(User &I){
2072 // FPTrunc is never a no-op cast, no need to check
2073 SDOperand N = getValue(I.getOperand(0));
2074 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2075 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2078 void SelectionDAGLowering::visitFPToUI(User &I) {
2079 // FPToUI is never a no-op cast, no need to check
2080 SDOperand N = getValue(I.getOperand(0));
2081 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2082 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2085 void SelectionDAGLowering::visitFPToSI(User &I) {
2086 // FPToSI is never a no-op cast, no need to check
2087 SDOperand N = getValue(I.getOperand(0));
2088 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2089 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2092 void SelectionDAGLowering::visitUIToFP(User &I) {
2093 // UIToFP is never a no-op cast, no need to check
2094 SDOperand N = getValue(I.getOperand(0));
2095 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2096 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2099 void SelectionDAGLowering::visitSIToFP(User &I){
2100 // UIToFP is never a no-op cast, no need to check
2101 SDOperand N = getValue(I.getOperand(0));
2102 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2103 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2106 void SelectionDAGLowering::visitPtrToInt(User &I) {
2107 // What to do depends on the size of the integer and the size of the pointer.
2108 // We can either truncate, zero extend, or no-op, accordingly.
2109 SDOperand N = getValue(I.getOperand(0));
2110 MVT::ValueType SrcVT = N.getValueType();
2111 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2113 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2114 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2116 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2117 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2118 setValue(&I, Result);
2121 void SelectionDAGLowering::visitIntToPtr(User &I) {
2122 // What to do depends on the size of the integer and the size of the pointer.
2123 // We can either truncate, zero extend, or no-op, accordingly.
2124 SDOperand N = getValue(I.getOperand(0));
2125 MVT::ValueType SrcVT = N.getValueType();
2126 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2127 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2128 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2130 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2131 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2134 void SelectionDAGLowering::visitBitCast(User &I) {
2135 SDOperand N = getValue(I.getOperand(0));
2136 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2137 if (DestVT == MVT::Vector) {
2138 // This is a cast to a vector from something else.
2139 // Get information about the output vector.
2140 const VectorType *DestTy = cast<VectorType>(I.getType());
2141 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2142 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
2143 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
2144 DAG.getValueType(EltVT)));
2147 MVT::ValueType SrcVT = N.getValueType();
2148 if (SrcVT == MVT::Vector) {
2149 // This is a cast from a vctor to something else.
2150 // Get information about the input vector.
2151 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
2155 // BitCast assures us that source and destination are the same size so this
2156 // is either a BIT_CONVERT or a no-op.
2157 if (DestVT != N.getValueType())
2158 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2160 setValue(&I, N); // noop cast.
2163 void SelectionDAGLowering::visitInsertElement(User &I) {
2164 SDOperand InVec = getValue(I.getOperand(0));
2165 SDOperand InVal = getValue(I.getOperand(1));
2166 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2167 getValue(I.getOperand(2)));
2169 SDOperand Num = *(InVec.Val->op_end()-2);
2170 SDOperand Typ = *(InVec.Val->op_end()-1);
2171 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
2172 InVec, InVal, InIdx, Num, Typ));
2175 void SelectionDAGLowering::visitExtractElement(User &I) {
2176 SDOperand InVec = getValue(I.getOperand(0));
2177 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2178 getValue(I.getOperand(1)));
2179 SDOperand Typ = *(InVec.Val->op_end()-1);
2180 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
2181 TLI.getValueType(I.getType()), InVec, InIdx));
2184 void SelectionDAGLowering::visitShuffleVector(User &I) {
2185 SDOperand V1 = getValue(I.getOperand(0));
2186 SDOperand V2 = getValue(I.getOperand(1));
2187 SDOperand Mask = getValue(I.getOperand(2));
2189 SDOperand Num = *(V1.Val->op_end()-2);
2190 SDOperand Typ = *(V2.Val->op_end()-1);
2191 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2192 V1, V2, Mask, Num, Typ));
2196 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2197 SDOperand N = getValue(I.getOperand(0));
2198 const Type *Ty = I.getOperand(0)->getType();
2200 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2203 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2204 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2207 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2208 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2209 getIntPtrConstant(Offset));
2211 Ty = StTy->getElementType(Field);
2213 Ty = cast<SequentialType>(Ty)->getElementType();
2215 // If this is a constant subscript, handle it quickly.
2216 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2217 if (CI->getZExtValue() == 0) continue;
2219 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2220 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2224 // N = N + Idx * ElementSize;
2225 uint64_t ElementSize = TD->getTypeSize(Ty);
2226 SDOperand IdxN = getValue(Idx);
2228 // If the index is smaller or larger than intptr_t, truncate or extend
2230 if (IdxN.getValueType() < N.getValueType()) {
2231 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2232 } else if (IdxN.getValueType() > N.getValueType())
2233 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2235 // If this is a multiply by a power of two, turn it into a shl
2236 // immediately. This is a very common case.
2237 if (isPowerOf2_64(ElementSize)) {
2238 unsigned Amt = Log2_64(ElementSize);
2239 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2240 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2241 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2245 SDOperand Scale = getIntPtrConstant(ElementSize);
2246 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2247 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2253 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2254 // If this is a fixed sized alloca in the entry block of the function,
2255 // allocate it statically on the stack.
2256 if (FuncInfo.StaticAllocaMap.count(&I))
2257 return; // getValue will auto-populate this.
2259 const Type *Ty = I.getAllocatedType();
2260 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
2262 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2265 SDOperand AllocSize = getValue(I.getArraySize());
2266 MVT::ValueType IntPtr = TLI.getPointerTy();
2267 if (IntPtr < AllocSize.getValueType())
2268 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2269 else if (IntPtr > AllocSize.getValueType())
2270 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2272 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2273 getIntPtrConstant(TySize));
2275 // Handle alignment. If the requested alignment is less than or equal to the
2276 // stack alignment, ignore it and round the size of the allocation up to the
2277 // stack alignment size. If the size is greater than the stack alignment, we
2278 // note this in the DYNAMIC_STACKALLOC node.
2279 unsigned StackAlign =
2280 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2281 if (Align <= StackAlign) {
2283 // Add SA-1 to the size.
2284 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2285 getIntPtrConstant(StackAlign-1));
2286 // Mask out the low bits for alignment purposes.
2287 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2288 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2291 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
2292 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2294 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2296 DAG.setRoot(DSA.getValue(1));
2298 // Inform the Frame Information that we have just allocated a variable-sized
2300 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2303 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2304 SDOperand Ptr = getValue(I.getOperand(0));
2310 // Do not serialize non-volatile loads against each other.
2311 Root = DAG.getRoot();
2314 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2315 Root, I.isVolatile()));
2318 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2319 const Value *SV, SDOperand Root,
2322 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
2323 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
2324 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2325 DAG.getSrcValue(SV));
2327 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
2331 DAG.setRoot(L.getValue(1));
2333 PendingLoads.push_back(L.getValue(1));
2339 void SelectionDAGLowering::visitStore(StoreInst &I) {
2340 Value *SrcV = I.getOperand(0);
2341 SDOperand Src = getValue(SrcV);
2342 SDOperand Ptr = getValue(I.getOperand(1));
2343 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2347 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2348 /// access memory and has no other side effects at all.
2349 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2350 #define GET_NO_MEMORY_INTRINSICS
2351 #include "llvm/Intrinsics.gen"
2352 #undef GET_NO_MEMORY_INTRINSICS
2356 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2357 // have any side-effects or if it only reads memory.
2358 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2359 #define GET_SIDE_EFFECT_INFO
2360 #include "llvm/Intrinsics.gen"
2361 #undef GET_SIDE_EFFECT_INFO
2365 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2367 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2368 unsigned Intrinsic) {
2369 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
2370 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
2372 // Build the operand list.
2373 SmallVector<SDOperand, 8> Ops;
2374 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2376 // We don't need to serialize loads against other loads.
2377 Ops.push_back(DAG.getRoot());
2379 Ops.push_back(getRoot());
2383 // Add the intrinsic ID as an integer operand.
2384 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2386 // Add all operands of the call to the operand list.
2387 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2388 SDOperand Op = getValue(I.getOperand(i));
2390 // If this is a vector type, force it to the right vector type.
2391 if (Op.getValueType() == MVT::Vector) {
2392 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
2393 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2395 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2396 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2397 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2400 assert(TLI.isTypeLegal(Op.getValueType()) &&
2401 "Intrinsic uses a non-legal type?");
2405 std::vector<MVT::ValueType> VTs;
2406 if (I.getType() != Type::VoidTy) {
2407 MVT::ValueType VT = TLI.getValueType(I.getType());
2408 if (VT == MVT::Vector) {
2409 const VectorType *DestTy = cast<VectorType>(I.getType());
2410 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2412 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2413 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2416 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2420 VTs.push_back(MVT::Other);
2422 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2427 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2428 &Ops[0], Ops.size());
2429 else if (I.getType() != Type::VoidTy)
2430 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2431 &Ops[0], Ops.size());
2433 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2434 &Ops[0], Ops.size());
2437 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2439 PendingLoads.push_back(Chain);
2443 if (I.getType() != Type::VoidTy) {
2444 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2445 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2446 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2447 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2448 DAG.getValueType(EVT));
2450 setValue(&I, Result);
2454 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2455 /// we want to emit this as a call to a named external function, return the name
2456 /// otherwise lower it and return null.
2458 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2459 switch (Intrinsic) {
2461 // By default, turn this into a target intrinsic node.
2462 visitTargetIntrinsic(I, Intrinsic);
2464 case Intrinsic::vastart: visitVAStart(I); return 0;
2465 case Intrinsic::vaend: visitVAEnd(I); return 0;
2466 case Intrinsic::vacopy: visitVACopy(I); return 0;
2467 case Intrinsic::returnaddress:
2468 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2469 getValue(I.getOperand(1))));
2471 case Intrinsic::frameaddress:
2472 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2473 getValue(I.getOperand(1))));
2475 case Intrinsic::setjmp:
2476 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2478 case Intrinsic::longjmp:
2479 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2481 case Intrinsic::memcpy_i32:
2482 case Intrinsic::memcpy_i64:
2483 visitMemIntrinsic(I, ISD::MEMCPY);
2485 case Intrinsic::memset_i32:
2486 case Intrinsic::memset_i64:
2487 visitMemIntrinsic(I, ISD::MEMSET);
2489 case Intrinsic::memmove_i32:
2490 case Intrinsic::memmove_i64:
2491 visitMemIntrinsic(I, ISD::MEMMOVE);
2494 case Intrinsic::dbg_stoppoint: {
2495 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2496 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2497 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2501 Ops[1] = getValue(SPI.getLineValue());
2502 Ops[2] = getValue(SPI.getColumnValue());
2504 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2505 assert(DD && "Not a debug information descriptor");
2506 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2508 Ops[3] = DAG.getString(CompileUnit->getFileName());
2509 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2511 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2516 case Intrinsic::dbg_region_start: {
2517 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2518 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2519 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2520 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2521 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2522 DAG.getConstant(LabelID, MVT::i32)));
2527 case Intrinsic::dbg_region_end: {
2528 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2529 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2530 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2531 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2532 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2533 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2538 case Intrinsic::dbg_func_start: {
2539 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2540 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2541 if (MMI && FSI.getSubprogram() &&
2542 MMI->Verify(FSI.getSubprogram())) {
2543 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
2544 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2545 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2550 case Intrinsic::dbg_declare: {
2551 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2552 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2553 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
2554 SDOperand AddressOp = getValue(DI.getAddress());
2555 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
2556 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
2562 case Intrinsic::eh_exception: {
2563 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2566 // Add a label to mark the beginning of the landing pad. Deletion of the
2567 // landing pad can thus be detected via the MachineModuleInfo.
2568 unsigned LabelID = MMI->addLandingPad(CurMBB);
2569 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2570 DAG.getConstant(LabelID, MVT::i32)));
2572 // Mark exception register as live in.
2573 unsigned Reg = TLI.getExceptionAddressRegister();
2574 if (Reg) CurMBB->addLiveIn(Reg);
2576 // Insert the EXCEPTIONADDR instruction.
2577 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2579 Ops[0] = DAG.getRoot();
2580 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2582 DAG.setRoot(Op.getValue(1));
2584 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2589 case Intrinsic::eh_selector:
2590 case Intrinsic::eh_filter:{
2591 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2594 // Inform the MachineModuleInfo of the personality for this landing pad.
2595 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2596 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2597 isa<Function>(CE->getOperand(0)) &&
2598 "Personality should be a function");
2599 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
2600 if (Intrinsic == Intrinsic::eh_filter)
2601 MMI->setIsFilterLandingPad(CurMBB);
2603 // Gather all the type infos for this landing pad and pass them along to
2604 // MachineModuleInfo.
2605 std::vector<GlobalVariable *> TyInfo;
2606 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
2607 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2608 if (CE && CE->getOpcode() == Instruction::BitCast &&
2609 isa<GlobalVariable>(CE->getOperand(0))) {
2610 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2612 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2613 assert(CI && CI->getZExtValue() == 0 &&
2614 "TypeInfo must be a global variable typeinfo or NULL");
2615 TyInfo.push_back(NULL);
2618 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2620 // Mark exception selector register as live in.
2621 unsigned Reg = TLI.getExceptionSelectorRegister();
2622 if (Reg) CurMBB->addLiveIn(Reg);
2624 // Insert the EHSELECTION instruction.
2625 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
2627 Ops[0] = getValue(I.getOperand(1));
2629 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2631 DAG.setRoot(Op.getValue(1));
2633 setValue(&I, DAG.getConstant(0, MVT::i32));
2639 case Intrinsic::eh_typeid_for: {
2640 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2643 // Find the type id for the given typeinfo.
2644 GlobalVariable *GV = NULL;
2645 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2646 if (CE && CE->getOpcode() == Instruction::BitCast &&
2647 isa<GlobalVariable>(CE->getOperand(0))) {
2648 GV = cast<GlobalVariable>(CE->getOperand(0));
2650 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2651 assert(CI && CI->getZExtValue() == 0 &&
2652 "TypeInfo must be a global variable typeinfo or NULL");
2656 unsigned TypeID = MMI->getTypeIDFor(GV);
2657 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
2659 setValue(&I, DAG.getConstant(0, MVT::i32));
2665 case Intrinsic::sqrt_f32:
2666 case Intrinsic::sqrt_f64:
2667 setValue(&I, DAG.getNode(ISD::FSQRT,
2668 getValue(I.getOperand(1)).getValueType(),
2669 getValue(I.getOperand(1))));
2671 case Intrinsic::powi_f32:
2672 case Intrinsic::powi_f64:
2673 setValue(&I, DAG.getNode(ISD::FPOWI,
2674 getValue(I.getOperand(1)).getValueType(),
2675 getValue(I.getOperand(1)),
2676 getValue(I.getOperand(2))));
2678 case Intrinsic::pcmarker: {
2679 SDOperand Tmp = getValue(I.getOperand(1));
2680 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2683 case Intrinsic::readcyclecounter: {
2684 SDOperand Op = getRoot();
2685 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2686 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2689 DAG.setRoot(Tmp.getValue(1));
2692 case Intrinsic::part_select: {
2693 // Currently not implemented: just abort
2694 assert(0 && "part_select intrinsic not implemented");
2697 case Intrinsic::part_set: {
2698 // Currently not implemented: just abort
2699 assert(0 && "part_set intrinsic not implemented");
2702 case Intrinsic::bswap:
2703 setValue(&I, DAG.getNode(ISD::BSWAP,
2704 getValue(I.getOperand(1)).getValueType(),
2705 getValue(I.getOperand(1))));
2707 case Intrinsic::cttz: {
2708 SDOperand Arg = getValue(I.getOperand(1));
2709 MVT::ValueType Ty = Arg.getValueType();
2710 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2712 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2713 else if (Ty > MVT::i32)
2714 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2715 setValue(&I, result);
2718 case Intrinsic::ctlz: {
2719 SDOperand Arg = getValue(I.getOperand(1));
2720 MVT::ValueType Ty = Arg.getValueType();
2721 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2723 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2724 else if (Ty > MVT::i32)
2725 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2726 setValue(&I, result);
2729 case Intrinsic::ctpop: {
2730 SDOperand Arg = getValue(I.getOperand(1));
2731 MVT::ValueType Ty = Arg.getValueType();
2732 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2734 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2735 else if (Ty > MVT::i32)
2736 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2737 setValue(&I, result);
2740 case Intrinsic::stacksave: {
2741 SDOperand Op = getRoot();
2742 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2743 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2745 DAG.setRoot(Tmp.getValue(1));
2748 case Intrinsic::stackrestore: {
2749 SDOperand Tmp = getValue(I.getOperand(1));
2750 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2753 case Intrinsic::prefetch:
2754 // FIXME: Currently discarding prefetches.
2760 void SelectionDAGLowering::LowerCallTo(Instruction &I,
2761 const Type *CalledValueTy,
2762 unsigned CallingConv,
2764 SDOperand Callee, unsigned OpIdx) {
2765 const PointerType *PT = cast<PointerType>(CalledValueTy);
2766 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2767 const ParamAttrsList *Attrs = FTy->getParamAttrs();
2769 TargetLowering::ArgListTy Args;
2770 TargetLowering::ArgListEntry Entry;
2771 Args.reserve(I.getNumOperands());
2772 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2773 Value *Arg = I.getOperand(i);
2774 SDOperand ArgNode = getValue(Arg);
2775 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2776 Entry.isSExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::SExt);
2777 Entry.isZExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::ZExt);
2778 Entry.isInReg = Attrs && Attrs->paramHasAttr(i, ParamAttr::InReg);
2779 Entry.isSRet = Attrs && Attrs->paramHasAttr(i, ParamAttr::StructRet);
2780 Args.push_back(Entry);
2783 std::pair<SDOperand,SDOperand> Result =
2784 TLI.LowerCallTo(getRoot(), I.getType(),
2785 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
2786 FTy->isVarArg(), CallingConv, IsTailCall,
2788 if (I.getType() != Type::VoidTy)
2789 setValue(&I, Result.first);
2790 DAG.setRoot(Result.second);
2794 void SelectionDAGLowering::visitCall(CallInst &I) {
2795 const char *RenameFn = 0;
2796 if (Function *F = I.getCalledFunction()) {
2797 if (F->isDeclaration())
2798 if (unsigned IID = F->getIntrinsicID()) {
2799 RenameFn = visitIntrinsicCall(I, IID);
2802 } else { // Not an LLVM intrinsic.
2803 const std::string &Name = F->getName();
2804 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2805 if (I.getNumOperands() == 3 && // Basic sanity checks.
2806 I.getOperand(1)->getType()->isFloatingPoint() &&
2807 I.getType() == I.getOperand(1)->getType() &&
2808 I.getType() == I.getOperand(2)->getType()) {
2809 SDOperand LHS = getValue(I.getOperand(1));
2810 SDOperand RHS = getValue(I.getOperand(2));
2811 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2815 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2816 if (I.getNumOperands() == 2 && // Basic sanity checks.
2817 I.getOperand(1)->getType()->isFloatingPoint() &&
2818 I.getType() == I.getOperand(1)->getType()) {
2819 SDOperand Tmp = getValue(I.getOperand(1));
2820 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2823 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2824 if (I.getNumOperands() == 2 && // Basic sanity checks.
2825 I.getOperand(1)->getType()->isFloatingPoint() &&
2826 I.getType() == I.getOperand(1)->getType()) {
2827 SDOperand Tmp = getValue(I.getOperand(1));
2828 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2831 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2832 if (I.getNumOperands() == 2 && // Basic sanity checks.
2833 I.getOperand(1)->getType()->isFloatingPoint() &&
2834 I.getType() == I.getOperand(1)->getType()) {
2835 SDOperand Tmp = getValue(I.getOperand(1));
2836 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2841 } else if (isa<InlineAsm>(I.getOperand(0))) {
2848 Callee = getValue(I.getOperand(0));
2850 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2852 LowerCallTo(I, I.getCalledValue()->getType(),
2860 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2861 SDOperand &Chain, SDOperand &Flag)const{
2862 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2863 Chain = Val.getValue(1);
2864 Flag = Val.getValue(2);
2866 // If the result was expanded, copy from the top part.
2867 if (Regs.size() > 1) {
2868 assert(Regs.size() == 2 &&
2869 "Cannot expand to more than 2 elts yet!");
2870 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2871 Chain = Hi.getValue(1);
2872 Flag = Hi.getValue(2);
2873 if (DAG.getTargetLoweringInfo().isLittleEndian())
2874 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2876 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2879 // Otherwise, if the return value was promoted or extended, truncate it to the
2880 // appropriate type.
2881 if (RegVT == ValueVT)
2884 if (MVT::isVector(RegVT)) {
2885 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2886 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2887 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2889 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2892 if (MVT::isInteger(RegVT)) {
2893 if (ValueVT < RegVT)
2894 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2896 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2899 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2900 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2903 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2904 /// specified value into the registers specified by this object. This uses
2905 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2906 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2907 SDOperand &Chain, SDOperand &Flag,
2908 MVT::ValueType PtrVT) const {
2909 if (Regs.size() == 1) {
2910 // If there is a single register and the types differ, this must be
2912 if (RegVT != ValueVT) {
2913 if (MVT::isVector(RegVT)) {
2914 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2915 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
2916 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
2917 if (RegVT < ValueVT)
2918 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2920 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2921 } else if (MVT::isFloatingPoint(RegVT) &&
2922 MVT::isFloatingPoint(Val.getValueType())) {
2923 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2924 } else if (MVT::getSizeInBits(RegVT) ==
2925 MVT::getSizeInBits(Val.getValueType())) {
2926 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2928 assert(0 && "Unknown mismatch!");
2931 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2932 Flag = Chain.getValue(1);
2934 std::vector<unsigned> R(Regs);
2935 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2936 std::reverse(R.begin(), R.end());
2938 for (unsigned i = 0, e = R.size(); i != e; ++i) {
2939 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2940 DAG.getConstant(i, PtrVT));
2941 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2942 Flag = Chain.getValue(1);
2947 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2948 /// operand list. This adds the code marker and includes the number of
2949 /// values added into it.
2950 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2951 std::vector<SDOperand> &Ops) const {
2952 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2953 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
2954 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2955 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2958 /// isAllocatableRegister - If the specified register is safe to allocate,
2959 /// i.e. it isn't a stack pointer or some other special register, return the
2960 /// register class for the register. Otherwise, return null.
2961 static const TargetRegisterClass *
2962 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2963 const TargetLowering &TLI, const MRegisterInfo *MRI) {
2964 MVT::ValueType FoundVT = MVT::Other;
2965 const TargetRegisterClass *FoundRC = 0;
2966 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2967 E = MRI->regclass_end(); RCI != E; ++RCI) {
2968 MVT::ValueType ThisVT = MVT::Other;
2970 const TargetRegisterClass *RC = *RCI;
2971 // If none of the the value types for this register class are valid, we
2972 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2973 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2975 if (TLI.isTypeLegal(*I)) {
2976 // If we have already found this register in a different register class,
2977 // choose the one with the largest VT specified. For example, on
2978 // PowerPC, we favor f64 register classes over f32.
2979 if (FoundVT == MVT::Other ||
2980 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2987 if (ThisVT == MVT::Other) continue;
2989 // NOTE: This isn't ideal. In particular, this might allocate the
2990 // frame pointer in functions that need it (due to them not being taken
2991 // out of allocation, because a variable sized allocation hasn't been seen
2992 // yet). This is a slight code pessimization, but should still work.
2993 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2994 E = RC->allocation_order_end(MF); I != E; ++I)
2996 // We found a matching register class. Keep looking at others in case
2997 // we find one with larger registers that this physreg is also in.
3006 RegsForValue SelectionDAGLowering::
3007 GetRegistersForValue(const std::string &ConstrCode,
3008 MVT::ValueType VT, bool isOutReg, bool isInReg,
3009 std::set<unsigned> &OutputRegs,
3010 std::set<unsigned> &InputRegs) {
3011 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3012 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
3013 std::vector<unsigned> Regs;
3015 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
3016 MVT::ValueType RegVT;
3017 MVT::ValueType ValueVT = VT;
3019 // If this is a constraint for a specific physical register, like {r17},
3021 if (PhysReg.first) {
3022 if (VT == MVT::Other)
3023 ValueVT = *PhysReg.second->vt_begin();
3025 // Get the actual register value type. This is important, because the user
3026 // may have asked for (e.g.) the AX register in i32 type. We need to
3027 // remember that AX is actually i16 to get the right extension.
3028 RegVT = *PhysReg.second->vt_begin();
3030 // This is a explicit reference to a physical register.
3031 Regs.push_back(PhysReg.first);
3033 // If this is an expanded reference, add the rest of the regs to Regs.
3035 TargetRegisterClass::iterator I = PhysReg.second->begin();
3036 TargetRegisterClass::iterator E = PhysReg.second->end();
3037 for (; *I != PhysReg.first; ++I)
3038 assert(I != E && "Didn't find reg!");
3040 // Already added the first reg.
3042 for (; NumRegs; --NumRegs, ++I) {
3043 assert(I != E && "Ran out of registers to allocate!");
3047 return RegsForValue(Regs, RegVT, ValueVT);
3050 // Otherwise, if this was a reference to an LLVM register class, create vregs
3051 // for this reference.
3052 std::vector<unsigned> RegClassRegs;
3053 if (PhysReg.second) {
3054 // If this is an early clobber or tied register, our regalloc doesn't know
3055 // how to maintain the constraint. If it isn't, go ahead and create vreg
3056 // and let the regalloc do the right thing.
3057 if (!isOutReg || !isInReg) {
3058 RegVT = *PhysReg.second->vt_begin();
3060 if (VT == MVT::Other)
3063 // Create the appropriate number of virtual registers.
3064 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
3065 for (; NumRegs; --NumRegs)
3066 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3068 return RegsForValue(Regs, RegVT, ValueVT);
3071 // Otherwise, we can't allocate it. Let the code below figure out how to
3072 // maintain these constraints.
3073 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3076 // This is a reference to a register class that doesn't directly correspond
3077 // to an LLVM register class. Allocate NumRegs consecutive, available,
3078 // registers from the class.
3079 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
3082 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3083 MachineFunction &MF = *CurMBB->getParent();
3084 unsigned NumAllocated = 0;
3085 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3086 unsigned Reg = RegClassRegs[i];
3087 // See if this register is available.
3088 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3089 (isInReg && InputRegs.count(Reg))) { // Already used.
3090 // Make sure we find consecutive registers.
3095 // Check to see if this register is allocatable (i.e. don't give out the
3097 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3099 // Make sure we find consecutive registers.
3104 // Okay, this register is good, we can use it.
3107 // If we allocated enough consecutive registers, succeed.
3108 if (NumAllocated == NumRegs) {
3109 unsigned RegStart = (i-NumAllocated)+1;
3110 unsigned RegEnd = i+1;
3111 // Mark all of the allocated registers used.
3112 for (unsigned i = RegStart; i != RegEnd; ++i) {
3113 unsigned Reg = RegClassRegs[i];
3114 Regs.push_back(Reg);
3115 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
3116 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
3119 return RegsForValue(Regs, *RC->vt_begin(), VT);
3123 // Otherwise, we couldn't allocate enough registers for this.
3124 return RegsForValue();
3127 /// getConstraintGenerality - Return an integer indicating how general CT is.
3128 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3130 default: assert(0 && "Unknown constraint type!");
3131 case TargetLowering::C_Other:
3132 case TargetLowering::C_Unknown:
3134 case TargetLowering::C_Register:
3136 case TargetLowering::C_RegisterClass:
3138 case TargetLowering::C_Memory:
3143 static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
3144 const TargetLowering &TLI) {
3145 assert(!C.empty() && "Must have at least one constraint");
3146 if (C.size() == 1) return C[0];
3148 std::string *Current = &C[0];
3149 // If we have multiple constraints, try to pick the most general one ahead
3150 // of time. This isn't a wonderful solution, but handles common cases.
3151 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0]);
3152 for (unsigned j = 1, e = C.size(); j != e; ++j) {
3153 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j]);
3154 if (getConstraintGenerality(ThisFlavor) >
3155 getConstraintGenerality(Flavor)) {
3156 // This constraint letter is more general than the previous one,
3158 Flavor = ThisFlavor;
3166 /// visitInlineAsm - Handle a call to an InlineAsm object.
3168 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3169 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
3171 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
3174 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
3175 std::vector<MVT::ValueType> ConstraintVTs;
3177 /// AsmNodeOperands - A list of pairs. The first element is a register, the
3178 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
3179 /// if it is a def of that register.
3180 std::vector<SDOperand> AsmNodeOperands;
3181 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3182 AsmNodeOperands.push_back(AsmStr);
3184 SDOperand Chain = getRoot();
3187 // We fully assign registers here at isel time. This is not optimal, but
3188 // should work. For register classes that correspond to LLVM classes, we
3189 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
3190 // over the constraints, collecting fixed registers that we know we can't use.
3191 std::set<unsigned> OutputRegs, InputRegs;
3193 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
3194 std::string ConstraintCode =
3195 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
3197 MVT::ValueType OpVT;
3199 // Compute the value type for each operand and add it to ConstraintVTs.
3200 switch (Constraints[i].Type) {
3201 case InlineAsm::isOutput:
3202 if (!Constraints[i].isIndirectOutput) {
3203 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3204 OpVT = TLI.getValueType(I.getType());
3206 const Type *OpTy = I.getOperand(OpNum)->getType();
3207 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
3208 OpNum++; // Consumes a call operand.
3211 case InlineAsm::isInput:
3212 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
3213 OpNum++; // Consumes a call operand.
3215 case InlineAsm::isClobber:
3220 ConstraintVTs.push_back(OpVT);
3222 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
3223 continue; // Not assigned a fixed reg.
3225 // Build a list of regs that this operand uses. This always has a single
3226 // element for promoted/expanded operands.
3227 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
3229 OutputRegs, InputRegs);
3231 switch (Constraints[i].Type) {
3232 case InlineAsm::isOutput:
3233 // We can't assign any other output to this register.
3234 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3235 // If this is an early-clobber output, it cannot be assigned to the same
3236 // value as the input reg.
3237 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
3238 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3240 case InlineAsm::isInput:
3241 // We can't assign any other input to this register.
3242 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3244 case InlineAsm::isClobber:
3245 // Clobbered regs cannot be used as inputs or outputs.
3246 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3247 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3252 // Loop over all of the inputs, copying the operand values into the
3253 // appropriate registers and processing the output regs.
3254 RegsForValue RetValRegs;
3255 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3258 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
3259 std::string ConstraintCode =
3260 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
3262 switch (Constraints[i].Type) {
3263 case InlineAsm::isOutput: {
3264 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3265 if (ConstraintCode.size() == 1) // not a physreg name.
3266 CTy = TLI.getConstraintType(ConstraintCode);
3268 if (CTy == TargetLowering::C_Memory) {
3270 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
3272 // Check that the operand (the address to store to) isn't a float.
3273 if (!MVT::isInteger(InOperandVal.getValueType()))
3274 assert(0 && "MATCH FAIL!");
3276 if (!Constraints[i].isIndirectOutput)
3277 assert(0 && "MATCH FAIL!");
3279 OpNum++; // Consumes a call operand.
3281 // Extend/truncate to the right pointer type if needed.
3282 MVT::ValueType PtrType = TLI.getPointerTy();
3283 if (InOperandVal.getValueType() < PtrType)
3284 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3285 else if (InOperandVal.getValueType() > PtrType)
3286 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3288 // Add information to the INLINEASM node to know about this output.
3289 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3290 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3291 AsmNodeOperands.push_back(InOperandVal);
3295 // Otherwise, this is a register output.
3296 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3298 // If this is an early-clobber output, or if there is an input
3299 // constraint that matches this, we need to reserve the input register
3300 // so no other inputs allocate to it.
3301 bool UsesInputRegister = false;
3302 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
3303 UsesInputRegister = true;
3305 // Copy the output from the appropriate register. Find a register that
3308 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3309 true, UsesInputRegister,
3310 OutputRegs, InputRegs);
3311 if (Regs.Regs.empty()) {
3312 cerr << "Couldn't allocate output reg for contraint '"
3313 << ConstraintCode << "'!\n";
3317 if (!Constraints[i].isIndirectOutput) {
3318 assert(RetValRegs.Regs.empty() &&
3319 "Cannot have multiple output constraints yet!");
3320 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3323 IndirectStoresToEmit.push_back(std::make_pair(Regs,
3324 I.getOperand(OpNum)));
3325 OpNum++; // Consumes a call operand.
3328 // Add information to the INLINEASM node to know that this register is
3330 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
3333 case InlineAsm::isInput: {
3334 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
3335 OpNum++; // Consumes a call operand.
3337 if (isdigit(ConstraintCode[0])) { // Matching constraint?
3338 // If this is required to match an output register we have already set,
3339 // just use its register.
3340 unsigned OperandNo = atoi(ConstraintCode.c_str());
3342 // Scan until we find the definition we already emitted of this operand.
3343 // When we find it, create a RegsForValue operand.
3344 unsigned CurOp = 2; // The first operand.
3345 for (; OperandNo; --OperandNo) {
3346 // Advance to the next operand.
3348 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3349 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3350 (NumOps & 7) == 4 /*MEM*/) &&
3351 "Skipped past definitions?");
3352 CurOp += (NumOps>>3)+1;
3356 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3357 if ((NumOps & 7) == 2 /*REGDEF*/) {
3358 // Add NumOps>>3 registers to MatchedRegs.
3359 RegsForValue MatchedRegs;
3360 MatchedRegs.ValueVT = InOperandVal.getValueType();
3361 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3362 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3364 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3365 MatchedRegs.Regs.push_back(Reg);
3368 // Use the produced MatchedRegs object to
3369 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3370 TLI.getPointerTy());
3371 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3374 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3375 assert(0 && "matching constraints for memory operands unimp");
3379 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3380 if (ConstraintCode.size() == 1) // not a physreg name.
3381 CTy = TLI.getConstraintType(ConstraintCode);
3383 if (CTy == TargetLowering::C_Other) {
3384 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
3385 ConstraintCode[0], DAG);
3386 if (!InOperandVal.Val) {
3387 cerr << "Invalid operand for inline asm constraint '"
3388 << ConstraintCode << "'!\n";
3392 // Add information to the INLINEASM node to know about this input.
3393 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3394 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3395 AsmNodeOperands.push_back(InOperandVal);
3397 } else if (CTy == TargetLowering::C_Memory) {
3400 // If the operand is a float, spill to a constant pool entry to get its
3402 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
3403 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
3405 if (!MVT::isInteger(InOperandVal.getValueType())) {
3406 cerr << "Match failed, cannot handle this yet!\n";
3407 InOperandVal.Val->dump();
3411 // Extend/truncate to the right pointer type if needed.
3412 MVT::ValueType PtrType = TLI.getPointerTy();
3413 if (InOperandVal.getValueType() < PtrType)
3414 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3415 else if (InOperandVal.getValueType() > PtrType)
3416 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3418 // Add information to the INLINEASM node to know about this input.
3419 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3420 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3421 AsmNodeOperands.push_back(InOperandVal);
3425 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3427 // Copy the input into the appropriate registers.
3428 RegsForValue InRegs =
3429 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3430 false, true, OutputRegs, InputRegs);
3431 // FIXME: should be match fail.
3432 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
3434 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
3436 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
3439 case InlineAsm::isClobber: {
3440 RegsForValue ClobberedRegs =
3441 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
3442 OutputRegs, InputRegs);
3443 // Add the clobbered value to the operand list, so that the register
3444 // allocator is aware that the physreg got clobbered.
3445 if (!ClobberedRegs.Regs.empty())
3446 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
3452 // Finish up input operands.
3453 AsmNodeOperands[0] = Chain;
3454 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3456 Chain = DAG.getNode(ISD::INLINEASM,
3457 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
3458 &AsmNodeOperands[0], AsmNodeOperands.size());
3459 Flag = Chain.getValue(1);
3461 // If this asm returns a register value, copy the result from that register
3462 // and set it as the value of the call.
3463 if (!RetValRegs.Regs.empty()) {
3464 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3466 // If the result of the inline asm is a vector, it may have the wrong
3467 // width/num elts. Make sure to convert it to the right type with
3469 if (Val.getValueType() == MVT::Vector) {
3470 const VectorType *VTy = cast<VectorType>(I.getType());
3471 unsigned DesiredNumElts = VTy->getNumElements();
3472 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType());
3474 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
3475 DAG.getConstant(DesiredNumElts, MVT::i32),
3476 DAG.getValueType(DesiredEltVT));
3482 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3484 // Process indirect outputs, first output all of the flagged copies out of
3486 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
3487 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
3488 Value *Ptr = IndirectStoresToEmit[i].second;
3489 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3490 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
3493 // Emit the non-flagged stores from the physregs.
3494 SmallVector<SDOperand, 8> OutChains;
3495 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
3496 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
3497 getValue(StoresToEmit[i].second),
3498 StoresToEmit[i].second, 0));
3499 if (!OutChains.empty())
3500 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3501 &OutChains[0], OutChains.size());
3506 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3507 SDOperand Src = getValue(I.getOperand(0));
3509 MVT::ValueType IntPtr = TLI.getPointerTy();
3511 if (IntPtr < Src.getValueType())
3512 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3513 else if (IntPtr > Src.getValueType())
3514 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
3516 // Scale the source by the type size.
3517 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
3518 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3519 Src, getIntPtrConstant(ElementSize));
3521 TargetLowering::ArgListTy Args;
3522 TargetLowering::ArgListEntry Entry;
3524 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3525 Args.push_back(Entry);
3527 std::pair<SDOperand,SDOperand> Result =
3528 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
3529 DAG.getExternalSymbol("malloc", IntPtr),
3531 setValue(&I, Result.first); // Pointers always fit in registers
3532 DAG.setRoot(Result.second);
3535 void SelectionDAGLowering::visitFree(FreeInst &I) {
3536 TargetLowering::ArgListTy Args;
3537 TargetLowering::ArgListEntry Entry;
3538 Entry.Node = getValue(I.getOperand(0));
3539 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3540 Args.push_back(Entry);
3541 MVT::ValueType IntPtr = TLI.getPointerTy();
3542 std::pair<SDOperand,SDOperand> Result =
3543 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
3544 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3545 DAG.setRoot(Result.second);
3548 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
3549 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3550 // instructions are special in various ways, which require special support to
3551 // insert. The specified MachineInstr is created but not inserted into any
3552 // basic blocks, and the scheduler passes ownership of it to this method.
3553 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3554 MachineBasicBlock *MBB) {
3555 cerr << "If a target marks an instruction with "
3556 << "'usesCustomDAGSchedInserter', it must implement "
3557 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
3562 void SelectionDAGLowering::visitVAStart(CallInst &I) {
3563 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3564 getValue(I.getOperand(1)),
3565 DAG.getSrcValue(I.getOperand(1))));
3568 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
3569 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3570 getValue(I.getOperand(0)),
3571 DAG.getSrcValue(I.getOperand(0)));
3573 DAG.setRoot(V.getValue(1));
3576 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
3577 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3578 getValue(I.getOperand(1)),
3579 DAG.getSrcValue(I.getOperand(1))));
3582 void SelectionDAGLowering::visitVACopy(CallInst &I) {
3583 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3584 getValue(I.getOperand(1)),
3585 getValue(I.getOperand(2)),
3586 DAG.getSrcValue(I.getOperand(1)),
3587 DAG.getSrcValue(I.getOperand(2))));
3590 /// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3591 /// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3592 static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3593 unsigned &i, SelectionDAG &DAG,
3594 TargetLowering &TLI) {
3595 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3596 return SDOperand(Arg, i++);
3598 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3599 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3601 return DAG.getNode(ISD::BIT_CONVERT, VT,
3602 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3603 } else if (NumVals == 2) {
3604 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3605 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3606 if (!TLI.isLittleEndian())
3608 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3610 // Value scalarized into many values. Unimp for now.
3611 assert(0 && "Cannot expand i64 -> i16 yet!");
3616 /// TargetLowering::LowerArguments - This is the default LowerArguments
3617 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
3618 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3619 /// integrated into SDISel.
3620 std::vector<SDOperand>
3621 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
3622 const FunctionType *FTy = F.getFunctionType();
3623 const ParamAttrsList *Attrs = FTy->getParamAttrs();
3624 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3625 std::vector<SDOperand> Ops;
3626 Ops.push_back(DAG.getRoot());
3627 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3628 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3630 // Add one result value for each formal argument.
3631 std::vector<MVT::ValueType> RetVals;
3633 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3635 MVT::ValueType VT = getValueType(I->getType());
3636 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3637 unsigned OriginalAlignment =
3638 getTargetData()->getABITypeAlignment(I->getType());
3640 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3641 // that is zero extended!
3642 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
3643 Flags &= ~(ISD::ParamFlags::SExt);
3644 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
3645 Flags |= ISD::ParamFlags::SExt;
3646 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
3647 Flags |= ISD::ParamFlags::InReg;
3648 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
3649 Flags |= ISD::ParamFlags::StructReturn;
3650 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
3652 switch (getTypeAction(VT)) {
3653 default: assert(0 && "Unknown type action!");
3655 RetVals.push_back(VT);
3656 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3659 RetVals.push_back(getTypeToTransformTo(VT));
3660 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3663 if (VT != MVT::Vector) {
3664 // If this is a large integer, it needs to be broken up into small
3665 // integers. Figure out what the destination type is and how many small
3666 // integers it turns into.
3667 MVT::ValueType NVT = getTypeToExpandTo(VT);
3668 unsigned NumVals = getNumElements(VT);
3669 for (unsigned i = 0; i != NumVals; ++i) {
3670 RetVals.push_back(NVT);
3671 // if it isn't first piece, alignment must be 1
3673 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3674 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3675 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3678 // Otherwise, this is a vector type. We only support legal vectors
3680 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3681 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
3683 // Figure out if there is a Packed type corresponding to this Vector
3684 // type. If so, convert to the vector type.
3685 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3686 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3687 RetVals.push_back(TVT);
3688 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3690 assert(0 && "Don't support illegal by-val vector arguments yet!");
3697 RetVals.push_back(MVT::Other);
3700 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3701 DAG.getNodeValueTypes(RetVals), RetVals.size(),
3702 &Ops[0], Ops.size()).Val;
3704 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
3706 // Set up the return result vector.
3710 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3712 MVT::ValueType VT = getValueType(I->getType());
3714 switch (getTypeAction(VT)) {
3715 default: assert(0 && "Unknown type action!");
3717 Ops.push_back(SDOperand(Result, i++));
3720 SDOperand Op(Result, i++);
3721 if (MVT::isInteger(VT)) {
3722 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
3723 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3724 DAG.getValueType(VT));
3725 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
3726 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3727 DAG.getValueType(VT));
3728 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3730 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3731 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3737 if (VT != MVT::Vector) {
3738 // If this is a large integer or a floating point node that needs to be
3739 // expanded, it needs to be reassembled from small integers. Figure out
3740 // what the source elt type is and how many small integers it is.
3741 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
3743 // Otherwise, this is a vector type. We only support legal vectors
3745 const VectorType *PTy = cast<VectorType>(I->getType());
3746 unsigned NumElems = PTy->getNumElements();
3747 const Type *EltTy = PTy->getElementType();
3749 // Figure out if there is a Packed type corresponding to this Vector
3750 // type. If so, convert to the vector type.
3751 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3752 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3753 SDOperand N = SDOperand(Result, i++);
3754 // Handle copies from generic vectors to registers.
3755 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3756 DAG.getConstant(NumElems, MVT::i32),
3757 DAG.getValueType(getValueType(EltTy)));
3760 assert(0 && "Don't support illegal by-val vector arguments yet!");
3771 /// ExpandScalarCallArgs - Recursively expand call argument node by
3772 /// bit_converting it or extract a pair of elements from the larger node.
3773 static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
3775 SmallVector<SDOperand, 32> &Ops,
3777 TargetLowering &TLI,
3778 bool isFirst = true) {
3780 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3781 // if it isn't first piece, alignment must be 1
3783 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3784 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3786 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3790 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3791 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3793 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3794 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
3795 } else if (NumVals == 2) {
3796 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3797 DAG.getConstant(0, TLI.getPointerTy()));
3798 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3799 DAG.getConstant(1, TLI.getPointerTy()));
3800 if (!TLI.isLittleEndian())
3802 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3803 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
3805 // Value scalarized into many values. Unimp for now.
3806 assert(0 && "Cannot expand i64 -> i16 yet!");
3810 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
3811 /// implementation, which just inserts an ISD::CALL node, which is later custom
3812 /// lowered by the target to something concrete. FIXME: When all targets are
3813 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3814 std::pair<SDOperand, SDOperand>
3815 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3816 bool RetTyIsSigned, bool isVarArg,
3817 unsigned CallingConv, bool isTailCall,
3819 ArgListTy &Args, SelectionDAG &DAG) {
3820 SmallVector<SDOperand, 32> Ops;
3821 Ops.push_back(Chain); // Op#0 - Chain
3822 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3823 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3824 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3825 Ops.push_back(Callee);
3827 // Handle all of the outgoing arguments.
3828 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3829 MVT::ValueType VT = getValueType(Args[i].Ty);
3830 SDOperand Op = Args[i].Node;
3831 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3832 unsigned OriginalAlignment =
3833 getTargetData()->getABITypeAlignment(Args[i].Ty);
3836 Flags |= ISD::ParamFlags::SExt;
3838 Flags |= ISD::ParamFlags::ZExt;
3839 if (Args[i].isInReg)
3840 Flags |= ISD::ParamFlags::InReg;
3842 Flags |= ISD::ParamFlags::StructReturn;
3843 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
3845 switch (getTypeAction(VT)) {
3846 default: assert(0 && "Unknown type action!");
3849 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3852 if (MVT::isInteger(VT)) {
3855 ExtOp = ISD::SIGN_EXTEND;
3856 else if (Args[i].isZExt)
3857 ExtOp = ISD::ZERO_EXTEND;
3859 ExtOp = ISD::ANY_EXTEND;
3860 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3862 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3863 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3866 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3869 if (VT != MVT::Vector) {
3870 // If this is a large integer, it needs to be broken down into small
3871 // integers. Figure out what the source elt type is and how many small
3873 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
3875 // Otherwise, this is a vector type. We only support legal vectors
3877 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
3878 unsigned NumElems = PTy->getNumElements();
3879 const Type *EltTy = PTy->getElementType();
3881 // Figure out if there is a Packed type corresponding to this Vector
3882 // type. If so, convert to the vector type.
3883 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3884 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3885 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
3886 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3888 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3890 assert(0 && "Don't support illegal by-val vector call args yet!");
3898 // Figure out the result value types.
3899 SmallVector<MVT::ValueType, 4> RetTys;
3901 if (RetTy != Type::VoidTy) {
3902 MVT::ValueType VT = getValueType(RetTy);
3903 switch (getTypeAction(VT)) {
3904 default: assert(0 && "Unknown type action!");
3906 RetTys.push_back(VT);
3909 RetTys.push_back(getTypeToTransformTo(VT));
3912 if (VT != MVT::Vector) {
3913 // If this is a large integer, it needs to be reassembled from small
3914 // integers. Figure out what the source elt type is and how many small
3916 MVT::ValueType NVT = getTypeToExpandTo(VT);
3917 unsigned NumVals = getNumElements(VT);
3918 for (unsigned i = 0; i != NumVals; ++i)
3919 RetTys.push_back(NVT);
3921 // Otherwise, this is a vector type. We only support legal vectors
3923 const VectorType *PTy = cast<VectorType>(RetTy);
3924 unsigned NumElems = PTy->getNumElements();
3925 const Type *EltTy = PTy->getElementType();
3927 // Figure out if there is a Packed type corresponding to this Vector
3928 // type. If so, convert to the vector type.
3929 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3930 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3931 RetTys.push_back(TVT);
3933 assert(0 && "Don't support illegal by-val vector call results yet!");
3940 RetTys.push_back(MVT::Other); // Always has a chain.
3942 // Finally, create the CALL node.
3943 SDOperand Res = DAG.getNode(ISD::CALL,
3944 DAG.getVTList(&RetTys[0], RetTys.size()),
3945 &Ops[0], Ops.size());
3947 // This returns a pair of operands. The first element is the
3948 // return value for the function (if RetTy is not VoidTy). The second
3949 // element is the outgoing token chain.
3951 if (RetTys.size() != 1) {
3952 MVT::ValueType VT = getValueType(RetTy);
3953 if (RetTys.size() == 2) {
3956 // If this value was promoted, truncate it down.
3957 if (ResVal.getValueType() != VT) {
3958 if (VT == MVT::Vector) {
3959 // Insert a VBIT_CONVERT to convert from the packed result type to the
3960 // MVT::Vector type.
3961 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3962 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
3964 // Figure out if there is a Packed type corresponding to this Vector
3965 // type. If so, convert to the vector type.
3966 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
3967 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3968 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3969 // "N x PTyElementVT" MVT::Vector type.
3970 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
3971 DAG.getConstant(NumElems, MVT::i32),
3972 DAG.getValueType(getValueType(EltTy)));
3976 } else if (MVT::isInteger(VT)) {
3977 unsigned AssertOp = ISD::AssertSext;
3979 AssertOp = ISD::AssertZext;
3980 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3981 DAG.getValueType(VT));
3982 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3984 assert(MVT::isFloatingPoint(VT));
3985 if (getTypeAction(VT) == Expand)
3986 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3988 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3991 } else if (RetTys.size() == 3) {
3992 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3993 Res.getValue(0), Res.getValue(1));
3996 assert(0 && "Case not handled yet!");
4000 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4003 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4004 assert(0 && "LowerOperation not implemented for this target!");
4009 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4010 SelectionDAG &DAG) {
4011 assert(0 && "CustomPromoteOperation not implemented for this target!");
4016 /// getMemsetValue - Vectorized representation of the memset value
4018 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
4019 SelectionDAG &DAG) {
4020 MVT::ValueType CurVT = VT;
4021 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4022 uint64_t Val = C->getValue() & 255;
4024 while (CurVT != MVT::i8) {
4025 Val = (Val << Shift) | Val;
4027 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4029 return DAG.getConstant(Val, VT);
4031 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4033 while (CurVT != MVT::i8) {
4035 DAG.getNode(ISD::OR, VT,
4036 DAG.getNode(ISD::SHL, VT, Value,
4037 DAG.getConstant(Shift, MVT::i8)), Value);
4039 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4046 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4047 /// used when a memcpy is turned into a memset when the source is a constant
4049 static SDOperand getMemsetStringVal(MVT::ValueType VT,
4050 SelectionDAG &DAG, TargetLowering &TLI,
4051 std::string &Str, unsigned Offset) {
4053 unsigned MSB = getSizeInBits(VT) / 8;
4054 if (TLI.isLittleEndian())
4055 Offset = Offset + MSB - 1;
4056 for (unsigned i = 0; i != MSB; ++i) {
4057 Val = (Val << 8) | (unsigned char)Str[Offset];
4058 Offset += TLI.isLittleEndian() ? -1 : 1;
4060 return DAG.getConstant(Val, VT);
4063 /// getMemBasePlusOffset - Returns base and offset node for the
4064 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4065 SelectionDAG &DAG, TargetLowering &TLI) {
4066 MVT::ValueType VT = Base.getValueType();
4067 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4070 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
4071 /// to replace the memset / memcpy is below the threshold. It also returns the
4072 /// types of the sequence of memory ops to perform memset / memcpy.
4073 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4074 unsigned Limit, uint64_t Size,
4075 unsigned Align, TargetLowering &TLI) {
4078 if (TLI.allowsUnalignedMemoryAccesses()) {
4081 switch (Align & 7) {
4097 MVT::ValueType LVT = MVT::i64;
4098 while (!TLI.isTypeLegal(LVT))
4099 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4100 assert(MVT::isInteger(LVT));
4105 unsigned NumMemOps = 0;
4107 unsigned VTSize = getSizeInBits(VT) / 8;
4108 while (VTSize > Size) {
4109 VT = (MVT::ValueType)((unsigned)VT - 1);
4112 assert(MVT::isInteger(VT));
4114 if (++NumMemOps > Limit)
4116 MemOps.push_back(VT);
4123 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
4124 SDOperand Op1 = getValue(I.getOperand(1));
4125 SDOperand Op2 = getValue(I.getOperand(2));
4126 SDOperand Op3 = getValue(I.getOperand(3));
4127 SDOperand Op4 = getValue(I.getOperand(4));
4128 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4129 if (Align == 0) Align = 1;
4131 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4132 std::vector<MVT::ValueType> MemOps;
4134 // Expand memset / memcpy to a series of load / store ops
4135 // if the size operand falls below a certain threshold.
4136 SmallVector<SDOperand, 8> OutChains;
4138 default: break; // Do nothing for now.
4140 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4141 Size->getValue(), Align, TLI)) {
4142 unsigned NumMemOps = MemOps.size();
4143 unsigned Offset = 0;
4144 for (unsigned i = 0; i < NumMemOps; i++) {
4145 MVT::ValueType VT = MemOps[i];
4146 unsigned VTSize = getSizeInBits(VT) / 8;
4147 SDOperand Value = getMemsetValue(Op2, VT, DAG);
4148 SDOperand Store = DAG.getStore(getRoot(), Value,
4149 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
4150 I.getOperand(1), Offset);
4151 OutChains.push_back(Store);
4158 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4159 Size->getValue(), Align, TLI)) {
4160 unsigned NumMemOps = MemOps.size();
4161 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
4162 GlobalAddressSDNode *G = NULL;
4164 bool CopyFromStr = false;
4166 if (Op2.getOpcode() == ISD::GlobalAddress)
4167 G = cast<GlobalAddressSDNode>(Op2);
4168 else if (Op2.getOpcode() == ISD::ADD &&
4169 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4170 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4171 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
4172 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
4175 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
4176 if (GV && GV->isConstant()) {
4177 Str = GV->getStringValue(false);
4185 for (unsigned i = 0; i < NumMemOps; i++) {
4186 MVT::ValueType VT = MemOps[i];
4187 unsigned VTSize = getSizeInBits(VT) / 8;
4188 SDOperand Value, Chain, Store;
4191 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4194 DAG.getStore(Chain, Value,
4195 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4196 I.getOperand(1), DstOff);
4198 Value = DAG.getLoad(VT, getRoot(),
4199 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
4200 I.getOperand(2), SrcOff);
4201 Chain = Value.getValue(1);
4203 DAG.getStore(Chain, Value,
4204 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4205 I.getOperand(1), DstOff);
4207 OutChains.push_back(Store);
4216 if (!OutChains.empty()) {
4217 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4218 &OutChains[0], OutChains.size()));
4223 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
4226 //===----------------------------------------------------------------------===//
4227 // SelectionDAGISel code
4228 //===----------------------------------------------------------------------===//
4230 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4231 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4234 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4235 AU.addRequired<AliasAnalysis>();
4236 AU.setPreservesAll();
4241 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4242 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4243 RegMap = MF.getSSARegMap();
4244 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4246 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4248 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4249 SelectBasicBlock(I, MF, FuncInfo);
4251 // Add function live-ins to entry block live-in set.
4252 BasicBlock *EntryBB = &Fn.getEntryBlock();
4253 BB = FuncInfo.MBBMap[EntryBB];
4254 if (!MF.livein_empty())
4255 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4256 E = MF.livein_end(); I != E; ++I)
4257 BB->addLiveIn(I->first);
4262 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4264 SDOperand Op = getValue(V);
4265 assert((Op.getOpcode() != ISD::CopyFromReg ||
4266 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4267 "Copy from a reg to the same reg!");
4269 // If this type is not legal, we must make sure to not create an invalid
4271 MVT::ValueType SrcVT = Op.getValueType();
4272 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
4273 if (SrcVT == DestVT) {
4274 return DAG.getCopyToReg(getRoot(), Reg, Op);
4275 } else if (SrcVT == MVT::Vector) {
4276 // Handle copies from generic vectors to registers.
4277 MVT::ValueType PTyElementVT, PTyLegalElementVT;
4278 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
4279 PTyElementVT, PTyLegalElementVT);
4281 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4282 // MVT::Vector type.
4283 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4284 DAG.getConstant(NE, MVT::i32),
4285 DAG.getValueType(PTyElementVT));
4287 // Loop over all of the elements of the resultant vector,
4288 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4289 // copying them into output registers.
4290 SmallVector<SDOperand, 8> OutChains;
4291 SDOperand Root = getRoot();
4292 for (unsigned i = 0; i != NE; ++i) {
4293 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
4294 Op, DAG.getConstant(i, TLI.getPointerTy()));
4295 if (PTyElementVT == PTyLegalElementVT) {
4296 // Elements are legal.
4297 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4298 } else if (PTyLegalElementVT > PTyElementVT) {
4299 // Elements are promoted.
4300 if (MVT::isFloatingPoint(PTyLegalElementVT))
4301 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4303 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4304 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4306 // Elements are expanded.
4307 // The src value is expanded into multiple registers.
4308 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
4309 Elt, DAG.getConstant(0, TLI.getPointerTy()));
4310 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
4311 Elt, DAG.getConstant(1, TLI.getPointerTy()));
4312 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4313 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4316 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4317 &OutChains[0], OutChains.size());
4318 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
4319 // The src value is promoted to the register.
4320 if (MVT::isFloatingPoint(SrcVT))
4321 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4323 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
4324 return DAG.getCopyToReg(getRoot(), Reg, Op);
4326 DestVT = TLI.getTypeToExpandTo(SrcVT);
4327 unsigned NumVals = TLI.getNumElements(SrcVT);
4329 return DAG.getCopyToReg(getRoot(), Reg,
4330 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4331 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
4332 // The src value is expanded into multiple registers.
4333 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4334 Op, DAG.getConstant(0, TLI.getPointerTy()));
4335 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4336 Op, DAG.getConstant(1, TLI.getPointerTy()));
4337 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
4338 return DAG.getCopyToReg(Op, Reg+1, Hi);
4342 void SelectionDAGISel::
4343 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
4344 std::vector<SDOperand> &UnorderedChains) {
4345 // If this is the entry block, emit arguments.
4346 Function &F = *LLVMBB->getParent();
4347 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4348 SDOperand OldRoot = SDL.DAG.getRoot();
4349 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4352 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4354 if (!AI->use_empty()) {
4355 SDL.setValue(AI, Args[a]);
4357 // If this argument is live outside of the entry block, insert a copy from
4358 // whereever we got it to the vreg that other BB's will reference it as.
4359 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4360 if (VMI != FuncInfo.ValueMap.end()) {
4361 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
4362 UnorderedChains.push_back(Copy);
4366 // Finally, if the target has anything special to do, allow it to do so.
4367 // FIXME: this should insert code into the DAG!
4368 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4371 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4372 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4373 FunctionLoweringInfo &FuncInfo) {
4374 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
4376 std::vector<SDOperand> UnorderedChains;
4378 // Lower any arguments needed in this block if this is the entry block.
4379 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4380 LowerArguments(LLVMBB, SDL, UnorderedChains);
4382 BB = FuncInfo.MBBMap[LLVMBB];
4383 SDL.setCurrentBasicBlock(BB);
4385 // Lower all of the non-terminator instructions.
4386 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4390 // Lower call part of invoke.
4391 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4392 if (Invoke) SDL.visitInvoke(*Invoke, false);
4394 // Ensure that all instructions which are used outside of their defining
4395 // blocks are available as virtual registers.
4396 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4397 if (!I->use_empty() && !isa<PHINode>(I)) {
4398 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4399 if (VMI != FuncInfo.ValueMap.end())
4400 UnorderedChains.push_back(
4401 SDL.CopyValueToVirtualRegister(I, VMI->second));
4404 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4405 // ensure constants are generated when needed. Remember the virtual registers
4406 // that need to be added to the Machine PHI nodes as input. We cannot just
4407 // directly add them, because expansion might result in multiple MBB's for one
4408 // BB. As such, the start of the BB might correspond to a different MBB than
4411 TerminatorInst *TI = LLVMBB->getTerminator();
4413 // Emit constants only once even if used by multiple PHI nodes.
4414 std::map<Constant*, unsigned> ConstantsOut;
4416 // Vector bool would be better, but vector<bool> is really slow.
4417 std::vector<unsigned char> SuccsHandled;
4418 if (TI->getNumSuccessors())
4419 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4421 // Check successor nodes PHI nodes that expect a constant to be available from
4423 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4424 BasicBlock *SuccBB = TI->getSuccessor(succ);
4425 if (!isa<PHINode>(SuccBB->begin())) continue;
4426 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4428 // If this terminator has multiple identical successors (common for
4429 // switches), only handle each succ once.
4430 unsigned SuccMBBNo = SuccMBB->getNumber();
4431 if (SuccsHandled[SuccMBBNo]) continue;
4432 SuccsHandled[SuccMBBNo] = true;
4434 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4437 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4438 // nodes and Machine PHI nodes, but the incoming operands have not been
4440 for (BasicBlock::iterator I = SuccBB->begin();
4441 (PN = dyn_cast<PHINode>(I)); ++I) {
4442 // Ignore dead phi's.
4443 if (PN->use_empty()) continue;
4446 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4448 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4449 unsigned &RegOut = ConstantsOut[C];
4451 RegOut = FuncInfo.CreateRegForValue(C);
4452 UnorderedChains.push_back(
4453 SDL.CopyValueToVirtualRegister(C, RegOut));
4457 Reg = FuncInfo.ValueMap[PHIOp];
4459 assert(isa<AllocaInst>(PHIOp) &&
4460 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4461 "Didn't codegen value into a register!??");
4462 Reg = FuncInfo.CreateRegForValue(PHIOp);
4463 UnorderedChains.push_back(
4464 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
4468 // Remember that this register needs to added to the machine PHI node as
4469 // the input for this MBB.
4470 MVT::ValueType VT = TLI.getValueType(PN->getType());
4471 unsigned NumElements;
4472 if (VT != MVT::Vector)
4473 NumElements = TLI.getNumElements(VT);
4475 MVT::ValueType VT1,VT2;
4477 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
4480 for (unsigned i = 0, e = NumElements; i != e; ++i)
4481 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4484 ConstantsOut.clear();
4486 // Turn all of the unordered chains into one factored node.
4487 if (!UnorderedChains.empty()) {
4488 SDOperand Root = SDL.getRoot();
4489 if (Root.getOpcode() != ISD::EntryToken) {
4490 unsigned i = 0, e = UnorderedChains.size();
4491 for (; i != e; ++i) {
4492 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4493 if (UnorderedChains[i].Val->getOperand(0) == Root)
4494 break; // Don't add the root if we already indirectly depend on it.
4498 UnorderedChains.push_back(Root);
4500 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4501 &UnorderedChains[0], UnorderedChains.size()));
4504 // Lower the terminator after the copies are emitted.
4506 // Just the branch part of invoke.
4507 SDL.visitInvoke(*Invoke, true);
4509 SDL.visit(*LLVMBB->getTerminator());
4512 // Copy over any CaseBlock records that may now exist due to SwitchInst
4513 // lowering, as well as any jump table information.
4514 SwitchCases.clear();
4515 SwitchCases = SDL.SwitchCases;
4517 JTCases = SDL.JTCases;
4518 BitTestCases.clear();
4519 BitTestCases = SDL.BitTestCases;
4521 // Make sure the root of the DAG is up-to-date.
4522 DAG.setRoot(SDL.getRoot());
4525 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4526 // Get alias analysis for load/store combining.
4527 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4529 // Run the DAG combiner in pre-legalize mode.
4530 DAG.Combine(false, AA);
4532 DOUT << "Lowered selection DAG:\n";
4535 // Second step, hack on the DAG until it only uses operations and types that
4536 // the target supports.
4539 DOUT << "Legalized selection DAG:\n";
4542 // Run the DAG combiner in post-legalize mode.
4543 DAG.Combine(true, AA);
4545 if (ViewISelDAGs) DAG.viewGraph();
4547 // Third, instruction select all of the operations to machine code, adding the
4548 // code to the MachineBasicBlock.
4549 InstructionSelectBasicBlock(DAG);
4551 DOUT << "Selected machine code:\n";
4555 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4556 FunctionLoweringInfo &FuncInfo) {
4557 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4559 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4562 // First step, lower LLVM code to some DAG. This DAG may use operations and
4563 // types that are not supported by the target.
4564 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4566 // Second step, emit the lowered DAG as machine code.
4567 CodeGenAndEmitDAG(DAG);
4570 DOUT << "Total amount of phi nodes to update: "
4571 << PHINodesToUpdate.size() << "\n";
4572 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4573 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4574 << ", " << PHINodesToUpdate[i].second << ")\n";);
4576 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4577 // PHI nodes in successors.
4578 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4579 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4580 MachineInstr *PHI = PHINodesToUpdate[i].first;
4581 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4582 "This is not a machine PHI node that we are updating!");
4583 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4584 PHI->addMachineBasicBlockOperand(BB);
4589 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4590 // Lower header first, if it wasn't already lowered
4591 if (!BitTestCases[i].Emitted) {
4592 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4594 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4595 // Set the current basic block to the mbb we wish to insert the code into
4596 BB = BitTestCases[i].Parent;
4597 HSDL.setCurrentBasicBlock(BB);
4599 HSDL.visitBitTestHeader(BitTestCases[i]);
4600 HSDAG.setRoot(HSDL.getRoot());
4601 CodeGenAndEmitDAG(HSDAG);
4604 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4605 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4607 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4608 // Set the current basic block to the mbb we wish to insert the code into
4609 BB = BitTestCases[i].Cases[j].ThisBB;
4610 BSDL.setCurrentBasicBlock(BB);
4613 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4614 BitTestCases[i].Reg,
4615 BitTestCases[i].Cases[j]);
4617 BSDL.visitBitTestCase(BitTestCases[i].Default,
4618 BitTestCases[i].Reg,
4619 BitTestCases[i].Cases[j]);
4622 BSDAG.setRoot(BSDL.getRoot());
4623 CodeGenAndEmitDAG(BSDAG);
4627 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4628 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4629 MachineBasicBlock *PHIBB = PHI->getParent();
4630 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4631 "This is not a machine PHI node that we are updating!");
4632 // This is "default" BB. We have two jumps to it. From "header" BB and
4633 // from last "case" BB.
4634 if (PHIBB == BitTestCases[i].Default) {
4635 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4636 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
4637 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4639 // One of "cases" BB.
4640 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4641 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4642 if (cBB->succ_end() !=
4643 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4644 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4645 PHI->addMachineBasicBlockOperand(cBB);
4651 // If the JumpTable record is filled in, then we need to emit a jump table.
4652 // Updating the PHI nodes is tricky in this case, since we need to determine
4653 // whether the PHI is a successor of the range check MBB or the jump table MBB
4654 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4655 // Lower header first, if it wasn't already lowered
4656 if (!JTCases[i].first.Emitted) {
4657 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4659 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4660 // Set the current basic block to the mbb we wish to insert the code into
4661 BB = JTCases[i].first.HeaderBB;
4662 HSDL.setCurrentBasicBlock(BB);
4664 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4665 HSDAG.setRoot(HSDL.getRoot());
4666 CodeGenAndEmitDAG(HSDAG);
4669 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4671 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
4672 // Set the current basic block to the mbb we wish to insert the code into
4673 BB = JTCases[i].second.MBB;
4674 JSDL.setCurrentBasicBlock(BB);
4676 JSDL.visitJumpTable(JTCases[i].second);
4677 JSDAG.setRoot(JSDL.getRoot());
4678 CodeGenAndEmitDAG(JSDAG);
4681 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4682 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4683 MachineBasicBlock *PHIBB = PHI->getParent();
4684 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4685 "This is not a machine PHI node that we are updating!");
4686 // "default" BB. We can go there only from header BB.
4687 if (PHIBB == JTCases[i].second.Default) {
4688 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4689 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
4691 // JT BB. Just iterate over successors here
4692 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4693 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4694 PHI->addMachineBasicBlockOperand(BB);
4699 // If the switch block involved a branch to one of the actual successors, we
4700 // need to update PHI nodes in that block.
4701 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4702 MachineInstr *PHI = PHINodesToUpdate[i].first;
4703 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4704 "This is not a machine PHI node that we are updating!");
4705 if (BB->isSuccessor(PHI->getParent())) {
4706 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4707 PHI->addMachineBasicBlockOperand(BB);
4711 // If we generated any switch lowering information, build and codegen any
4712 // additional DAGs necessary.
4713 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4714 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4716 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4718 // Set the current basic block to the mbb we wish to insert the code into
4719 BB = SwitchCases[i].ThisBB;
4720 SDL.setCurrentBasicBlock(BB);
4723 SDL.visitSwitchCase(SwitchCases[i]);
4724 SDAG.setRoot(SDL.getRoot());
4725 CodeGenAndEmitDAG(SDAG);
4727 // Handle any PHI nodes in successors of this chunk, as if we were coming
4728 // from the original BB before switch expansion. Note that PHI nodes can
4729 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4730 // handle them the right number of times.
4731 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4732 for (MachineBasicBlock::iterator Phi = BB->begin();
4733 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4734 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4735 for (unsigned pn = 0; ; ++pn) {
4736 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4737 if (PHINodesToUpdate[pn].first == Phi) {
4738 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4739 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4745 // Don't process RHS if same block as LHS.
4746 if (BB == SwitchCases[i].FalseBB)
4747 SwitchCases[i].FalseBB = 0;
4749 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4750 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4751 SwitchCases[i].FalseBB = 0;
4753 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4758 //===----------------------------------------------------------------------===//
4759 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4760 /// target node in the graph.
4761 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4762 if (ViewSchedDAGs) DAG.viewGraph();
4764 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4768 RegisterScheduler::setDefault(Ctor);
4771 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4777 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4778 return new HazardRecognizer();
4781 //===----------------------------------------------------------------------===//
4782 // Helper functions used by the generated instruction selector.
4783 //===----------------------------------------------------------------------===//
4784 // Calls to these methods are generated by tblgen.
4786 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
4787 /// the dag combiner simplified the 255, we still want to match. RHS is the
4788 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4789 /// specified in the .td file (e.g. 255).
4790 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4791 int64_t DesiredMaskS) {
4792 uint64_t ActualMask = RHS->getValue();
4793 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4795 // If the actual mask exactly matches, success!
4796 if (ActualMask == DesiredMask)
4799 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4800 if (ActualMask & ~DesiredMask)
4803 // Otherwise, the DAG Combiner may have proven that the value coming in is
4804 // either already zero or is not demanded. Check for known zero input bits.
4805 uint64_t NeededMask = DesiredMask & ~ActualMask;
4806 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4809 // TODO: check to see if missing bits are just not demanded.
4811 // Otherwise, this pattern doesn't match.
4815 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
4816 /// the dag combiner simplified the 255, we still want to match. RHS is the
4817 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4818 /// specified in the .td file (e.g. 255).
4819 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4820 int64_t DesiredMaskS) {
4821 uint64_t ActualMask = RHS->getValue();
4822 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4824 // If the actual mask exactly matches, success!
4825 if (ActualMask == DesiredMask)
4828 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4829 if (ActualMask & ~DesiredMask)
4832 // Otherwise, the DAG Combiner may have proven that the value coming in is
4833 // either already zero or is not demanded. Check for known zero input bits.
4834 uint64_t NeededMask = DesiredMask & ~ActualMask;
4836 uint64_t KnownZero, KnownOne;
4837 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4839 // If all the missing bits in the or are already known to be set, match!
4840 if ((NeededMask & KnownOne) == NeededMask)
4843 // TODO: check to see if missing bits are just not demanded.
4845 // Otherwise, this pattern doesn't match.
4850 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4851 /// by tblgen. Others should not call it.
4852 void SelectionDAGISel::
4853 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4854 std::vector<SDOperand> InOps;
4855 std::swap(InOps, Ops);
4857 Ops.push_back(InOps[0]); // input chain.
4858 Ops.push_back(InOps[1]); // input asm string.
4860 unsigned i = 2, e = InOps.size();
4861 if (InOps[e-1].getValueType() == MVT::Flag)
4862 --e; // Don't process a flag operand if it is here.
4865 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4866 if ((Flags & 7) != 4 /*MEM*/) {
4867 // Just skip over this operand, copying the operands verbatim.
4868 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4869 i += (Flags >> 3) + 1;
4871 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4872 // Otherwise, this is a memory operand. Ask the target to select it.
4873 std::vector<SDOperand> SelOps;
4874 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4875 cerr << "Could not match memory address. Inline asm failure!\n";
4879 // Add this to the output node.
4880 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4881 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4883 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4888 // Add the flag input back if present.
4889 if (e != InOps.size())
4890 Ops.push_back(InOps.back());