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/Analysis/AliasAnalysis.h"
16 #include "llvm/CodeGen/SelectionDAGISel.h"
17 #include "llvm/CodeGen/ScheduleDAG.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineDebugInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/SchedulerRegistry.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/CodeGen/SSARegMap.h"
36 #include "llvm/Target/MRegisterInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetFrameInfo.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/Compiler.h"
53 ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
56 ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
59 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
63 //===---------------------------------------------------------------------===//
65 /// RegisterScheduler class - Track the registration of instruction schedulers.
67 //===---------------------------------------------------------------------===//
68 MachinePassRegistry RegisterScheduler::Registry;
70 //===---------------------------------------------------------------------===//
72 /// ISHeuristic command line option for instruction schedulers.
74 //===---------------------------------------------------------------------===//
76 cl::opt<RegisterScheduler::FunctionPassCtor, false,
77 RegisterPassParser<RegisterScheduler> >
79 cl::init(&createDefaultScheduler),
80 cl::desc("Instruction schedulers available:"));
82 static RegisterScheduler
83 defaultListDAGScheduler("default", " Best scheduler for the target",
84 createDefaultScheduler);
88 /// RegsForValue - This struct represents the physical registers that a
89 /// particular value is assigned and the type information about the value.
90 /// This is needed because values can be promoted into larger registers and
91 /// expanded into multiple smaller registers than the value.
92 struct VISIBILITY_HIDDEN RegsForValue {
93 /// Regs - This list hold the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
96 std::vector<unsigned> Regs;
98 /// RegVT - The value type of each register.
100 MVT::ValueType RegVT;
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
112 RegsForValue(const std::vector<unsigned> ®s,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 SDOperand getCopyFromRegs(SelectionDAG &DAG,
121 SDOperand &Chain, SDOperand &Flag) const;
123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124 /// specified value into the registers specified by this object. This uses
125 /// Chain/Flag as the input and updates them for the output Chain/Flag.
126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
127 SDOperand &Chain, SDOperand &Flag,
128 MVT::ValueType PtrVT) const;
130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
131 /// operand list. This adds the code marker and includes the number of
132 /// values added into it.
133 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
134 std::vector<SDOperand> &Ops) const;
139 //===--------------------------------------------------------------------===//
140 /// createDefaultScheduler - This creates an instruction scheduler appropriate
142 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
144 MachineBasicBlock *BB) {
145 TargetLowering &TLI = IS->getTargetLowering();
147 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
148 return createTDListDAGScheduler(IS, DAG, BB);
150 assert(TLI.getSchedulingPreference() ==
151 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
152 return createBURRListDAGScheduler(IS, DAG, BB);
157 //===--------------------------------------------------------------------===//
158 /// FunctionLoweringInfo - This contains information that is global to a
159 /// function that is used when lowering a region of the function.
160 class FunctionLoweringInfo {
167 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
169 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
170 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
172 /// ValueMap - Since we emit code for the function a basic block at a time,
173 /// we must remember which virtual registers hold the values for
174 /// cross-basic-block values.
175 std::map<const Value*, unsigned> ValueMap;
177 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
178 /// the entry block. This allows the allocas to be efficiently referenced
179 /// anywhere in the function.
180 std::map<const AllocaInst*, int> StaticAllocaMap;
182 unsigned MakeReg(MVT::ValueType VT) {
183 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
186 /// isExportedInst - Return true if the specified value is an instruction
187 /// exported from its block.
188 bool isExportedInst(const Value *V) {
189 return ValueMap.count(V);
192 unsigned CreateRegForValue(const Value *V);
194 unsigned InitializeRegForValue(const Value *V) {
195 unsigned &R = ValueMap[V];
196 assert(R == 0 && "Already initialized this value register!");
197 return R = CreateRegForValue(V);
202 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
203 /// PHI nodes or outside of the basic block that defines it, or used by a
204 /// switch instruction, which may expand to multiple basic blocks.
205 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
206 if (isa<PHINode>(I)) return true;
207 BasicBlock *BB = I->getParent();
208 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
209 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
210 // FIXME: Remove switchinst special case.
211 isa<SwitchInst>(*UI))
216 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
217 /// entry block, return true. This includes arguments used by switches, since
218 /// the switch may expand into multiple basic blocks.
219 static bool isOnlyUsedInEntryBlock(Argument *A) {
220 BasicBlock *Entry = A->getParent()->begin();
221 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
222 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
223 return false; // Use not in entry block.
227 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
228 Function &fn, MachineFunction &mf)
229 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
231 // Create a vreg for each argument register that is not dead and is used
232 // outside of the entry block for the function.
233 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
235 if (!isOnlyUsedInEntryBlock(AI))
236 InitializeRegForValue(AI);
238 // Initialize the mapping of values to registers. This is only set up for
239 // instruction values that are used outside of the block that defines
241 Function::iterator BB = Fn.begin(), EB = Fn.end();
242 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
243 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
244 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
245 const Type *Ty = AI->getAllocatedType();
246 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
248 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
251 // If the alignment of the value is smaller than the size of the
252 // value, and if the size of the value is particularly small
253 // (<= 8 bytes), round up to the size of the value for potentially
254 // better performance.
256 // FIXME: This could be made better with a preferred alignment hook in
257 // TargetData. It serves primarily to 8-byte align doubles for X86.
258 if (Align < TySize && TySize <= 8) Align = TySize;
259 TySize *= CUI->getZExtValue(); // Get total allocated size.
260 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
261 StaticAllocaMap[AI] =
262 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
265 for (; BB != EB; ++BB)
266 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
267 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
268 if (!isa<AllocaInst>(I) ||
269 !StaticAllocaMap.count(cast<AllocaInst>(I)))
270 InitializeRegForValue(I);
272 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
273 // also creates the initial PHI MachineInstrs, though none of the input
274 // operands are populated.
275 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
276 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
278 MF.getBasicBlockList().push_back(MBB);
280 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
283 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
284 if (PN->use_empty()) continue;
286 MVT::ValueType VT = TLI.getValueType(PN->getType());
287 unsigned NumElements;
288 if (VT != MVT::Vector)
289 NumElements = TLI.getNumElements(VT);
291 MVT::ValueType VT1,VT2;
293 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
296 unsigned PHIReg = ValueMap[PN];
297 assert(PHIReg && "PHI node does not have an assigned virtual register!");
298 for (unsigned i = 0; i != NumElements; ++i)
299 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
304 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
305 /// the correctly promoted or expanded types. Assign these registers
306 /// consecutive vreg numbers and return the first assigned number.
307 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
308 MVT::ValueType VT = TLI.getValueType(V->getType());
310 // The number of multiples of registers that we need, to, e.g., split up
311 // a <2 x int64> -> 4 x i32 registers.
312 unsigned NumVectorRegs = 1;
314 // If this is a packed type, figure out what type it will decompose into
315 // and how many of the elements it will use.
316 if (VT == MVT::Vector) {
317 const PackedType *PTy = cast<PackedType>(V->getType());
318 unsigned NumElts = PTy->getNumElements();
319 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
321 // Divide the input until we get to a supported size. This will always
322 // end with a scalar if the target doesn't support vectors.
323 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
330 VT = getVectorType(EltTy, NumElts);
333 // The common case is that we will only create one register for this
334 // value. If we have that case, create and return the virtual register.
335 unsigned NV = TLI.getNumElements(VT);
337 // If we are promoting this value, pick the next largest supported type.
338 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
339 unsigned Reg = MakeReg(PromotedType);
340 // If this is a vector of supported or promoted types (e.g. 4 x i16),
341 // create all of the registers.
342 for (unsigned i = 1; i != NumVectorRegs; ++i)
343 MakeReg(PromotedType);
347 // If this value is represented with multiple target registers, make sure
348 // to create enough consecutive registers of the right (smaller) type.
349 unsigned NT = VT-1; // Find the type to use.
350 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
353 unsigned R = MakeReg((MVT::ValueType)NT);
354 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
355 MakeReg((MVT::ValueType)NT);
359 //===----------------------------------------------------------------------===//
360 /// SelectionDAGLowering - This is the common target-independent lowering
361 /// implementation that is parameterized by a TargetLowering object.
362 /// Also, targets can overload any lowering method.
365 class SelectionDAGLowering {
366 MachineBasicBlock *CurMBB;
368 std::map<const Value*, SDOperand> NodeMap;
370 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
371 /// them up and then emit token factor nodes when possible. This allows us to
372 /// get simple disambiguation between loads without worrying about alias
374 std::vector<SDOperand> PendingLoads;
376 /// Case - A pair of values to record the Value for a switch case, and the
377 /// case's target basic block.
378 typedef std::pair<Constant*, MachineBasicBlock*> Case;
379 typedef std::vector<Case>::iterator CaseItr;
380 typedef std::pair<CaseItr, CaseItr> CaseRange;
382 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
383 /// of conditional branches.
385 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
386 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
388 /// CaseBB - The MBB in which to emit the compare and branch
389 MachineBasicBlock *CaseBB;
390 /// LT, GE - If nonzero, we know the current case value must be less-than or
391 /// greater-than-or-equal-to these Constants.
394 /// Range - A pair of iterators representing the range of case values to be
395 /// processed at this point in the binary search tree.
399 /// The comparison function for sorting Case values.
401 bool operator () (const Case& C1, const Case& C2) {
402 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
403 if (I1->getType()->isUnsigned())
404 return I1->getZExtValue() <
405 cast<const ConstantInt>(C2.first)->getZExtValue();
407 return cast<const ConstantInt>(C1.first)->getSExtValue() <
408 cast<const ConstantInt>(C2.first)->getSExtValue();
413 // TLI - This is information that describes the available target features we
414 // need for lowering. This indicates when operations are unavailable,
415 // implemented with a libcall, etc.
418 const TargetData *TD;
420 /// SwitchCases - Vector of CaseBlock structures used to communicate
421 /// SwitchInst code generation information.
422 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
423 SelectionDAGISel::JumpTable JT;
425 /// FuncInfo - Information about the function as a whole.
427 FunctionLoweringInfo &FuncInfo;
429 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
430 FunctionLoweringInfo &funcinfo)
431 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
432 JT(0,0,0,0), FuncInfo(funcinfo) {
435 /// getRoot - Return the current virtual root of the Selection DAG.
437 SDOperand getRoot() {
438 if (PendingLoads.empty())
439 return DAG.getRoot();
441 if (PendingLoads.size() == 1) {
442 SDOperand Root = PendingLoads[0];
444 PendingLoads.clear();
448 // Otherwise, we have to make a token factor node.
449 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
450 &PendingLoads[0], PendingLoads.size());
451 PendingLoads.clear();
456 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
458 void visit(Instruction &I) { visit(I.getOpcode(), I); }
460 void visit(unsigned Opcode, User &I) {
462 default: assert(0 && "Unknown instruction type encountered!");
464 // Build the switch statement using the Instruction.def file.
465 #define HANDLE_INST(NUM, OPCODE, CLASS) \
466 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
467 #include "llvm/Instruction.def"
471 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
473 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
474 const Value *SV, SDOperand Root,
477 SDOperand getIntPtrConstant(uint64_t Val) {
478 return DAG.getConstant(Val, TLI.getPointerTy());
481 SDOperand getValue(const Value *V);
483 const SDOperand &setValue(const Value *V, SDOperand NewN) {
484 SDOperand &N = NodeMap[V];
485 assert(N.Val == 0 && "Already set a value for this node!");
489 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
491 bool OutReg, bool InReg,
492 std::set<unsigned> &OutputRegs,
493 std::set<unsigned> &InputRegs);
495 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
496 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
498 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
499 void ExportFromCurrentBlock(Value *V);
501 // Terminator instructions.
502 void visitRet(ReturnInst &I);
503 void visitBr(BranchInst &I);
504 void visitSwitch(SwitchInst &I);
505 void visitUnreachable(UnreachableInst &I) { /* noop */ }
507 // Helper for visitSwitch
508 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
509 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
511 // These all get lowered before this pass.
512 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
513 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
515 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
516 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
517 void visitShift(User &I, unsigned Opcode);
518 void visitAdd(User &I) {
519 if (I.getType()->isFloatingPoint())
520 visitFPBinary(I, ISD::FADD, ISD::VADD);
522 visitIntBinary(I, ISD::ADD, ISD::VADD);
524 void visitSub(User &I);
525 void visitMul(User &I) {
526 if (I.getType()->isFloatingPoint())
527 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
529 visitIntBinary(I, ISD::MUL, ISD::VMUL);
531 void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
532 void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
533 void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
534 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
535 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
536 void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
537 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
538 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
539 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
540 void visitShl(User &I) { visitShift(I, ISD::SHL); }
541 void visitShr(User &I) {
542 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
545 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
546 ISD::CondCode FPOpc);
547 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
549 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
551 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
553 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
555 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
557 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
560 void visitExtractElement(User &I);
561 void visitInsertElement(User &I);
562 void visitShuffleVector(User &I);
564 void visitGetElementPtr(User &I);
565 void visitCast(User &I);
566 void visitSelect(User &I);
568 void visitMalloc(MallocInst &I);
569 void visitFree(FreeInst &I);
570 void visitAlloca(AllocaInst &I);
571 void visitLoad(LoadInst &I);
572 void visitStore(StoreInst &I);
573 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
574 void visitCall(CallInst &I);
575 void visitInlineAsm(CallInst &I);
576 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
577 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
579 void visitVAStart(CallInst &I);
580 void visitVAArg(VAArgInst &I);
581 void visitVAEnd(CallInst &I);
582 void visitVACopy(CallInst &I);
583 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
585 void visitMemIntrinsic(CallInst &I, unsigned Op);
587 void visitUserOp1(Instruction &I) {
588 assert(0 && "UserOp1 should not exist at instruction selection time!");
591 void visitUserOp2(Instruction &I) {
592 assert(0 && "UserOp2 should not exist at instruction selection time!");
596 } // end namespace llvm
598 SDOperand SelectionDAGLowering::getValue(const Value *V) {
599 SDOperand &N = NodeMap[V];
602 const Type *VTy = V->getType();
603 MVT::ValueType VT = TLI.getValueType(VTy);
604 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
605 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
606 visit(CE->getOpcode(), *CE);
607 assert(N.Val && "visit didn't populate the ValueMap!");
609 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
610 return N = DAG.getGlobalAddress(GV, VT);
611 } else if (isa<ConstantPointerNull>(C)) {
612 return N = DAG.getConstant(0, TLI.getPointerTy());
613 } else if (isa<UndefValue>(C)) {
614 if (!isa<PackedType>(VTy))
615 return N = DAG.getNode(ISD::UNDEF, VT);
617 // Create a VBUILD_VECTOR of undef nodes.
618 const PackedType *PTy = cast<PackedType>(VTy);
619 unsigned NumElements = PTy->getNumElements();
620 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
622 SmallVector<SDOperand, 8> Ops;
623 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
625 // Create a VConstant node with generic Vector type.
626 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
627 Ops.push_back(DAG.getValueType(PVT));
628 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
629 &Ops[0], Ops.size());
630 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
631 return N = DAG.getConstantFP(CFP->getValue(), VT);
632 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
633 unsigned NumElements = PTy->getNumElements();
634 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
636 // Now that we know the number and type of the elements, push a
637 // Constant or ConstantFP node onto the ops list for each element of
638 // the packed constant.
639 SmallVector<SDOperand, 8> Ops;
640 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
641 for (unsigned i = 0; i != NumElements; ++i)
642 Ops.push_back(getValue(CP->getOperand(i)));
644 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
646 if (MVT::isFloatingPoint(PVT))
647 Op = DAG.getConstantFP(0, PVT);
649 Op = DAG.getConstant(0, PVT);
650 Ops.assign(NumElements, Op);
653 // Create a VBUILD_VECTOR node with generic Vector type.
654 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
655 Ops.push_back(DAG.getValueType(PVT));
656 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
658 // Canonicalize all constant ints to be unsigned.
659 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
663 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
664 std::map<const AllocaInst*, int>::iterator SI =
665 FuncInfo.StaticAllocaMap.find(AI);
666 if (SI != FuncInfo.StaticAllocaMap.end())
667 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
670 std::map<const Value*, unsigned>::const_iterator VMI =
671 FuncInfo.ValueMap.find(V);
672 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
674 unsigned InReg = VMI->second;
676 // If this type is not legal, make it so now.
677 if (VT != MVT::Vector) {
678 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
680 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
682 // Source must be expanded. This input value is actually coming from the
683 // register pair VMI->second and VMI->second+1.
684 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
685 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
686 } else if (DestVT > VT) { // Promotion case
687 if (MVT::isFloatingPoint(VT))
688 N = DAG.getNode(ISD::FP_ROUND, VT, N);
690 N = DAG.getNode(ISD::TRUNCATE, VT, N);
693 // Otherwise, if this is a vector, make it available as a generic vector
695 MVT::ValueType PTyElementVT, PTyLegalElementVT;
696 const PackedType *PTy = cast<PackedType>(VTy);
697 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
700 // Build a VBUILD_VECTOR with the input registers.
701 SmallVector<SDOperand, 8> Ops;
702 if (PTyElementVT == PTyLegalElementVT) {
703 // If the value types are legal, just VBUILD the CopyFromReg nodes.
704 for (unsigned i = 0; i != NE; ++i)
705 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
707 } else if (PTyElementVT < PTyLegalElementVT) {
708 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
709 for (unsigned i = 0; i != NE; ++i) {
710 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
712 if (MVT::isFloatingPoint(PTyElementVT))
713 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
715 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
719 // If the register was expanded, use BUILD_PAIR.
720 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
721 for (unsigned i = 0; i != NE/2; ++i) {
722 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
724 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
726 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
730 Ops.push_back(DAG.getConstant(NE, MVT::i32));
731 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
732 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
734 // Finally, use a VBIT_CONVERT to make this available as the appropriate
736 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
737 DAG.getConstant(PTy->getNumElements(),
739 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
746 void SelectionDAGLowering::visitRet(ReturnInst &I) {
747 if (I.getNumOperands() == 0) {
748 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
751 SmallVector<SDOperand, 8> NewValues;
752 NewValues.push_back(getRoot());
753 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
754 SDOperand RetOp = getValue(I.getOperand(i));
755 bool isSigned = I.getOperand(i)->getType()->isSigned();
757 // If this is an integer return value, we need to promote it ourselves to
758 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
760 // FIXME: C calling convention requires the return type to be promoted to
761 // at least 32-bit. But this is not necessary for non-C calling conventions.
762 if (MVT::isInteger(RetOp.getValueType()) &&
763 RetOp.getValueType() < MVT::i64) {
764 MVT::ValueType TmpVT;
765 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
766 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
771 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
773 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
775 NewValues.push_back(RetOp);
776 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
778 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
779 &NewValues[0], NewValues.size()));
782 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
783 /// the current basic block, add it to ValueMap now so that we'll get a
785 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
786 // No need to export constants.
787 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
790 if (FuncInfo.isExportedInst(V)) return;
792 unsigned Reg = FuncInfo.InitializeRegForValue(V);
793 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
796 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
797 const BasicBlock *FromBB) {
798 // The operands of the setcc have to be in this block. We don't know
799 // how to export them from some other block.
800 if (Instruction *VI = dyn_cast<Instruction>(V)) {
801 // Can export from current BB.
802 if (VI->getParent() == FromBB)
805 // Is already exported, noop.
806 return FuncInfo.isExportedInst(V);
809 // If this is an argument, we can export it if the BB is the entry block or
810 // if it is already exported.
811 if (isa<Argument>(V)) {
812 if (FromBB == &FromBB->getParent()->getEntryBlock())
815 // Otherwise, can only export this if it is already exported.
816 return FuncInfo.isExportedInst(V);
819 // Otherwise, constants can always be exported.
823 static bool InBlock(const Value *V, const BasicBlock *BB) {
824 if (const Instruction *I = dyn_cast<Instruction>(V))
825 return I->getParent() == BB;
829 /// FindMergedConditions - If Cond is an expression like
830 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
831 MachineBasicBlock *TBB,
832 MachineBasicBlock *FBB,
833 MachineBasicBlock *CurBB,
835 // If this node is not part of the or/and tree, emit it as a branch.
836 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
838 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
839 BOp->getParent() != CurBB->getBasicBlock() ||
840 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
841 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
842 const BasicBlock *BB = CurBB->getBasicBlock();
844 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
845 if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
846 II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
847 // The operands of the setcc have to be in this block. We don't know
848 // how to export them from some other block. If this is the first
849 // block of the sequence, no exporting is needed.
851 (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
852 isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
853 SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
854 II->getOperand(2), TBB, FBB, CurBB);
855 SwitchCases.push_back(CB);
860 // If the leaf of the tree is a setcond inst, merge the condition into the
862 if (BOp && isa<SetCondInst>(BOp) &&
863 // The operands of the setcc have to be in this block. We don't know
864 // how to export them from some other block. If this is the first block
865 // of the sequence, no exporting is needed.
867 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
868 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
869 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
870 switch (BOp->getOpcode()) {
871 default: assert(0 && "Unknown setcc opcode!");
872 case Instruction::SetEQ:
873 SignCond = ISD::SETEQ;
874 UnsCond = ISD::SETEQ;
875 FPCond = ISD::SETOEQ;
877 case Instruction::SetNE:
878 SignCond = ISD::SETNE;
879 UnsCond = ISD::SETNE;
880 FPCond = ISD::SETUNE;
882 case Instruction::SetLE:
883 SignCond = ISD::SETLE;
884 UnsCond = ISD::SETULE;
885 FPCond = ISD::SETOLE;
887 case Instruction::SetGE:
888 SignCond = ISD::SETGE;
889 UnsCond = ISD::SETUGE;
890 FPCond = ISD::SETOGE;
892 case Instruction::SetLT:
893 SignCond = ISD::SETLT;
894 UnsCond = ISD::SETULT;
895 FPCond = ISD::SETOLT;
897 case Instruction::SetGT:
898 SignCond = ISD::SETGT;
899 UnsCond = ISD::SETUGT;
900 FPCond = ISD::SETOGT;
904 const Type *OpType = BOp->getOperand(0)->getType();
905 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
906 OpType = PTy->getElementType();
908 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
910 else if (OpType->isUnsigned())
913 Condition = SignCond;
915 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
916 BOp->getOperand(1), TBB, FBB, CurBB);
917 SwitchCases.push_back(CB);
921 // Create a CaseBlock record representing this branch.
922 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
924 SwitchCases.push_back(CB);
929 // Create TmpBB after CurBB.
930 MachineFunction::iterator BBI = CurBB;
931 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
932 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
934 if (Opc == Instruction::Or) {
943 // Emit the LHS condition.
944 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
946 // Emit the RHS condition into TmpBB.
947 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
949 assert(Opc == Instruction::And && "Unknown merge op!");
957 // This requires creation of TmpBB after CurBB.
959 // Emit the LHS condition.
960 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
962 // Emit the RHS condition into TmpBB.
963 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
967 /// If the set of cases should be emitted as a series of branches, return true.
968 /// If we should emit this as a bunch of and/or'd together conditions, return
971 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
972 if (Cases.size() != 2) return true;
974 // If this is two comparisons of the same values or'd or and'd together, they
975 // will get folded into a single comparison, so don't emit two blocks.
976 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
977 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
978 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
979 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
986 void SelectionDAGLowering::visitBr(BranchInst &I) {
987 // Update machine-CFG edges.
988 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
990 // Figure out which block is immediately after the current one.
991 MachineBasicBlock *NextBlock = 0;
992 MachineFunction::iterator BBI = CurMBB;
993 if (++BBI != CurMBB->getParent()->end())
996 if (I.isUnconditional()) {
997 // If this is not a fall-through branch, emit the branch.
998 if (Succ0MBB != NextBlock)
999 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1000 DAG.getBasicBlock(Succ0MBB)));
1002 // Update machine-CFG edges.
1003 CurMBB->addSuccessor(Succ0MBB);
1008 // If this condition is one of the special cases we handle, do special stuff
1010 Value *CondVal = I.getCondition();
1011 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1013 // If this is a series of conditions that are or'd or and'd together, emit
1014 // this as a sequence of branches instead of setcc's with and/or operations.
1015 // For example, instead of something like:
1028 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1029 if (BOp->hasOneUse() &&
1030 (BOp->getOpcode() == Instruction::And ||
1031 BOp->getOpcode() == Instruction::Or)) {
1032 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1033 // If the compares in later blocks need to use values not currently
1034 // exported from this block, export them now. This block should always
1035 // be the first entry.
1036 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1038 // Allow some cases to be rejected.
1039 if (ShouldEmitAsBranches(SwitchCases)) {
1040 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1041 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1042 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1045 // Emit the branch for this block.
1046 visitSwitchCase(SwitchCases[0]);
1047 SwitchCases.erase(SwitchCases.begin());
1051 // Okay, we decided not to do this, remove any inserted MBB's and clear
1053 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1054 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1056 SwitchCases.clear();
1060 // Create a CaseBlock record representing this branch.
1061 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
1062 Succ0MBB, Succ1MBB, CurMBB);
1063 // Use visitSwitchCase to actually insert the fast branch sequence for this
1065 visitSwitchCase(CB);
1068 /// visitSwitchCase - Emits the necessary code to represent a single node in
1069 /// the binary search tree resulting from lowering a switch instruction.
1070 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1072 SDOperand CondLHS = getValue(CB.CmpLHS);
1074 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1075 // handle common cases produced by branch lowering.
1076 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
1078 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1079 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1080 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1082 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1084 // Set NextBlock to be the MBB immediately after the current one, if any.
1085 // This is used to avoid emitting unnecessary branches to the next block.
1086 MachineBasicBlock *NextBlock = 0;
1087 MachineFunction::iterator BBI = CurMBB;
1088 if (++BBI != CurMBB->getParent()->end())
1091 // If the lhs block is the next block, invert the condition so that we can
1092 // fall through to the lhs instead of the rhs block.
1093 if (CB.TrueBB == NextBlock) {
1094 std::swap(CB.TrueBB, CB.FalseBB);
1095 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1096 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1098 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1099 DAG.getBasicBlock(CB.TrueBB));
1100 if (CB.FalseBB == NextBlock)
1101 DAG.setRoot(BrCond);
1103 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1104 DAG.getBasicBlock(CB.FalseBB)));
1105 // Update successor info
1106 CurMBB->addSuccessor(CB.TrueBB);
1107 CurMBB->addSuccessor(CB.FalseBB);
1110 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1111 // Emit the code for the jump table
1112 MVT::ValueType PTy = TLI.getPointerTy();
1113 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1114 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1115 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1120 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1121 // Figure out which block is immediately after the current one.
1122 MachineBasicBlock *NextBlock = 0;
1123 MachineFunction::iterator BBI = CurMBB;
1125 if (++BBI != CurMBB->getParent()->end())
1128 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1130 // If there is only the default destination, branch to it if it is not the
1131 // next basic block. Otherwise, just fall through.
1132 if (I.getNumOperands() == 2) {
1133 // Update machine-CFG edges.
1135 // If this is not a fall-through branch, emit the branch.
1136 if (Default != NextBlock)
1137 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1138 DAG.getBasicBlock(Default)));
1140 CurMBB->addSuccessor(Default);
1144 // If there are any non-default case statements, create a vector of Cases
1145 // representing each one, and sort the vector so that we can efficiently
1146 // create a binary search tree from them.
1147 std::vector<Case> Cases;
1149 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1150 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1151 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1154 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1156 // Get the Value to be switched on and default basic blocks, which will be
1157 // inserted into CaseBlock records, representing basic blocks in the binary
1159 Value *SV = I.getOperand(0);
1161 // Get the MachineFunction which holds the current MBB. This is used during
1162 // emission of jump tables, and when inserting any additional MBBs necessary
1163 // to represent the switch.
1164 MachineFunction *CurMF = CurMBB->getParent();
1165 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
1167 // If the switch has few cases (two or less) emit a series of specific
1169 if (Cases.size() < 3) {
1170 // TODO: If any two of the cases has the same destination, and if one value
1171 // is the same as the other, but has one bit unset that the other has set,
1172 // use bit manipulation to do two compares at once. For example:
1173 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1175 // Rearrange the case blocks so that the last one falls through if possible.
1176 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1177 // The last case block won't fall through into 'NextBlock' if we emit the
1178 // branches in this order. See if rearranging a case value would help.
1179 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1180 if (Cases[i].second == NextBlock) {
1181 std::swap(Cases[i], Cases.back());
1187 // Create a CaseBlock record representing a conditional branch to
1188 // the Case's target mbb if the value being switched on SV is equal
1190 MachineBasicBlock *CurBlock = CurMBB;
1191 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1192 MachineBasicBlock *FallThrough;
1194 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1195 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1197 // If the last case doesn't match, go to the default block.
1198 FallThrough = Default;
1201 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1202 Cases[i].second, FallThrough, CurBlock);
1204 // If emitting the first comparison, just call visitSwitchCase to emit the
1205 // code into the current block. Otherwise, push the CaseBlock onto the
1206 // vector to be later processed by SDISel, and insert the node's MBB
1207 // before the next MBB.
1208 if (CurBlock == CurMBB)
1209 visitSwitchCase(CB);
1211 SwitchCases.push_back(CB);
1213 CurBlock = FallThrough;
1218 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1219 // target supports indirect branches, then emit a jump table rather than
1220 // lowering the switch to a binary tree of conditional branches.
1221 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1222 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
1224 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1225 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
1226 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1228 if (Density >= 0.3125) {
1229 // Create a new basic block to hold the code for loading the address
1230 // of the jump table, and jumping to it. Update successor information;
1231 // we will either branch to the default case for the switch, or the jump
1233 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1234 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1235 CurMBB->addSuccessor(Default);
1236 CurMBB->addSuccessor(JumpTableBB);
1238 // Subtract the lowest switch case value from the value being switched on
1239 // and conditional branch to default mbb if the result is greater than the
1240 // difference between smallest and largest cases.
1241 SDOperand SwitchOp = getValue(SV);
1242 MVT::ValueType VT = SwitchOp.getValueType();
1243 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1244 DAG.getConstant(First, VT));
1246 // The SDNode we just created, which holds the value being switched on
1247 // minus the the smallest case value, needs to be copied to a virtual
1248 // register so it can be used as an index into the jump table in a
1249 // subsequent basic block. This value may be smaller or larger than the
1250 // target's pointer type, and therefore require extension or truncating.
1251 if (VT > TLI.getPointerTy())
1252 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1254 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1256 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1257 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1259 // Emit the range check for the jump table, and branch to the default
1260 // block for the switch statement if the value being switched on exceeds
1261 // the largest case in the switch.
1262 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1263 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1264 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1265 DAG.getBasicBlock(Default)));
1267 // Build a vector of destination BBs, corresponding to each target
1268 // of the jump table. If the value of the jump table slot corresponds to
1269 // a case statement, push the case's BB onto the vector, otherwise, push
1271 std::vector<MachineBasicBlock*> DestBBs;
1272 uint64_t TEI = First;
1273 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
1274 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
1275 DestBBs.push_back(ii->second);
1278 DestBBs.push_back(Default);
1281 // Update successor info. Add one edge to each unique successor.
1282 // Vector bool would be better, but vector<bool> is really slow.
1283 std::vector<unsigned char> SuccsHandled;
1284 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1286 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1287 E = DestBBs.end(); I != E; ++I) {
1288 if (!SuccsHandled[(*I)->getNumber()]) {
1289 SuccsHandled[(*I)->getNumber()] = true;
1290 JumpTableBB->addSuccessor(*I);
1294 // Create a jump table index for this jump table, or return an existing
1296 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1298 // Set the jump table information so that we can codegen it as a second
1299 // MachineBasicBlock
1300 JT.Reg = JumpTableReg;
1302 JT.MBB = JumpTableBB;
1303 JT.Default = Default;
1308 // Push the initial CaseRec onto the worklist
1309 std::vector<CaseRec> CaseVec;
1310 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1312 while (!CaseVec.empty()) {
1313 // Grab a record representing a case range to process off the worklist
1314 CaseRec CR = CaseVec.back();
1317 // Size is the number of Cases represented by this range. If Size is 1,
1318 // then we are processing a leaf of the binary search tree. Otherwise,
1319 // we need to pick a pivot, and push left and right ranges onto the
1321 unsigned Size = CR.Range.second - CR.Range.first;
1324 // Create a CaseBlock record representing a conditional branch to
1325 // the Case's target mbb if the value being switched on SV is equal
1326 // to C. Otherwise, branch to default.
1327 Constant *C = CR.Range.first->first;
1328 MachineBasicBlock *Target = CR.Range.first->second;
1329 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1332 // If the MBB representing the leaf node is the current MBB, then just
1333 // call visitSwitchCase to emit the code into the current block.
1334 // Otherwise, push the CaseBlock onto the vector to be later processed
1335 // by SDISel, and insert the node's MBB before the next MBB.
1336 if (CR.CaseBB == CurMBB)
1337 visitSwitchCase(CB);
1339 SwitchCases.push_back(CB);
1341 // split case range at pivot
1342 CaseItr Pivot = CR.Range.first + (Size / 2);
1343 CaseRange LHSR(CR.Range.first, Pivot);
1344 CaseRange RHSR(Pivot, CR.Range.second);
1345 Constant *C = Pivot->first;
1346 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1348 // We know that we branch to the LHS if the Value being switched on is
1349 // less than the Pivot value, C. We use this to optimize our binary
1350 // tree a bit, by recognizing that if SV is greater than or equal to the
1351 // LHS's Case Value, and that Case Value is exactly one less than the
1352 // Pivot's Value, then we can branch directly to the LHS's Target,
1353 // rather than creating a leaf node for it.
1354 if ((LHSR.second - LHSR.first) == 1 &&
1355 LHSR.first->first == CR.GE &&
1356 cast<ConstantIntegral>(C)->getZExtValue() ==
1357 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
1358 TrueBB = LHSR.first->second;
1360 TrueBB = new MachineBasicBlock(LLVMBB);
1361 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1362 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1365 // Similar to the optimization above, if the Value being switched on is
1366 // known to be less than the Constant CR.LT, and the current Case Value
1367 // is CR.LT - 1, then we can branch directly to the target block for
1368 // the current Case Value, rather than emitting a RHS leaf node for it.
1369 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1370 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1371 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
1372 FalseBB = RHSR.first->second;
1374 FalseBB = new MachineBasicBlock(LLVMBB);
1375 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1376 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1379 // Create a CaseBlock record representing a conditional branch to
1380 // the LHS node if the value being switched on SV is less than C.
1381 // Otherwise, branch to LHS.
1382 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1383 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
1385 if (CR.CaseBB == CurMBB)
1386 visitSwitchCase(CB);
1388 SwitchCases.push_back(CB);
1393 void SelectionDAGLowering::visitSub(User &I) {
1394 // -0.0 - X --> fneg
1395 if (I.getType()->isFloatingPoint()) {
1396 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1397 if (CFP->isExactlyValue(-0.0)) {
1398 SDOperand Op2 = getValue(I.getOperand(1));
1399 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1402 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1404 visitIntBinary(I, ISD::SUB, ISD::VSUB);
1408 SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
1409 const Type *Ty = I.getType();
1410 SDOperand Op1 = getValue(I.getOperand(0));
1411 SDOperand Op2 = getValue(I.getOperand(1));
1413 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1414 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1415 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1416 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1418 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1423 SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1424 const Type *Ty = I.getType();
1425 SDOperand Op1 = getValue(I.getOperand(0));
1426 SDOperand Op2 = getValue(I.getOperand(1));
1428 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1429 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1430 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1431 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1433 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1437 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1438 SDOperand Op1 = getValue(I.getOperand(0));
1439 SDOperand Op2 = getValue(I.getOperand(1));
1441 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1443 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1446 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
1447 ISD::CondCode UnsignedOpcode,
1448 ISD::CondCode FPOpcode) {
1449 SDOperand Op1 = getValue(I.getOperand(0));
1450 SDOperand Op2 = getValue(I.getOperand(1));
1451 ISD::CondCode Opcode = SignedOpcode;
1452 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
1454 else if (I.getOperand(0)->getType()->isUnsigned())
1455 Opcode = UnsignedOpcode;
1456 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1459 void SelectionDAGLowering::visitSelect(User &I) {
1460 SDOperand Cond = getValue(I.getOperand(0));
1461 SDOperand TrueVal = getValue(I.getOperand(1));
1462 SDOperand FalseVal = getValue(I.getOperand(2));
1463 if (!isa<PackedType>(I.getType())) {
1464 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1465 TrueVal, FalseVal));
1467 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1468 *(TrueVal.Val->op_end()-2),
1469 *(TrueVal.Val->op_end()-1)));
1473 void SelectionDAGLowering::visitCast(User &I) {
1474 SDOperand N = getValue(I.getOperand(0));
1475 MVT::ValueType SrcVT = N.getValueType();
1476 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1478 if (DestVT == MVT::Vector) {
1479 // This is a cast to a vector from something else. This is always a bit
1480 // convert. Get information about the input vector.
1481 const PackedType *DestTy = cast<PackedType>(I.getType());
1482 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1483 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1484 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1485 DAG.getValueType(EltVT)));
1486 } else if (SrcVT == DestVT) {
1487 setValue(&I, N); // noop cast.
1488 } else if (DestVT == MVT::i1) {
1489 // Cast to bool is a comparison against zero, not truncation to zero.
1490 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
1491 DAG.getConstantFP(0.0, N.getValueType());
1492 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
1493 } else if (isInteger(SrcVT)) {
1494 if (isInteger(DestVT)) { // Int -> Int cast
1495 if (DestVT < SrcVT) // Truncating cast?
1496 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1497 else if (I.getOperand(0)->getType()->isSigned())
1498 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1500 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1501 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
1502 if (I.getOperand(0)->getType()->isSigned())
1503 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1505 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1507 assert(0 && "Unknown cast!");
1509 } else if (isFloatingPoint(SrcVT)) {
1510 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1511 if (DestVT < SrcVT) // Rounding cast?
1512 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1514 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1515 } else if (isInteger(DestVT)) { // FP -> Int cast.
1516 if (I.getType()->isSigned())
1517 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1519 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1521 assert(0 && "Unknown cast!");
1524 assert(SrcVT == MVT::Vector && "Unknown cast!");
1525 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1526 // This is a cast from a vector to something else. This is always a bit
1527 // convert. Get information about the input vector.
1528 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1532 void SelectionDAGLowering::visitInsertElement(User &I) {
1533 SDOperand InVec = getValue(I.getOperand(0));
1534 SDOperand InVal = getValue(I.getOperand(1));
1535 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1536 getValue(I.getOperand(2)));
1538 SDOperand Num = *(InVec.Val->op_end()-2);
1539 SDOperand Typ = *(InVec.Val->op_end()-1);
1540 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1541 InVec, InVal, InIdx, Num, Typ));
1544 void SelectionDAGLowering::visitExtractElement(User &I) {
1545 SDOperand InVec = getValue(I.getOperand(0));
1546 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1547 getValue(I.getOperand(1)));
1548 SDOperand Typ = *(InVec.Val->op_end()-1);
1549 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1550 TLI.getValueType(I.getType()), InVec, InIdx));
1553 void SelectionDAGLowering::visitShuffleVector(User &I) {
1554 SDOperand V1 = getValue(I.getOperand(0));
1555 SDOperand V2 = getValue(I.getOperand(1));
1556 SDOperand Mask = getValue(I.getOperand(2));
1558 SDOperand Num = *(V1.Val->op_end()-2);
1559 SDOperand Typ = *(V2.Val->op_end()-1);
1560 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1561 V1, V2, Mask, Num, Typ));
1565 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1566 SDOperand N = getValue(I.getOperand(0));
1567 const Type *Ty = I.getOperand(0)->getType();
1569 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1572 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1573 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
1576 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1577 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1578 getIntPtrConstant(Offset));
1580 Ty = StTy->getElementType(Field);
1582 Ty = cast<SequentialType>(Ty)->getElementType();
1584 // If this is a constant subscript, handle it quickly.
1585 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1586 if (CI->getZExtValue() == 0) continue;
1588 if (CI->getType()->isSigned())
1590 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
1593 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
1594 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1598 // N = N + Idx * ElementSize;
1599 uint64_t ElementSize = TD->getTypeSize(Ty);
1600 SDOperand IdxN = getValue(Idx);
1602 // If the index is smaller or larger than intptr_t, truncate or extend
1604 if (IdxN.getValueType() < N.getValueType()) {
1605 if (Idx->getType()->isSigned())
1606 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1608 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1609 } else if (IdxN.getValueType() > N.getValueType())
1610 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1612 // If this is a multiply by a power of two, turn it into a shl
1613 // immediately. This is a very common case.
1614 if (isPowerOf2_64(ElementSize)) {
1615 unsigned Amt = Log2_64(ElementSize);
1616 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1617 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1618 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1622 SDOperand Scale = getIntPtrConstant(ElementSize);
1623 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1624 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1630 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1631 // If this is a fixed sized alloca in the entry block of the function,
1632 // allocate it statically on the stack.
1633 if (FuncInfo.StaticAllocaMap.count(&I))
1634 return; // getValue will auto-populate this.
1636 const Type *Ty = I.getAllocatedType();
1637 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1638 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
1641 SDOperand AllocSize = getValue(I.getArraySize());
1642 MVT::ValueType IntPtr = TLI.getPointerTy();
1643 if (IntPtr < AllocSize.getValueType())
1644 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1645 else if (IntPtr > AllocSize.getValueType())
1646 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1648 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1649 getIntPtrConstant(TySize));
1651 // Handle alignment. If the requested alignment is less than or equal to the
1652 // stack alignment, ignore it and round the size of the allocation up to the
1653 // stack alignment size. If the size is greater than the stack alignment, we
1654 // note this in the DYNAMIC_STACKALLOC node.
1655 unsigned StackAlign =
1656 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1657 if (Align <= StackAlign) {
1659 // Add SA-1 to the size.
1660 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1661 getIntPtrConstant(StackAlign-1));
1662 // Mask out the low bits for alignment purposes.
1663 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1664 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1667 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
1668 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1670 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
1671 DAG.setRoot(setValue(&I, DSA).getValue(1));
1673 // Inform the Frame Information that we have just allocated a variable-sized
1675 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1678 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1679 SDOperand Ptr = getValue(I.getOperand(0));
1685 // Do not serialize non-volatile loads against each other.
1686 Root = DAG.getRoot();
1689 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
1690 Root, I.isVolatile()));
1693 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1694 const Value *SV, SDOperand Root,
1697 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1698 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1699 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1700 DAG.getSrcValue(SV));
1702 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
1706 DAG.setRoot(L.getValue(1));
1708 PendingLoads.push_back(L.getValue(1));
1714 void SelectionDAGLowering::visitStore(StoreInst &I) {
1715 Value *SrcV = I.getOperand(0);
1716 SDOperand Src = getValue(SrcV);
1717 SDOperand Ptr = getValue(I.getOperand(1));
1718 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1722 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1723 /// access memory and has no other side effects at all.
1724 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1725 #define GET_NO_MEMORY_INTRINSICS
1726 #include "llvm/Intrinsics.gen"
1727 #undef GET_NO_MEMORY_INTRINSICS
1731 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1732 // have any side-effects or if it only reads memory.
1733 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1734 #define GET_SIDE_EFFECT_INFO
1735 #include "llvm/Intrinsics.gen"
1736 #undef GET_SIDE_EFFECT_INFO
1740 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1742 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1743 unsigned Intrinsic) {
1744 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1745 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1747 // Build the operand list.
1748 SmallVector<SDOperand, 8> Ops;
1749 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1751 // We don't need to serialize loads against other loads.
1752 Ops.push_back(DAG.getRoot());
1754 Ops.push_back(getRoot());
1758 // Add the intrinsic ID as an integer operand.
1759 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1761 // Add all operands of the call to the operand list.
1762 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1763 SDOperand Op = getValue(I.getOperand(i));
1765 // If this is a vector type, force it to the right packed type.
1766 if (Op.getValueType() == MVT::Vector) {
1767 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1768 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1770 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1771 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1772 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1775 assert(TLI.isTypeLegal(Op.getValueType()) &&
1776 "Intrinsic uses a non-legal type?");
1780 std::vector<MVT::ValueType> VTs;
1781 if (I.getType() != Type::VoidTy) {
1782 MVT::ValueType VT = TLI.getValueType(I.getType());
1783 if (VT == MVT::Vector) {
1784 const PackedType *DestTy = cast<PackedType>(I.getType());
1785 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1787 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1788 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1791 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1795 VTs.push_back(MVT::Other);
1797 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1802 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1803 &Ops[0], Ops.size());
1804 else if (I.getType() != Type::VoidTy)
1805 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1806 &Ops[0], Ops.size());
1808 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1809 &Ops[0], Ops.size());
1812 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1814 PendingLoads.push_back(Chain);
1818 if (I.getType() != Type::VoidTy) {
1819 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1820 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1821 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1822 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1823 DAG.getValueType(EVT));
1825 setValue(&I, Result);
1829 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1830 /// we want to emit this as a call to a named external function, return the name
1831 /// otherwise lower it and return null.
1833 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1834 switch (Intrinsic) {
1836 // By default, turn this into a target intrinsic node.
1837 visitTargetIntrinsic(I, Intrinsic);
1839 case Intrinsic::vastart: visitVAStart(I); return 0;
1840 case Intrinsic::vaend: visitVAEnd(I); return 0;
1841 case Intrinsic::vacopy: visitVACopy(I); return 0;
1842 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1843 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1844 case Intrinsic::setjmp:
1845 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1847 case Intrinsic::longjmp:
1848 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1850 case Intrinsic::memcpy_i32:
1851 case Intrinsic::memcpy_i64:
1852 visitMemIntrinsic(I, ISD::MEMCPY);
1854 case Intrinsic::memset_i32:
1855 case Intrinsic::memset_i64:
1856 visitMemIntrinsic(I, ISD::MEMSET);
1858 case Intrinsic::memmove_i32:
1859 case Intrinsic::memmove_i64:
1860 visitMemIntrinsic(I, ISD::MEMMOVE);
1863 case Intrinsic::dbg_stoppoint: {
1864 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1865 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1866 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1870 Ops[1] = getValue(SPI.getLineValue());
1871 Ops[2] = getValue(SPI.getColumnValue());
1873 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1874 assert(DD && "Not a debug information descriptor");
1875 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1877 Ops[3] = DAG.getString(CompileUnit->getFileName());
1878 Ops[4] = DAG.getString(CompileUnit->getDirectory());
1880 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
1885 case Intrinsic::dbg_region_start: {
1886 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1887 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1888 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1889 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1890 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1891 DAG.getConstant(LabelID, MVT::i32)));
1896 case Intrinsic::dbg_region_end: {
1897 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1898 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1899 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1900 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1901 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1902 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
1907 case Intrinsic::dbg_func_start: {
1908 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1909 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1910 if (DebugInfo && FSI.getSubprogram() &&
1911 DebugInfo->Verify(FSI.getSubprogram())) {
1912 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1913 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1914 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
1919 case Intrinsic::dbg_declare: {
1920 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1921 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1922 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1923 SDOperand AddressOp = getValue(DI.getAddress());
1924 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
1925 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1931 case Intrinsic::isunordered_f32:
1932 case Intrinsic::isunordered_f64:
1933 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1934 getValue(I.getOperand(2)), ISD::SETUO));
1937 case Intrinsic::sqrt_f32:
1938 case Intrinsic::sqrt_f64:
1939 setValue(&I, DAG.getNode(ISD::FSQRT,
1940 getValue(I.getOperand(1)).getValueType(),
1941 getValue(I.getOperand(1))));
1943 case Intrinsic::powi_f32:
1944 case Intrinsic::powi_f64:
1945 setValue(&I, DAG.getNode(ISD::FPOWI,
1946 getValue(I.getOperand(1)).getValueType(),
1947 getValue(I.getOperand(1)),
1948 getValue(I.getOperand(2))));
1950 case Intrinsic::pcmarker: {
1951 SDOperand Tmp = getValue(I.getOperand(1));
1952 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1955 case Intrinsic::readcyclecounter: {
1956 SDOperand Op = getRoot();
1957 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1958 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1961 DAG.setRoot(Tmp.getValue(1));
1964 case Intrinsic::bswap_i16:
1965 case Intrinsic::bswap_i32:
1966 case Intrinsic::bswap_i64:
1967 setValue(&I, DAG.getNode(ISD::BSWAP,
1968 getValue(I.getOperand(1)).getValueType(),
1969 getValue(I.getOperand(1))));
1971 case Intrinsic::cttz_i8:
1972 case Intrinsic::cttz_i16:
1973 case Intrinsic::cttz_i32:
1974 case Intrinsic::cttz_i64:
1975 setValue(&I, DAG.getNode(ISD::CTTZ,
1976 getValue(I.getOperand(1)).getValueType(),
1977 getValue(I.getOperand(1))));
1979 case Intrinsic::ctlz_i8:
1980 case Intrinsic::ctlz_i16:
1981 case Intrinsic::ctlz_i32:
1982 case Intrinsic::ctlz_i64:
1983 setValue(&I, DAG.getNode(ISD::CTLZ,
1984 getValue(I.getOperand(1)).getValueType(),
1985 getValue(I.getOperand(1))));
1987 case Intrinsic::ctpop_i8:
1988 case Intrinsic::ctpop_i16:
1989 case Intrinsic::ctpop_i32:
1990 case Intrinsic::ctpop_i64:
1991 setValue(&I, DAG.getNode(ISD::CTPOP,
1992 getValue(I.getOperand(1)).getValueType(),
1993 getValue(I.getOperand(1))));
1995 case Intrinsic::stacksave: {
1996 SDOperand Op = getRoot();
1997 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1998 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2000 DAG.setRoot(Tmp.getValue(1));
2003 case Intrinsic::stackrestore: {
2004 SDOperand Tmp = getValue(I.getOperand(1));
2005 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2008 case Intrinsic::prefetch:
2009 // FIXME: Currently discarding prefetches.
2015 void SelectionDAGLowering::visitCall(CallInst &I) {
2016 const char *RenameFn = 0;
2017 if (Function *F = I.getCalledFunction()) {
2018 if (F->isExternal())
2019 if (unsigned IID = F->getIntrinsicID()) {
2020 RenameFn = visitIntrinsicCall(I, IID);
2023 } else { // Not an LLVM intrinsic.
2024 const std::string &Name = F->getName();
2025 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2026 if (I.getNumOperands() == 3 && // Basic sanity checks.
2027 I.getOperand(1)->getType()->isFloatingPoint() &&
2028 I.getType() == I.getOperand(1)->getType() &&
2029 I.getType() == I.getOperand(2)->getType()) {
2030 SDOperand LHS = getValue(I.getOperand(1));
2031 SDOperand RHS = getValue(I.getOperand(2));
2032 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2036 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2037 if (I.getNumOperands() == 2 && // Basic sanity checks.
2038 I.getOperand(1)->getType()->isFloatingPoint() &&
2039 I.getType() == I.getOperand(1)->getType()) {
2040 SDOperand Tmp = getValue(I.getOperand(1));
2041 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2044 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2045 if (I.getNumOperands() == 2 && // Basic sanity checks.
2046 I.getOperand(1)->getType()->isFloatingPoint() &&
2047 I.getType() == I.getOperand(1)->getType()) {
2048 SDOperand Tmp = getValue(I.getOperand(1));
2049 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2052 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2053 if (I.getNumOperands() == 2 && // Basic sanity checks.
2054 I.getOperand(1)->getType()->isFloatingPoint() &&
2055 I.getType() == I.getOperand(1)->getType()) {
2056 SDOperand Tmp = getValue(I.getOperand(1));
2057 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2062 } else if (isa<InlineAsm>(I.getOperand(0))) {
2069 Callee = getValue(I.getOperand(0));
2071 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2072 std::vector<std::pair<SDOperand, const Type*> > Args;
2073 Args.reserve(I.getNumOperands());
2074 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2075 Value *Arg = I.getOperand(i);
2076 SDOperand ArgNode = getValue(Arg);
2077 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2080 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2081 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2083 std::pair<SDOperand,SDOperand> Result =
2084 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
2085 I.isTailCall(), Callee, Args, DAG);
2086 if (I.getType() != Type::VoidTy)
2087 setValue(&I, Result.first);
2088 DAG.setRoot(Result.second);
2091 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2092 SDOperand &Chain, SDOperand &Flag)const{
2093 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2094 Chain = Val.getValue(1);
2095 Flag = Val.getValue(2);
2097 // If the result was expanded, copy from the top part.
2098 if (Regs.size() > 1) {
2099 assert(Regs.size() == 2 &&
2100 "Cannot expand to more than 2 elts yet!");
2101 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2102 Chain = Hi.getValue(1);
2103 Flag = Hi.getValue(2);
2104 if (DAG.getTargetLoweringInfo().isLittleEndian())
2105 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2107 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2110 // Otherwise, if the return value was promoted or extended, truncate it to the
2111 // appropriate type.
2112 if (RegVT == ValueVT)
2115 if (MVT::isInteger(RegVT)) {
2116 if (ValueVT < RegVT)
2117 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2119 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2121 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2125 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2126 /// specified value into the registers specified by this object. This uses
2127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2128 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2129 SDOperand &Chain, SDOperand &Flag,
2130 MVT::ValueType PtrVT) const {
2131 if (Regs.size() == 1) {
2132 // If there is a single register and the types differ, this must be
2134 if (RegVT != ValueVT) {
2135 if (MVT::isInteger(RegVT)) {
2136 if (RegVT < ValueVT)
2137 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2139 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2141 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2143 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2144 Flag = Chain.getValue(1);
2146 std::vector<unsigned> R(Regs);
2147 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2148 std::reverse(R.begin(), R.end());
2150 for (unsigned i = 0, e = R.size(); i != e; ++i) {
2151 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2152 DAG.getConstant(i, PtrVT));
2153 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2154 Flag = Chain.getValue(1);
2159 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2160 /// operand list. This adds the code marker and includes the number of
2161 /// values added into it.
2162 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2163 std::vector<SDOperand> &Ops) const {
2164 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2165 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2166 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2169 /// isAllocatableRegister - If the specified register is safe to allocate,
2170 /// i.e. it isn't a stack pointer or some other special register, return the
2171 /// register class for the register. Otherwise, return null.
2172 static const TargetRegisterClass *
2173 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2174 const TargetLowering &TLI, const MRegisterInfo *MRI) {
2175 MVT::ValueType FoundVT = MVT::Other;
2176 const TargetRegisterClass *FoundRC = 0;
2177 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2178 E = MRI->regclass_end(); RCI != E; ++RCI) {
2179 MVT::ValueType ThisVT = MVT::Other;
2181 const TargetRegisterClass *RC = *RCI;
2182 // If none of the the value types for this register class are valid, we
2183 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2184 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2186 if (TLI.isTypeLegal(*I)) {
2187 // If we have already found this register in a different register class,
2188 // choose the one with the largest VT specified. For example, on
2189 // PowerPC, we favor f64 register classes over f32.
2190 if (FoundVT == MVT::Other ||
2191 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2198 if (ThisVT == MVT::Other) continue;
2200 // NOTE: This isn't ideal. In particular, this might allocate the
2201 // frame pointer in functions that need it (due to them not being taken
2202 // out of allocation, because a variable sized allocation hasn't been seen
2203 // yet). This is a slight code pessimization, but should still work.
2204 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2205 E = RC->allocation_order_end(MF); I != E; ++I)
2207 // We found a matching register class. Keep looking at others in case
2208 // we find one with larger registers that this physreg is also in.
2217 RegsForValue SelectionDAGLowering::
2218 GetRegistersForValue(const std::string &ConstrCode,
2219 MVT::ValueType VT, bool isOutReg, bool isInReg,
2220 std::set<unsigned> &OutputRegs,
2221 std::set<unsigned> &InputRegs) {
2222 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2223 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2224 std::vector<unsigned> Regs;
2226 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2227 MVT::ValueType RegVT;
2228 MVT::ValueType ValueVT = VT;
2230 // If this is a constraint for a specific physical register, like {r17},
2232 if (PhysReg.first) {
2233 if (VT == MVT::Other)
2234 ValueVT = *PhysReg.second->vt_begin();
2236 // Get the actual register value type. This is important, because the user
2237 // may have asked for (e.g.) the AX register in i32 type. We need to
2238 // remember that AX is actually i16 to get the right extension.
2239 RegVT = *PhysReg.second->vt_begin();
2241 // This is a explicit reference to a physical register.
2242 Regs.push_back(PhysReg.first);
2244 // If this is an expanded reference, add the rest of the regs to Regs.
2246 TargetRegisterClass::iterator I = PhysReg.second->begin();
2247 TargetRegisterClass::iterator E = PhysReg.second->end();
2248 for (; *I != PhysReg.first; ++I)
2249 assert(I != E && "Didn't find reg!");
2251 // Already added the first reg.
2253 for (; NumRegs; --NumRegs, ++I) {
2254 assert(I != E && "Ran out of registers to allocate!");
2258 return RegsForValue(Regs, RegVT, ValueVT);
2261 // Otherwise, if this was a reference to an LLVM register class, create vregs
2262 // for this reference.
2263 std::vector<unsigned> RegClassRegs;
2264 if (PhysReg.second) {
2265 // If this is an early clobber or tied register, our regalloc doesn't know
2266 // how to maintain the constraint. If it isn't, go ahead and create vreg
2267 // and let the regalloc do the right thing.
2268 if (!isOutReg || !isInReg) {
2269 if (VT == MVT::Other)
2270 ValueVT = *PhysReg.second->vt_begin();
2271 RegVT = *PhysReg.second->vt_begin();
2273 // Create the appropriate number of virtual registers.
2274 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2275 for (; NumRegs; --NumRegs)
2276 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2278 return RegsForValue(Regs, RegVT, ValueVT);
2281 // Otherwise, we can't allocate it. Let the code below figure out how to
2282 // maintain these constraints.
2283 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2286 // This is a reference to a register class that doesn't directly correspond
2287 // to an LLVM register class. Allocate NumRegs consecutive, available,
2288 // registers from the class.
2289 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2292 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2293 MachineFunction &MF = *CurMBB->getParent();
2294 unsigned NumAllocated = 0;
2295 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2296 unsigned Reg = RegClassRegs[i];
2297 // See if this register is available.
2298 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2299 (isInReg && InputRegs.count(Reg))) { // Already used.
2300 // Make sure we find consecutive registers.
2305 // Check to see if this register is allocatable (i.e. don't give out the
2307 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
2309 // Make sure we find consecutive registers.
2314 // Okay, this register is good, we can use it.
2317 // If we allocated enough consecutive
2318 if (NumAllocated == NumRegs) {
2319 unsigned RegStart = (i-NumAllocated)+1;
2320 unsigned RegEnd = i+1;
2321 // Mark all of the allocated registers used.
2322 for (unsigned i = RegStart; i != RegEnd; ++i) {
2323 unsigned Reg = RegClassRegs[i];
2324 Regs.push_back(Reg);
2325 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2326 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2329 return RegsForValue(Regs, *RC->vt_begin(), VT);
2333 // Otherwise, we couldn't allocate enough registers for this.
2334 return RegsForValue();
2338 /// visitInlineAsm - Handle a call to an InlineAsm object.
2340 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2341 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2343 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2346 // Note, we treat inline asms both with and without side-effects as the same.
2347 // If an inline asm doesn't have side effects and doesn't access memory, we
2348 // could not choose to not chain it.
2349 bool hasSideEffects = IA->hasSideEffects();
2351 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
2352 std::vector<MVT::ValueType> ConstraintVTs;
2354 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2355 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2356 /// if it is a def of that register.
2357 std::vector<SDOperand> AsmNodeOperands;
2358 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2359 AsmNodeOperands.push_back(AsmStr);
2361 SDOperand Chain = getRoot();
2364 // We fully assign registers here at isel time. This is not optimal, but
2365 // should work. For register classes that correspond to LLVM classes, we
2366 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2367 // over the constraints, collecting fixed registers that we know we can't use.
2368 std::set<unsigned> OutputRegs, InputRegs;
2370 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2371 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2372 std::string &ConstraintCode = Constraints[i].Codes[0];
2374 MVT::ValueType OpVT;
2376 // Compute the value type for each operand and add it to ConstraintVTs.
2377 switch (Constraints[i].Type) {
2378 case InlineAsm::isOutput:
2379 if (!Constraints[i].isIndirectOutput) {
2380 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2381 OpVT = TLI.getValueType(I.getType());
2383 const Type *OpTy = I.getOperand(OpNum)->getType();
2384 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2385 OpNum++; // Consumes a call operand.
2388 case InlineAsm::isInput:
2389 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2390 OpNum++; // Consumes a call operand.
2392 case InlineAsm::isClobber:
2397 ConstraintVTs.push_back(OpVT);
2399 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2400 continue; // Not assigned a fixed reg.
2402 // Build a list of regs that this operand uses. This always has a single
2403 // element for promoted/expanded operands.
2404 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2406 OutputRegs, InputRegs);
2408 switch (Constraints[i].Type) {
2409 case InlineAsm::isOutput:
2410 // We can't assign any other output to this register.
2411 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2412 // If this is an early-clobber output, it cannot be assigned to the same
2413 // value as the input reg.
2414 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2415 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2417 case InlineAsm::isInput:
2418 // We can't assign any other input to this register.
2419 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2421 case InlineAsm::isClobber:
2422 // Clobbered regs cannot be used as inputs or outputs.
2423 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2424 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2429 // Loop over all of the inputs, copying the operand values into the
2430 // appropriate registers and processing the output regs.
2431 RegsForValue RetValRegs;
2432 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2435 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2436 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2437 std::string &ConstraintCode = Constraints[i].Codes[0];
2439 switch (Constraints[i].Type) {
2440 case InlineAsm::isOutput: {
2441 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2442 if (ConstraintCode.size() == 1) // not a physreg name.
2443 CTy = TLI.getConstraintType(ConstraintCode[0]);
2445 if (CTy == TargetLowering::C_Memory) {
2447 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2449 // Check that the operand (the address to store to) isn't a float.
2450 if (!MVT::isInteger(InOperandVal.getValueType()))
2451 assert(0 && "MATCH FAIL!");
2453 if (!Constraints[i].isIndirectOutput)
2454 assert(0 && "MATCH FAIL!");
2456 OpNum++; // Consumes a call operand.
2458 // Extend/truncate to the right pointer type if needed.
2459 MVT::ValueType PtrType = TLI.getPointerTy();
2460 if (InOperandVal.getValueType() < PtrType)
2461 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2462 else if (InOperandVal.getValueType() > PtrType)
2463 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2465 // Add information to the INLINEASM node to know about this output.
2466 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2467 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2468 AsmNodeOperands.push_back(InOperandVal);
2472 // Otherwise, this is a register output.
2473 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2475 // If this is an early-clobber output, or if there is an input
2476 // constraint that matches this, we need to reserve the input register
2477 // so no other inputs allocate to it.
2478 bool UsesInputRegister = false;
2479 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2480 UsesInputRegister = true;
2482 // Copy the output from the appropriate register. Find a register that
2485 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2486 true, UsesInputRegister,
2487 OutputRegs, InputRegs);
2488 if (Regs.Regs.empty()) {
2489 std::cerr << "Couldn't allocate output reg for contraint '"
2490 << ConstraintCode << "'!\n";
2494 if (!Constraints[i].isIndirectOutput) {
2495 assert(RetValRegs.Regs.empty() &&
2496 "Cannot have multiple output constraints yet!");
2497 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2500 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2501 I.getOperand(OpNum)));
2502 OpNum++; // Consumes a call operand.
2505 // Add information to the INLINEASM node to know that this register is
2507 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2510 case InlineAsm::isInput: {
2511 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2512 OpNum++; // Consumes a call operand.
2514 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2515 // If this is required to match an output register we have already set,
2516 // just use its register.
2517 unsigned OperandNo = atoi(ConstraintCode.c_str());
2519 // Scan until we find the definition we already emitted of this operand.
2520 // When we find it, create a RegsForValue operand.
2521 unsigned CurOp = 2; // The first operand.
2522 for (; OperandNo; --OperandNo) {
2523 // Advance to the next operand.
2525 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2526 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2527 (NumOps & 7) == 4 /*MEM*/) &&
2528 "Skipped past definitions?");
2529 CurOp += (NumOps>>3)+1;
2533 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2534 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2535 "Skipped past definitions?");
2537 // Add NumOps>>3 registers to MatchedRegs.
2538 RegsForValue MatchedRegs;
2539 MatchedRegs.ValueVT = InOperandVal.getValueType();
2540 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2541 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2542 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2543 MatchedRegs.Regs.push_back(Reg);
2546 // Use the produced MatchedRegs object to
2547 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2548 TLI.getPointerTy());
2549 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2553 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2554 if (ConstraintCode.size() == 1) // not a physreg name.
2555 CTy = TLI.getConstraintType(ConstraintCode[0]);
2557 if (CTy == TargetLowering::C_Other) {
2558 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2559 ConstraintCode[0], DAG);
2560 if (!InOperandVal.Val) {
2561 std::cerr << "Invalid operand for inline asm constraint '"
2562 << ConstraintCode << "'!\n";
2566 // Add information to the INLINEASM node to know about this input.
2567 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2568 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2569 AsmNodeOperands.push_back(InOperandVal);
2571 } else if (CTy == TargetLowering::C_Memory) {
2574 // Check that the operand isn't a float.
2575 if (!MVT::isInteger(InOperandVal.getValueType()))
2576 assert(0 && "MATCH FAIL!");
2578 // Extend/truncate to the right pointer type if needed.
2579 MVT::ValueType PtrType = TLI.getPointerTy();
2580 if (InOperandVal.getValueType() < PtrType)
2581 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2582 else if (InOperandVal.getValueType() > PtrType)
2583 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2585 // Add information to the INLINEASM node to know about this input.
2586 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2587 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2588 AsmNodeOperands.push_back(InOperandVal);
2592 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2594 // Copy the input into the appropriate registers.
2595 RegsForValue InRegs =
2596 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2597 false, true, OutputRegs, InputRegs);
2598 // FIXME: should be match fail.
2599 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2601 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
2603 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2606 case InlineAsm::isClobber: {
2607 RegsForValue ClobberedRegs =
2608 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2609 OutputRegs, InputRegs);
2610 // Add the clobbered value to the operand list, so that the register
2611 // allocator is aware that the physreg got clobbered.
2612 if (!ClobberedRegs.Regs.empty())
2613 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2619 // Finish up input operands.
2620 AsmNodeOperands[0] = Chain;
2621 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2623 Chain = DAG.getNode(ISD::INLINEASM,
2624 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
2625 &AsmNodeOperands[0], AsmNodeOperands.size());
2626 Flag = Chain.getValue(1);
2628 // If this asm returns a register value, copy the result from that register
2629 // and set it as the value of the call.
2630 if (!RetValRegs.Regs.empty())
2631 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2633 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2635 // Process indirect outputs, first output all of the flagged copies out of
2637 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2638 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2639 Value *Ptr = IndirectStoresToEmit[i].second;
2640 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2641 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2644 // Emit the non-flagged stores from the physregs.
2645 SmallVector<SDOperand, 8> OutChains;
2646 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2647 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
2648 getValue(StoresToEmit[i].second),
2649 StoresToEmit[i].second, 0));
2650 if (!OutChains.empty())
2651 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2652 &OutChains[0], OutChains.size());
2657 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2658 SDOperand Src = getValue(I.getOperand(0));
2660 MVT::ValueType IntPtr = TLI.getPointerTy();
2662 if (IntPtr < Src.getValueType())
2663 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2664 else if (IntPtr > Src.getValueType())
2665 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2667 // Scale the source by the type size.
2668 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2669 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2670 Src, getIntPtrConstant(ElementSize));
2672 std::vector<std::pair<SDOperand, const Type*> > Args;
2673 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
2675 std::pair<SDOperand,SDOperand> Result =
2676 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2677 DAG.getExternalSymbol("malloc", IntPtr),
2679 setValue(&I, Result.first); // Pointers always fit in registers
2680 DAG.setRoot(Result.second);
2683 void SelectionDAGLowering::visitFree(FreeInst &I) {
2684 std::vector<std::pair<SDOperand, const Type*> > Args;
2685 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2686 TLI.getTargetData()->getIntPtrType()));
2687 MVT::ValueType IntPtr = TLI.getPointerTy();
2688 std::pair<SDOperand,SDOperand> Result =
2689 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2690 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2691 DAG.setRoot(Result.second);
2694 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2695 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2696 // instructions are special in various ways, which require special support to
2697 // insert. The specified MachineInstr is created but not inserted into any
2698 // basic blocks, and the scheduler passes ownership of it to this method.
2699 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2700 MachineBasicBlock *MBB) {
2701 std::cerr << "If a target marks an instruction with "
2702 "'usesCustomDAGSchedInserter', it must implement "
2703 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2708 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2709 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2710 getValue(I.getOperand(1)),
2711 DAG.getSrcValue(I.getOperand(1))));
2714 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2715 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2716 getValue(I.getOperand(0)),
2717 DAG.getSrcValue(I.getOperand(0)));
2719 DAG.setRoot(V.getValue(1));
2722 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2723 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2724 getValue(I.getOperand(1)),
2725 DAG.getSrcValue(I.getOperand(1))));
2728 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2729 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2730 getValue(I.getOperand(1)),
2731 getValue(I.getOperand(2)),
2732 DAG.getSrcValue(I.getOperand(1)),
2733 DAG.getSrcValue(I.getOperand(2))));
2736 /// TargetLowering::LowerArguments - This is the default LowerArguments
2737 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
2738 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2739 /// integrated into SDISel.
2740 std::vector<SDOperand>
2741 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2742 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2743 std::vector<SDOperand> Ops;
2744 Ops.push_back(DAG.getRoot());
2745 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2746 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2748 // Add one result value for each formal argument.
2749 std::vector<MVT::ValueType> RetVals;
2750 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2751 MVT::ValueType VT = getValueType(I->getType());
2753 switch (getTypeAction(VT)) {
2754 default: assert(0 && "Unknown type action!");
2756 RetVals.push_back(VT);
2759 RetVals.push_back(getTypeToTransformTo(VT));
2762 if (VT != MVT::Vector) {
2763 // If this is a large integer, it needs to be broken up into small
2764 // integers. Figure out what the destination type is and how many small
2765 // integers it turns into.
2766 MVT::ValueType NVT = getTypeToTransformTo(VT);
2767 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2768 for (unsigned i = 0; i != NumVals; ++i)
2769 RetVals.push_back(NVT);
2771 // Otherwise, this is a vector type. We only support legal vectors
2773 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2774 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2776 // Figure out if there is a Packed type corresponding to this Vector
2777 // type. If so, convert to the packed type.
2778 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2779 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2780 RetVals.push_back(TVT);
2782 assert(0 && "Don't support illegal by-val vector arguments yet!");
2789 RetVals.push_back(MVT::Other);
2792 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2793 DAG.getNodeValueTypes(RetVals), RetVals.size(),
2794 &Ops[0], Ops.size()).Val;
2796 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
2798 // Set up the return result vector.
2801 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2802 MVT::ValueType VT = getValueType(I->getType());
2804 switch (getTypeAction(VT)) {
2805 default: assert(0 && "Unknown type action!");
2807 Ops.push_back(SDOperand(Result, i++));
2810 SDOperand Op(Result, i++);
2811 if (MVT::isInteger(VT)) {
2812 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2814 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2815 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2817 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2818 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2824 if (VT != MVT::Vector) {
2825 // If this is a large integer, it needs to be reassembled from small
2826 // integers. Figure out what the source elt type is and how many small
2828 MVT::ValueType NVT = getTypeToTransformTo(VT);
2829 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2831 SDOperand Lo = SDOperand(Result, i++);
2832 SDOperand Hi = SDOperand(Result, i++);
2834 if (!isLittleEndian())
2837 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2839 // Value scalarized into many values. Unimp for now.
2840 assert(0 && "Cannot expand i64 -> i16 yet!");
2843 // Otherwise, this is a vector type. We only support legal vectors
2845 const PackedType *PTy = cast<PackedType>(I->getType());
2846 unsigned NumElems = PTy->getNumElements();
2847 const Type *EltTy = PTy->getElementType();
2849 // Figure out if there is a Packed type corresponding to this Vector
2850 // type. If so, convert to the packed type.
2851 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2852 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2853 SDOperand N = SDOperand(Result, i++);
2854 // Handle copies from generic vectors to registers.
2855 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2856 DAG.getConstant(NumElems, MVT::i32),
2857 DAG.getValueType(getValueType(EltTy)));
2860 assert(0 && "Don't support illegal by-val vector arguments yet!");
2871 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
2872 /// implementation, which just inserts an ISD::CALL node, which is later custom
2873 /// lowered by the target to something concrete. FIXME: When all targets are
2874 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2875 std::pair<SDOperand, SDOperand>
2876 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2877 unsigned CallingConv, bool isTailCall,
2879 ArgListTy &Args, SelectionDAG &DAG) {
2880 SmallVector<SDOperand, 32> Ops;
2881 Ops.push_back(Chain); // Op#0 - Chain
2882 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2883 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2884 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2885 Ops.push_back(Callee);
2887 // Handle all of the outgoing arguments.
2888 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2889 MVT::ValueType VT = getValueType(Args[i].second);
2890 SDOperand Op = Args[i].first;
2891 bool isSigned = Args[i].second->isSigned();
2892 switch (getTypeAction(VT)) {
2893 default: assert(0 && "Unknown type action!");
2896 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2899 if (MVT::isInteger(VT)) {
2900 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2901 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2903 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2904 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2907 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2910 if (VT != MVT::Vector) {
2911 // If this is a large integer, it needs to be broken down into small
2912 // integers. Figure out what the source elt type is and how many small
2914 MVT::ValueType NVT = getTypeToTransformTo(VT);
2915 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2917 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2918 DAG.getConstant(0, getPointerTy()));
2919 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2920 DAG.getConstant(1, getPointerTy()));
2921 if (!isLittleEndian())
2925 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2927 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2929 // Value scalarized into many values. Unimp for now.
2930 assert(0 && "Cannot expand i64 -> i16 yet!");
2933 // Otherwise, this is a vector type. We only support legal vectors
2935 const PackedType *PTy = cast<PackedType>(Args[i].second);
2936 unsigned NumElems = PTy->getNumElements();
2937 const Type *EltTy = PTy->getElementType();
2939 // Figure out if there is a Packed type corresponding to this Vector
2940 // type. If so, convert to the packed type.
2941 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2942 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2943 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2944 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2946 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2948 assert(0 && "Don't support illegal by-val vector call args yet!");
2956 // Figure out the result value types.
2957 SmallVector<MVT::ValueType, 4> RetTys;
2959 if (RetTy != Type::VoidTy) {
2960 MVT::ValueType VT = getValueType(RetTy);
2961 switch (getTypeAction(VT)) {
2962 default: assert(0 && "Unknown type action!");
2964 RetTys.push_back(VT);
2967 RetTys.push_back(getTypeToTransformTo(VT));
2970 if (VT != MVT::Vector) {
2971 // If this is a large integer, it needs to be reassembled from small
2972 // integers. Figure out what the source elt type is and how many small
2974 MVT::ValueType NVT = getTypeToTransformTo(VT);
2975 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2976 for (unsigned i = 0; i != NumVals; ++i)
2977 RetTys.push_back(NVT);
2979 // Otherwise, this is a vector type. We only support legal vectors
2981 const PackedType *PTy = cast<PackedType>(RetTy);
2982 unsigned NumElems = PTy->getNumElements();
2983 const Type *EltTy = PTy->getElementType();
2985 // Figure out if there is a Packed type corresponding to this Vector
2986 // type. If so, convert to the packed type.
2987 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2988 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2989 RetTys.push_back(TVT);
2991 assert(0 && "Don't support illegal by-val vector call results yet!");
2998 RetTys.push_back(MVT::Other); // Always has a chain.
3000 // Finally, create the CALL node.
3001 SDOperand Res = DAG.getNode(ISD::CALL,
3002 DAG.getVTList(&RetTys[0], RetTys.size()),
3003 &Ops[0], Ops.size());
3005 // This returns a pair of operands. The first element is the
3006 // return value for the function (if RetTy is not VoidTy). The second
3007 // element is the outgoing token chain.
3009 if (RetTys.size() != 1) {
3010 MVT::ValueType VT = getValueType(RetTy);
3011 if (RetTys.size() == 2) {
3014 // If this value was promoted, truncate it down.
3015 if (ResVal.getValueType() != VT) {
3016 if (VT == MVT::Vector) {
3017 // Insert a VBITCONVERT to convert from the packed result type to the
3018 // MVT::Vector type.
3019 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3020 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3022 // Figure out if there is a Packed type corresponding to this Vector
3023 // type. If so, convert to the packed type.
3024 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3025 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3026 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3027 // "N x PTyElementVT" MVT::Vector type.
3028 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
3029 DAG.getConstant(NumElems, MVT::i32),
3030 DAG.getValueType(getValueType(EltTy)));
3034 } else if (MVT::isInteger(VT)) {
3035 unsigned AssertOp = RetTy->isSigned() ?
3036 ISD::AssertSext : ISD::AssertZext;
3037 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3038 DAG.getValueType(VT));
3039 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3041 assert(MVT::isFloatingPoint(VT));
3042 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3045 } else if (RetTys.size() == 3) {
3046 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3047 Res.getValue(0), Res.getValue(1));
3050 assert(0 && "Case not handled yet!");
3054 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3059 // It is always conservatively correct for llvm.returnaddress and
3060 // llvm.frameaddress to return 0.
3062 // FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3063 // expanded to 0 if the target wants.
3064 std::pair<SDOperand, SDOperand>
3065 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3066 unsigned Depth, SelectionDAG &DAG) {
3067 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
3070 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3071 assert(0 && "LowerOperation not implemented for this target!");
3076 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3077 SelectionDAG &DAG) {
3078 assert(0 && "CustomPromoteOperation not implemented for this target!");
3083 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
3084 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
3085 std::pair<SDOperand,SDOperand> Result =
3086 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
3087 setValue(&I, Result.first);
3088 DAG.setRoot(Result.second);
3091 /// getMemsetValue - Vectorized representation of the memset value
3093 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
3094 SelectionDAG &DAG) {
3095 MVT::ValueType CurVT = VT;
3096 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3097 uint64_t Val = C->getValue() & 255;
3099 while (CurVT != MVT::i8) {
3100 Val = (Val << Shift) | Val;
3102 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3104 return DAG.getConstant(Val, VT);
3106 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3108 while (CurVT != MVT::i8) {
3110 DAG.getNode(ISD::OR, VT,
3111 DAG.getNode(ISD::SHL, VT, Value,
3112 DAG.getConstant(Shift, MVT::i8)), Value);
3114 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3121 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3122 /// used when a memcpy is turned into a memset when the source is a constant
3124 static SDOperand getMemsetStringVal(MVT::ValueType VT,
3125 SelectionDAG &DAG, TargetLowering &TLI,
3126 std::string &Str, unsigned Offset) {
3127 MVT::ValueType CurVT = VT;
3129 unsigned MSB = getSizeInBits(VT) / 8;
3130 if (TLI.isLittleEndian())
3131 Offset = Offset + MSB - 1;
3132 for (unsigned i = 0; i != MSB; ++i) {
3133 Val = (Val << 8) | Str[Offset];
3134 Offset += TLI.isLittleEndian() ? -1 : 1;
3136 return DAG.getConstant(Val, VT);
3139 /// getMemBasePlusOffset - Returns base and offset node for the
3140 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3141 SelectionDAG &DAG, TargetLowering &TLI) {
3142 MVT::ValueType VT = Base.getValueType();
3143 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3146 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3147 /// to replace the memset / memcpy is below the threshold. It also returns the
3148 /// types of the sequence of memory ops to perform memset / memcpy.
3149 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3150 unsigned Limit, uint64_t Size,
3151 unsigned Align, TargetLowering &TLI) {
3154 if (TLI.allowsUnalignedMemoryAccesses()) {
3157 switch (Align & 7) {
3173 MVT::ValueType LVT = MVT::i64;
3174 while (!TLI.isTypeLegal(LVT))
3175 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3176 assert(MVT::isInteger(LVT));
3181 unsigned NumMemOps = 0;
3183 unsigned VTSize = getSizeInBits(VT) / 8;
3184 while (VTSize > Size) {
3185 VT = (MVT::ValueType)((unsigned)VT - 1);
3188 assert(MVT::isInteger(VT));
3190 if (++NumMemOps > Limit)
3192 MemOps.push_back(VT);
3199 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
3200 SDOperand Op1 = getValue(I.getOperand(1));
3201 SDOperand Op2 = getValue(I.getOperand(2));
3202 SDOperand Op3 = getValue(I.getOperand(3));
3203 SDOperand Op4 = getValue(I.getOperand(4));
3204 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3205 if (Align == 0) Align = 1;
3207 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3208 std::vector<MVT::ValueType> MemOps;
3210 // Expand memset / memcpy to a series of load / store ops
3211 // if the size operand falls below a certain threshold.
3212 SmallVector<SDOperand, 8> OutChains;
3214 default: break; // Do nothing for now.
3216 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3217 Size->getValue(), Align, TLI)) {
3218 unsigned NumMemOps = MemOps.size();
3219 unsigned Offset = 0;
3220 for (unsigned i = 0; i < NumMemOps; i++) {
3221 MVT::ValueType VT = MemOps[i];
3222 unsigned VTSize = getSizeInBits(VT) / 8;
3223 SDOperand Value = getMemsetValue(Op2, VT, DAG);
3224 SDOperand Store = DAG.getStore(getRoot(), Value,
3225 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
3226 I.getOperand(1), Offset);
3227 OutChains.push_back(Store);
3234 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3235 Size->getValue(), Align, TLI)) {
3236 unsigned NumMemOps = MemOps.size();
3237 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
3238 GlobalAddressSDNode *G = NULL;
3240 bool CopyFromStr = false;
3242 if (Op2.getOpcode() == ISD::GlobalAddress)
3243 G = cast<GlobalAddressSDNode>(Op2);
3244 else if (Op2.getOpcode() == ISD::ADD &&
3245 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3246 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3247 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
3248 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
3251 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3253 Str = GV->getStringValue(false);
3261 for (unsigned i = 0; i < NumMemOps; i++) {
3262 MVT::ValueType VT = MemOps[i];
3263 unsigned VTSize = getSizeInBits(VT) / 8;
3264 SDOperand Value, Chain, Store;
3267 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3270 DAG.getStore(Chain, Value,
3271 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3272 I.getOperand(1), DstOff);
3274 Value = DAG.getLoad(VT, getRoot(),
3275 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
3276 I.getOperand(2), SrcOff);
3277 Chain = Value.getValue(1);
3279 DAG.getStore(Chain, Value,
3280 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3281 I.getOperand(1), DstOff);
3283 OutChains.push_back(Store);
3292 if (!OutChains.empty()) {
3293 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3294 &OutChains[0], OutChains.size()));
3299 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
3302 //===----------------------------------------------------------------------===//
3303 // SelectionDAGISel code
3304 //===----------------------------------------------------------------------===//
3306 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3307 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3310 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
3311 // FIXME: we only modify the CFG to split critical edges. This
3312 // updates dom and loop info.
3313 AU.addRequired<AliasAnalysis>();
3317 /// OptimizeNoopCopyExpression - We have determined that the specified cast
3318 /// instruction is a noop copy (e.g. it's casting from one pointer type to
3319 /// another, int->uint, or int->sbyte on PPC.
3321 /// Return true if any changes are made.
3322 static bool OptimizeNoopCopyExpression(CastInst *CI) {
3323 BasicBlock *DefBB = CI->getParent();
3325 /// InsertedCasts - Only insert a cast in each block once.
3326 std::map<BasicBlock*, CastInst*> InsertedCasts;
3328 bool MadeChange = false;
3329 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3331 Use &TheUse = UI.getUse();
3332 Instruction *User = cast<Instruction>(*UI);
3334 // Figure out which BB this cast is used in. For PHI's this is the
3335 // appropriate predecessor block.
3336 BasicBlock *UserBB = User->getParent();
3337 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3338 unsigned OpVal = UI.getOperandNo()/2;
3339 UserBB = PN->getIncomingBlock(OpVal);
3342 // Preincrement use iterator so we don't invalidate it.
3345 // If this user is in the same block as the cast, don't change the cast.
3346 if (UserBB == DefBB) continue;
3348 // If we have already inserted a cast into this block, use it.
3349 CastInst *&InsertedCast = InsertedCasts[UserBB];
3351 if (!InsertedCast) {
3352 BasicBlock::iterator InsertPt = UserBB->begin();
3353 while (isa<PHINode>(InsertPt)) ++InsertPt;
3356 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3360 // Replace a use of the cast with a use of the new casat.
3361 TheUse = InsertedCast;
3364 // If we removed all uses, nuke the cast.
3365 if (CI->use_empty())
3366 CI->eraseFromParent();
3371 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3372 /// casting to the type of GEPI.
3373 static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3374 Instruction *GEPI, Value *Ptr,
3376 if (V) return V; // Already computed.
3378 BasicBlock::iterator InsertPt;
3379 if (BB == GEPI->getParent()) {
3380 // If insert into the GEP's block, insert right after the GEP.
3384 // Otherwise, insert at the top of BB, after any PHI nodes
3385 InsertPt = BB->begin();
3386 while (isa<PHINode>(InsertPt)) ++InsertPt;
3389 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3390 // BB so that there is only one value live across basic blocks (the cast
3392 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3393 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3394 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3396 // Add the offset, cast it to the right type.
3397 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
3398 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
3401 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3402 /// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3403 /// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3404 /// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3405 /// sink PtrOffset into user blocks where doing so will likely allow us to fold
3406 /// the constant add into a load or store instruction. Additionally, if a user
3407 /// is a pointer-pointer cast, we look through it to find its users.
3408 static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3409 Constant *PtrOffset, BasicBlock *DefBB,
3410 GetElementPtrInst *GEPI,
3411 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
3412 while (!RepPtr->use_empty()) {
3413 Instruction *User = cast<Instruction>(RepPtr->use_back());
3415 // If the user is a Pointer-Pointer cast, recurse.
3416 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3417 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3419 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3420 // could invalidate an iterator.
3421 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3425 // If this is a load of the pointer, or a store through the pointer, emit
3426 // the increment into the load/store block.
3427 Instruction *NewVal;
3428 if (isa<LoadInst>(User) ||
3429 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3430 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3431 User->getParent(), GEPI,
3434 // If this use is not foldable into the addressing mode, use a version
3435 // emitted in the GEP block.
3436 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3440 if (GEPI->getType() != RepPtr->getType()) {
3441 BasicBlock::iterator IP = NewVal;
3443 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3445 User->replaceUsesOfWith(RepPtr, NewVal);
3450 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3451 /// selection, we want to be a bit careful about some things. In particular, if
3452 /// we have a GEP instruction that is used in a different block than it is
3453 /// defined, the addressing expression of the GEP cannot be folded into loads or
3454 /// stores that use it. In this case, decompose the GEP and move constant
3455 /// indices into blocks that use it.
3456 static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
3457 const TargetData *TD) {
3458 // If this GEP is only used inside the block it is defined in, there is no
3459 // need to rewrite it.
3460 bool isUsedOutsideDefBB = false;
3461 BasicBlock *DefBB = GEPI->getParent();
3462 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3464 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3465 isUsedOutsideDefBB = true;
3469 if (!isUsedOutsideDefBB) return false;
3471 // If this GEP has no non-zero constant indices, there is nothing we can do,
3473 bool hasConstantIndex = false;
3474 bool hasVariableIndex = false;
3475 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3476 E = GEPI->op_end(); OI != E; ++OI) {
3477 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
3478 if (CI->getZExtValue()) {
3479 hasConstantIndex = true;
3483 hasVariableIndex = true;
3487 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3488 if (!hasConstantIndex && !hasVariableIndex) {
3489 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3490 GEPI->getName(), GEPI);
3491 GEPI->replaceAllUsesWith(NC);
3492 GEPI->eraseFromParent();
3496 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
3497 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3500 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3501 // constant offset (which we now know is non-zero) and deal with it later.
3502 uint64_t ConstantOffset = 0;
3503 const Type *UIntPtrTy = TD->getIntPtrType();
3504 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3505 const Type *Ty = GEPI->getOperand(0)->getType();
3507 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3508 E = GEPI->op_end(); OI != E; ++OI) {
3510 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3511 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
3513 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
3514 Ty = StTy->getElementType(Field);
3516 Ty = cast<SequentialType>(Ty)->getElementType();
3518 // Handle constant subscripts.
3519 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3520 if (CI->getZExtValue() == 0) continue;
3521 if (CI->getType()->isSigned())
3522 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
3524 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
3528 // Ptr = Ptr + Idx * ElementSize;
3530 // Cast Idx to UIntPtrTy if needed.
3531 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3533 uint64_t ElementSize = TD->getTypeSize(Ty);
3534 // Mask off bits that should not be set.
3535 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3536 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
3538 // Multiply by the element size and add to the base.
3539 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3540 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3544 // Make sure that the offset fits in uintptr_t.
3545 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3546 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
3548 // Okay, we have now emitted all of the variable index parts to the BB that
3549 // the GEP is defined in. Loop over all of the using instructions, inserting
3550 // an "add Ptr, ConstantOffset" into each block that uses it and update the
3551 // instruction to use the newly computed value, making GEPI dead. When the
3552 // user is a load or store instruction address, we emit the add into the user
3553 // block, otherwise we use a canonical version right next to the gep (these
3554 // won't be foldable as addresses, so we might as well share the computation).
3556 std::map<BasicBlock*,Instruction*> InsertedExprs;
3557 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3559 // Finally, the GEP is dead, remove it.
3560 GEPI->eraseFromParent();
3566 /// SplitEdgeNicely - Split the critical edge from TI to it's specified
3567 /// successor if it will improve codegen. We only do this if the successor has
3568 /// phi nodes (otherwise critical edges are ok). If there is already another
3569 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
3570 /// instead of introducing a new block.
3571 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3572 BasicBlock *TIBB = TI->getParent();
3573 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3574 assert(isa<PHINode>(Dest->begin()) &&
3575 "This should only be called if Dest has a PHI!");
3577 /// TIPHIValues - This array is lazily computed to determine the values of
3578 /// PHIs in Dest that TI would provide.
3579 std::vector<Value*> TIPHIValues;
3581 // Check to see if Dest has any blocks that can be used as a split edge for
3583 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3584 BasicBlock *Pred = *PI;
3585 // To be usable, the pred has to end with an uncond branch to the dest.
3586 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3587 if (!PredBr || !PredBr->isUnconditional() ||
3588 // Must be empty other than the branch.
3589 &Pred->front() != PredBr)
3592 // Finally, since we know that Dest has phi nodes in it, we have to make
3593 // sure that jumping to Pred will have the same affect as going to Dest in
3594 // terms of PHI values.
3597 bool FoundMatch = true;
3598 for (BasicBlock::iterator I = Dest->begin();
3599 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3600 if (PHINo == TIPHIValues.size())
3601 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3603 // If the PHI entry doesn't work, we can't use this pred.
3604 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3610 // If we found a workable predecessor, change TI to branch to Succ.
3612 Dest->removePredecessor(TIBB);
3613 TI->setSuccessor(SuccNum, Pred);
3618 SplitCriticalEdge(TI, SuccNum, P, true);
3622 bool SelectionDAGISel::runOnFunction(Function &Fn) {
3623 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3624 RegMap = MF.getSSARegMap();
3625 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3627 // First, split all critical edges.
3629 // In this pass we also look for GEP and cast instructions that are used
3630 // across basic blocks and rewrite them to improve basic-block-at-a-time
3633 bool MadeChange = true;
3634 while (MadeChange) {
3636 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
3637 // Split all critical edges where the dest block has a PHI.
3638 TerminatorInst *BBTI = BB->getTerminator();
3639 if (BBTI->getNumSuccessors() > 1) {
3640 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
3641 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3642 isCriticalEdge(BBTI, i, true))
3643 SplitEdgeNicely(BBTI, i, this);
3647 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3648 Instruction *I = BBI++;
3649 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3650 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3651 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3652 // If the source of the cast is a constant, then this should have
3653 // already been constant folded. The only reason NOT to constant fold
3654 // it is if something (e.g. LSR) was careful to place the constant
3655 // evaluation in a block other than then one that uses it (e.g. to hoist
3656 // the address of globals out of a loop). If this is the case, we don't
3657 // want to forward-subst the cast.
3658 if (isa<Constant>(CI->getOperand(0)))
3661 // If this is a noop copy, sink it into user blocks to reduce the number
3662 // of virtual registers that must be created and coallesced.
3663 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3664 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3666 // This is an fp<->int conversion?
3667 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3670 // If this is an extension, it will be a zero or sign extension, which
3672 if (SrcVT < DstVT) continue;
3674 // If these values will be promoted, find out what they will be promoted
3675 // to. This helps us consider truncates on PPC as noop copies when they
3677 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3678 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3679 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3680 DstVT = TLI.getTypeToTransformTo(DstVT);
3682 // If, after promotion, these are the same types, this is a noop copy.
3684 MadeChange |= OptimizeNoopCopyExpression(CI);
3690 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3692 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3693 SelectBasicBlock(I, MF, FuncInfo);
3698 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3700 SDOperand Op = getValue(V);
3701 assert((Op.getOpcode() != ISD::CopyFromReg ||
3702 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3703 "Copy from a reg to the same reg!");
3705 // If this type is not legal, we must make sure to not create an invalid
3707 MVT::ValueType SrcVT = Op.getValueType();
3708 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3709 if (SrcVT == DestVT) {
3710 return DAG.getCopyToReg(getRoot(), Reg, Op);
3711 } else if (SrcVT == MVT::Vector) {
3712 // Handle copies from generic vectors to registers.
3713 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3714 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3715 PTyElementVT, PTyLegalElementVT);
3717 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3718 // MVT::Vector type.
3719 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3720 DAG.getConstant(NE, MVT::i32),
3721 DAG.getValueType(PTyElementVT));
3723 // Loop over all of the elements of the resultant vector,
3724 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3725 // copying them into output registers.
3726 SmallVector<SDOperand, 8> OutChains;
3727 SDOperand Root = getRoot();
3728 for (unsigned i = 0; i != NE; ++i) {
3729 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3730 Op, DAG.getConstant(i, TLI.getPointerTy()));
3731 if (PTyElementVT == PTyLegalElementVT) {
3732 // Elements are legal.
3733 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3734 } else if (PTyLegalElementVT > PTyElementVT) {
3735 // Elements are promoted.
3736 if (MVT::isFloatingPoint(PTyLegalElementVT))
3737 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3739 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3740 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3742 // Elements are expanded.
3743 // The src value is expanded into multiple registers.
3744 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3745 Elt, DAG.getConstant(0, TLI.getPointerTy()));
3746 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3747 Elt, DAG.getConstant(1, TLI.getPointerTy()));
3748 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3749 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3752 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3753 &OutChains[0], OutChains.size());
3754 } else if (SrcVT < DestVT) {
3755 // The src value is promoted to the register.
3756 if (MVT::isFloatingPoint(SrcVT))
3757 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3759 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3760 return DAG.getCopyToReg(getRoot(), Reg, Op);
3762 // The src value is expanded into multiple registers.
3763 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3764 Op, DAG.getConstant(0, TLI.getPointerTy()));
3765 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3766 Op, DAG.getConstant(1, TLI.getPointerTy()));
3767 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
3768 return DAG.getCopyToReg(Op, Reg+1, Hi);
3772 void SelectionDAGISel::
3773 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3774 std::vector<SDOperand> &UnorderedChains) {
3775 // If this is the entry block, emit arguments.
3776 Function &F = *BB->getParent();
3777 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3778 SDOperand OldRoot = SDL.DAG.getRoot();
3779 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3782 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3784 if (!AI->use_empty()) {
3785 SDL.setValue(AI, Args[a]);
3787 // If this argument is live outside of the entry block, insert a copy from
3788 // whereever we got it to the vreg that other BB's will reference it as.
3789 if (FuncInfo.ValueMap.count(AI)) {
3791 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
3792 UnorderedChains.push_back(Copy);
3796 // Finally, if the target has anything special to do, allow it to do so.
3797 // FIXME: this should insert code into the DAG!
3798 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3801 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3802 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3803 FunctionLoweringInfo &FuncInfo) {
3804 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3806 std::vector<SDOperand> UnorderedChains;
3808 // Lower any arguments needed in this block if this is the entry block.
3809 if (LLVMBB == &LLVMBB->getParent()->front())
3810 LowerArguments(LLVMBB, SDL, UnorderedChains);
3812 BB = FuncInfo.MBBMap[LLVMBB];
3813 SDL.setCurrentBasicBlock(BB);
3815 // Lower all of the non-terminator instructions.
3816 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3820 // Ensure that all instructions which are used outside of their defining
3821 // blocks are available as virtual registers.
3822 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3823 if (!I->use_empty() && !isa<PHINode>(I)) {
3824 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3825 if (VMI != FuncInfo.ValueMap.end())
3826 UnorderedChains.push_back(
3827 SDL.CopyValueToVirtualRegister(I, VMI->second));
3830 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3831 // ensure constants are generated when needed. Remember the virtual registers
3832 // that need to be added to the Machine PHI nodes as input. We cannot just
3833 // directly add them, because expansion might result in multiple MBB's for one
3834 // BB. As such, the start of the BB might correspond to a different MBB than
3837 TerminatorInst *TI = LLVMBB->getTerminator();
3839 // Emit constants only once even if used by multiple PHI nodes.
3840 std::map<Constant*, unsigned> ConstantsOut;
3842 // Vector bool would be better, but vector<bool> is really slow.
3843 std::vector<unsigned char> SuccsHandled;
3844 if (TI->getNumSuccessors())
3845 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3847 // Check successor nodes PHI nodes that expect a constant to be available from
3849 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3850 BasicBlock *SuccBB = TI->getSuccessor(succ);
3851 if (!isa<PHINode>(SuccBB->begin())) continue;
3852 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
3854 // If this terminator has multiple identical successors (common for
3855 // switches), only handle each succ once.
3856 unsigned SuccMBBNo = SuccMBB->getNumber();
3857 if (SuccsHandled[SuccMBBNo]) continue;
3858 SuccsHandled[SuccMBBNo] = true;
3860 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
3863 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3864 // nodes and Machine PHI nodes, but the incoming operands have not been
3866 for (BasicBlock::iterator I = SuccBB->begin();
3867 (PN = dyn_cast<PHINode>(I)); ++I) {
3868 // Ignore dead phi's.
3869 if (PN->use_empty()) continue;
3872 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3873 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3874 unsigned &RegOut = ConstantsOut[C];
3876 RegOut = FuncInfo.CreateRegForValue(C);
3877 UnorderedChains.push_back(
3878 SDL.CopyValueToVirtualRegister(C, RegOut));
3882 Reg = FuncInfo.ValueMap[PHIOp];
3884 assert(isa<AllocaInst>(PHIOp) &&
3885 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3886 "Didn't codegen value into a register!??");
3887 Reg = FuncInfo.CreateRegForValue(PHIOp);
3888 UnorderedChains.push_back(
3889 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
3893 // Remember that this register needs to added to the machine PHI node as
3894 // the input for this MBB.
3895 MVT::ValueType VT = TLI.getValueType(PN->getType());
3896 unsigned NumElements;
3897 if (VT != MVT::Vector)
3898 NumElements = TLI.getNumElements(VT);
3900 MVT::ValueType VT1,VT2;
3902 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3905 for (unsigned i = 0, e = NumElements; i != e; ++i)
3906 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3909 ConstantsOut.clear();
3911 // Turn all of the unordered chains into one factored node.
3912 if (!UnorderedChains.empty()) {
3913 SDOperand Root = SDL.getRoot();
3914 if (Root.getOpcode() != ISD::EntryToken) {
3915 unsigned i = 0, e = UnorderedChains.size();
3916 for (; i != e; ++i) {
3917 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3918 if (UnorderedChains[i].Val->getOperand(0) == Root)
3919 break; // Don't add the root if we already indirectly depend on it.
3923 UnorderedChains.push_back(Root);
3925 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3926 &UnorderedChains[0], UnorderedChains.size()));
3929 // Lower the terminator after the copies are emitted.
3930 SDL.visit(*LLVMBB->getTerminator());
3932 // Copy over any CaseBlock records that may now exist due to SwitchInst
3933 // lowering, as well as any jump table information.
3934 SwitchCases.clear();
3935 SwitchCases = SDL.SwitchCases;
3938 // Make sure the root of the DAG is up-to-date.
3939 DAG.setRoot(SDL.getRoot());
3942 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
3943 // Get alias analysis for load/store combining.
3944 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3946 // Run the DAG combiner in pre-legalize mode.
3947 DAG.Combine(false, AA);
3949 DEBUG(std::cerr << "Lowered selection DAG:\n");
3952 // Second step, hack on the DAG until it only uses operations and types that
3953 // the target supports.
3956 DEBUG(std::cerr << "Legalized selection DAG:\n");
3959 // Run the DAG combiner in post-legalize mode.
3960 DAG.Combine(true, AA);
3962 if (ViewISelDAGs) DAG.viewGraph();
3964 // Third, instruction select all of the operations to machine code, adding the
3965 // code to the MachineBasicBlock.
3966 InstructionSelectBasicBlock(DAG);
3968 DEBUG(std::cerr << "Selected machine code:\n");
3972 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3973 FunctionLoweringInfo &FuncInfo) {
3974 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3976 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3979 // First step, lower LLVM code to some DAG. This DAG may use operations and
3980 // types that are not supported by the target.
3981 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3983 // Second step, emit the lowered DAG as machine code.
3984 CodeGenAndEmitDAG(DAG);
3987 // Next, now that we know what the last MBB the LLVM BB expanded is, update
3988 // PHI nodes in successors.
3989 if (SwitchCases.empty() && JT.Reg == 0) {
3990 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3991 MachineInstr *PHI = PHINodesToUpdate[i].first;
3992 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3993 "This is not a machine PHI node that we are updating!");
3994 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
3995 PHI->addMachineBasicBlockOperand(BB);
4000 // If the JumpTable record is filled in, then we need to emit a jump table.
4001 // Updating the PHI nodes is tricky in this case, since we need to determine
4002 // whether the PHI is a successor of the range check MBB or the jump table MBB
4004 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4005 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4007 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4008 MachineBasicBlock *RangeBB = BB;
4009 // Set the current basic block to the mbb we wish to insert the code into
4011 SDL.setCurrentBasicBlock(BB);
4013 SDL.visitJumpTable(JT);
4014 SDAG.setRoot(SDL.getRoot());
4015 CodeGenAndEmitDAG(SDAG);
4017 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4018 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4019 MachineBasicBlock *PHIBB = PHI->getParent();
4020 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4021 "This is not a machine PHI node that we are updating!");
4022 if (PHIBB == JT.Default) {
4023 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4024 PHI->addMachineBasicBlockOperand(RangeBB);
4026 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4027 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4028 PHI->addMachineBasicBlockOperand(BB);
4034 // If the switch block involved a branch to one of the actual successors, we
4035 // need to update PHI nodes in that block.
4036 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4037 MachineInstr *PHI = PHINodesToUpdate[i].first;
4038 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4039 "This is not a machine PHI node that we are updating!");
4040 if (BB->isSuccessor(PHI->getParent())) {
4041 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4042 PHI->addMachineBasicBlockOperand(BB);
4046 // If we generated any switch lowering information, build and codegen any
4047 // additional DAGs necessary.
4048 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4049 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4051 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4053 // Set the current basic block to the mbb we wish to insert the code into
4054 BB = SwitchCases[i].ThisBB;
4055 SDL.setCurrentBasicBlock(BB);
4058 SDL.visitSwitchCase(SwitchCases[i]);
4059 SDAG.setRoot(SDL.getRoot());
4060 CodeGenAndEmitDAG(SDAG);
4062 // Handle any PHI nodes in successors of this chunk, as if we were coming
4063 // from the original BB before switch expansion. Note that PHI nodes can
4064 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4065 // handle them the right number of times.
4066 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4067 for (MachineBasicBlock::iterator Phi = BB->begin();
4068 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4069 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4070 for (unsigned pn = 0; ; ++pn) {
4071 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4072 if (PHINodesToUpdate[pn].first == Phi) {
4073 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4074 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4080 // Don't process RHS if same block as LHS.
4081 if (BB == SwitchCases[i].FalseBB)
4082 SwitchCases[i].FalseBB = 0;
4084 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4085 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4086 SwitchCases[i].FalseBB = 0;
4088 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4093 //===----------------------------------------------------------------------===//
4094 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4095 /// target node in the graph.
4096 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4097 if (ViewSchedDAGs) DAG.viewGraph();
4099 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4103 RegisterScheduler::setDefault(Ctor);
4106 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4112 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4113 return new HazardRecognizer();
4116 //===----------------------------------------------------------------------===//
4117 // Helper functions used by the generated instruction selector.
4118 //===----------------------------------------------------------------------===//
4119 // Calls to these methods are generated by tblgen.
4121 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
4122 /// the dag combiner simplified the 255, we still want to match. RHS is the
4123 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4124 /// specified in the .td file (e.g. 255).
4125 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4126 int64_t DesiredMaskS) {
4127 uint64_t ActualMask = RHS->getValue();
4128 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4130 // If the actual mask exactly matches, success!
4131 if (ActualMask == DesiredMask)
4134 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4135 if (ActualMask & ~DesiredMask)
4138 // Otherwise, the DAG Combiner may have proven that the value coming in is
4139 // either already zero or is not demanded. Check for known zero input bits.
4140 uint64_t NeededMask = DesiredMask & ~ActualMask;
4141 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4144 // TODO: check to see if missing bits are just not demanded.
4146 // Otherwise, this pattern doesn't match.
4150 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
4151 /// the dag combiner simplified the 255, we still want to match. RHS is the
4152 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4153 /// specified in the .td file (e.g. 255).
4154 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4155 int64_t DesiredMaskS) {
4156 uint64_t ActualMask = RHS->getValue();
4157 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4159 // If the actual mask exactly matches, success!
4160 if (ActualMask == DesiredMask)
4163 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4164 if (ActualMask & ~DesiredMask)
4167 // Otherwise, the DAG Combiner may have proven that the value coming in is
4168 // either already zero or is not demanded. Check for known zero input bits.
4169 uint64_t NeededMask = DesiredMask & ~ActualMask;
4171 uint64_t KnownZero, KnownOne;
4172 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4174 // If all the missing bits in the or are already known to be set, match!
4175 if ((NeededMask & KnownOne) == NeededMask)
4178 // TODO: check to see if missing bits are just not demanded.
4180 // Otherwise, this pattern doesn't match.
4185 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4186 /// by tblgen. Others should not call it.
4187 void SelectionDAGISel::
4188 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4189 std::vector<SDOperand> InOps;
4190 std::swap(InOps, Ops);
4192 Ops.push_back(InOps[0]); // input chain.
4193 Ops.push_back(InOps[1]); // input asm string.
4195 unsigned i = 2, e = InOps.size();
4196 if (InOps[e-1].getValueType() == MVT::Flag)
4197 --e; // Don't process a flag operand if it is here.
4200 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4201 if ((Flags & 7) != 4 /*MEM*/) {
4202 // Just skip over this operand, copying the operands verbatim.
4203 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4204 i += (Flags >> 3) + 1;
4206 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4207 // Otherwise, this is a memory operand. Ask the target to select it.
4208 std::vector<SDOperand> SelOps;
4209 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4210 std::cerr << "Could not match memory address. Inline asm failure!\n";
4214 // Add this to the output node.
4215 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4216 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4221 // Add the flag input back if present.
4222 if (e != InOps.size())
4223 Ops.push_back(InOps.back());