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/MachineDebugInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/SchedulerRegistry.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/CodeGen/SSARegMap.h"
35 #include "llvm/Target/MRegisterInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetFrameInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/Compiler.h"
52 ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
55 ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
58 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
62 //===---------------------------------------------------------------------===//
64 /// RegisterScheduler class - Track the registration of instruction schedulers.
66 //===---------------------------------------------------------------------===//
67 MachinePassRegistry RegisterScheduler::Registry;
69 //===---------------------------------------------------------------------===//
71 /// ISHeuristic command line option for instruction schedulers.
73 //===---------------------------------------------------------------------===//
75 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
78 cl::init(&createDefaultScheduler),
79 cl::desc("Instruction schedulers available:"));
81 static RegisterScheduler
82 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
91 struct VISIBILITY_HIDDEN RegsForValue {
92 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
95 std::vector<unsigned> Regs;
97 /// RegVT - The value type of each register.
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
111 RegsForValue(const std::vector<unsigned> ®s,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
120 SDOperand &Chain, SDOperand &Flag) const;
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
133 std::vector<SDOperand> &Ops) const;
138 //===--------------------------------------------------------------------===//
139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
156 //===--------------------------------------------------------------------===//
157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
159 class FunctionLoweringInfo {
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
174 std::map<const Value*, unsigned> ValueMap;
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
191 unsigned CreateRegForValue(const Value *V);
193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
201 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
202 /// PHI nodes or outside of the basic block that defines it, or used by a
203 /// switch instruction, which may expand to multiple basic blocks.
204 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
209 // FIXME: Remove switchinst special case.
210 isa<SwitchInst>(*UI))
215 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
216 /// entry block, return true. This includes arguments used by switches, since
217 /// the switch may expand into multiple basic blocks.
218 static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
222 return false; // Use not in entry block.
226 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
227 Function &fn, MachineFunction &mf)
228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
240 Function::iterator BB = Fn.begin(), EB = Fn.end();
241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
244 const Type *Ty = AI->getAllocatedType();
245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
247 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
250 // If the alignment of the value is smaller than the size of the
251 // value, and if the size of the value is particularly small
252 // (<= 8 bytes), round up to the size of the value for potentially
253 // better performance.
255 // FIXME: This could be made better with a preferred alignment hook in
256 // TargetData. It serves primarily to 8-byte align doubles for X86.
257 if (Align < TySize && TySize <= 8) Align = TySize;
258 TySize *= CUI->getZExtValue(); // Get total allocated size.
259 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
260 StaticAllocaMap[AI] =
261 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
264 for (; BB != EB; ++BB)
265 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
266 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
267 if (!isa<AllocaInst>(I) ||
268 !StaticAllocaMap.count(cast<AllocaInst>(I)))
269 InitializeRegForValue(I);
271 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
272 // also creates the initial PHI MachineInstrs, though none of the input
273 // operands are populated.
274 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
275 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
277 MF.getBasicBlockList().push_back(MBB);
279 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
282 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
283 if (PN->use_empty()) continue;
285 MVT::ValueType VT = TLI.getValueType(PN->getType());
286 unsigned NumElements;
287 if (VT != MVT::Vector)
288 NumElements = TLI.getNumElements(VT);
290 MVT::ValueType VT1,VT2;
292 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
295 unsigned PHIReg = ValueMap[PN];
296 assert(PHIReg && "PHI node does not have an assigned virtual register!");
297 for (unsigned i = 0; i != NumElements; ++i)
298 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
303 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
304 /// the correctly promoted or expanded types. Assign these registers
305 /// consecutive vreg numbers and return the first assigned number.
306 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
307 MVT::ValueType VT = TLI.getValueType(V->getType());
309 // The number of multiples of registers that we need, to, e.g., split up
310 // a <2 x int64> -> 4 x i32 registers.
311 unsigned NumVectorRegs = 1;
313 // If this is a packed type, figure out what type it will decompose into
314 // and how many of the elements it will use.
315 if (VT == MVT::Vector) {
316 const PackedType *PTy = cast<PackedType>(V->getType());
317 unsigned NumElts = PTy->getNumElements();
318 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
320 // Divide the input until we get to a supported size. This will always
321 // end with a scalar if the target doesn't support vectors.
322 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
329 VT = getVectorType(EltTy, NumElts);
332 // The common case is that we will only create one register for this
333 // value. If we have that case, create and return the virtual register.
334 unsigned NV = TLI.getNumElements(VT);
336 // If we are promoting this value, pick the next largest supported type.
337 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
338 unsigned Reg = MakeReg(PromotedType);
339 // If this is a vector of supported or promoted types (e.g. 4 x i16),
340 // create all of the registers.
341 for (unsigned i = 1; i != NumVectorRegs; ++i)
342 MakeReg(PromotedType);
346 // If this value is represented with multiple target registers, make sure
347 // to create enough consecutive registers of the right (smaller) type.
348 unsigned NT = VT-1; // Find the type to use.
349 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
352 unsigned R = MakeReg((MVT::ValueType)NT);
353 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
354 MakeReg((MVT::ValueType)NT);
358 //===----------------------------------------------------------------------===//
359 /// SelectionDAGLowering - This is the common target-independent lowering
360 /// implementation that is parameterized by a TargetLowering object.
361 /// Also, targets can overload any lowering method.
364 class SelectionDAGLowering {
365 MachineBasicBlock *CurMBB;
367 std::map<const Value*, SDOperand> NodeMap;
369 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
370 /// them up and then emit token factor nodes when possible. This allows us to
371 /// get simple disambiguation between loads without worrying about alias
373 std::vector<SDOperand> PendingLoads;
375 /// Case - A pair of values to record the Value for a switch case, and the
376 /// case's target basic block.
377 typedef std::pair<Constant*, MachineBasicBlock*> Case;
378 typedef std::vector<Case>::iterator CaseItr;
379 typedef std::pair<CaseItr, CaseItr> CaseRange;
381 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
382 /// of conditional branches.
384 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
385 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
387 /// CaseBB - The MBB in which to emit the compare and branch
388 MachineBasicBlock *CaseBB;
389 /// LT, GE - If nonzero, we know the current case value must be less-than or
390 /// greater-than-or-equal-to these Constants.
393 /// Range - A pair of iterators representing the range of case values to be
394 /// processed at this point in the binary search tree.
398 /// The comparison function for sorting Case values.
400 bool operator () (const Case& C1, const Case& C2) {
401 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
402 if (I1->getType()->isUnsigned())
403 return I1->getZExtValue() <
404 cast<const ConstantInt>(C2.first)->getZExtValue();
406 return cast<const ConstantInt>(C1.first)->getSExtValue() <
407 cast<const ConstantInt>(C2.first)->getSExtValue();
412 // TLI - This is information that describes the available target features we
413 // need for lowering. This indicates when operations are unavailable,
414 // implemented with a libcall, etc.
417 const TargetData *TD;
419 /// SwitchCases - Vector of CaseBlock structures used to communicate
420 /// SwitchInst code generation information.
421 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
422 SelectionDAGISel::JumpTable JT;
424 /// FuncInfo - Information about the function as a whole.
426 FunctionLoweringInfo &FuncInfo;
428 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
429 FunctionLoweringInfo &funcinfo)
430 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
431 JT(0,0,0,0), FuncInfo(funcinfo) {
434 /// getRoot - Return the current virtual root of the Selection DAG.
436 SDOperand getRoot() {
437 if (PendingLoads.empty())
438 return DAG.getRoot();
440 if (PendingLoads.size() == 1) {
441 SDOperand Root = PendingLoads[0];
443 PendingLoads.clear();
447 // Otherwise, we have to make a token factor node.
448 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
449 &PendingLoads[0], PendingLoads.size());
450 PendingLoads.clear();
455 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
457 void visit(Instruction &I) { visit(I.getOpcode(), I); }
459 void visit(unsigned Opcode, User &I) {
460 // Note: this doesn't use InstVisitor, because it has to work with
461 // ConstantExpr's in addition to instructions.
463 default: assert(0 && "Unknown instruction type encountered!");
465 // Build the switch statement using the Instruction.def file.
466 #define HANDLE_INST(NUM, OPCODE, CLASS) \
467 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
468 #include "llvm/Instruction.def"
472 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
474 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
475 const Value *SV, SDOperand Root,
478 SDOperand getIntPtrConstant(uint64_t Val) {
479 return DAG.getConstant(Val, TLI.getPointerTy());
482 SDOperand getValue(const Value *V);
484 const SDOperand &setValue(const Value *V, SDOperand NewN) {
485 SDOperand &N = NodeMap[V];
486 assert(N.Val == 0 && "Already set a value for this node!");
490 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
492 bool OutReg, bool InReg,
493 std::set<unsigned> &OutputRegs,
494 std::set<unsigned> &InputRegs);
496 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
497 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
499 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
500 void ExportFromCurrentBlock(Value *V);
502 // Terminator instructions.
503 void visitRet(ReturnInst &I);
504 void visitBr(BranchInst &I);
505 void visitSwitch(SwitchInst &I);
506 void visitUnreachable(UnreachableInst &I) { /* noop */ }
508 // Helper for visitSwitch
509 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
510 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
512 // These all get lowered before this pass.
513 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
514 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
516 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
517 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
518 void visitShift(User &I, unsigned Opcode);
519 void visitAdd(User &I) {
520 if (I.getType()->isFloatingPoint())
521 visitFPBinary(I, ISD::FADD, ISD::VADD);
523 visitIntBinary(I, ISD::ADD, ISD::VADD);
525 void visitSub(User &I);
526 void visitMul(User &I) {
527 if (I.getType()->isFloatingPoint())
528 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
530 visitIntBinary(I, ISD::MUL, ISD::VMUL);
532 void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
533 void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
534 void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
535 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
536 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
537 void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
538 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
539 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
540 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
541 void visitShl(User &I) { visitShift(I, ISD::SHL); }
542 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
543 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
544 void visitICmp(User &I);
545 void visitFCmp(User &I);
546 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
547 ISD::CondCode FPOpc);
548 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
550 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
552 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
554 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
556 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
558 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
561 void visitExtractElement(User &I);
562 void visitInsertElement(User &I);
563 void visitShuffleVector(User &I);
565 void visitGetElementPtr(User &I);
566 void visitCast(User &I);
567 void visitSelect(User &I);
569 void visitMalloc(MallocInst &I);
570 void visitFree(FreeInst &I);
571 void visitAlloca(AllocaInst &I);
572 void visitLoad(LoadInst &I);
573 void visitStore(StoreInst &I);
574 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
575 void visitCall(CallInst &I);
576 void visitInlineAsm(CallInst &I);
577 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
578 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
580 void visitVAStart(CallInst &I);
581 void visitVAArg(VAArgInst &I);
582 void visitVAEnd(CallInst &I);
583 void visitVACopy(CallInst &I);
584 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
586 void visitMemIntrinsic(CallInst &I, unsigned Op);
588 void visitUserOp1(Instruction &I) {
589 assert(0 && "UserOp1 should not exist at instruction selection time!");
592 void visitUserOp2(Instruction &I) {
593 assert(0 && "UserOp2 should not exist at instruction selection time!");
597 } // end namespace llvm
599 SDOperand SelectionDAGLowering::getValue(const Value *V) {
600 SDOperand &N = NodeMap[V];
603 const Type *VTy = V->getType();
604 MVT::ValueType VT = TLI.getValueType(VTy);
605 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
606 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
607 visit(CE->getOpcode(), *CE);
608 assert(N.Val && "visit didn't populate the ValueMap!");
610 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
611 return N = DAG.getGlobalAddress(GV, VT);
612 } else if (isa<ConstantPointerNull>(C)) {
613 return N = DAG.getConstant(0, TLI.getPointerTy());
614 } else if (isa<UndefValue>(C)) {
615 if (!isa<PackedType>(VTy))
616 return N = DAG.getNode(ISD::UNDEF, VT);
618 // Create a VBUILD_VECTOR of undef nodes.
619 const PackedType *PTy = cast<PackedType>(VTy);
620 unsigned NumElements = PTy->getNumElements();
621 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
623 SmallVector<SDOperand, 8> Ops;
624 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
626 // Create a VConstant node with generic Vector type.
627 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
628 Ops.push_back(DAG.getValueType(PVT));
629 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
630 &Ops[0], Ops.size());
631 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
632 return N = DAG.getConstantFP(CFP->getValue(), VT);
633 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
634 unsigned NumElements = PTy->getNumElements();
635 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
637 // Now that we know the number and type of the elements, push a
638 // Constant or ConstantFP node onto the ops list for each element of
639 // the packed constant.
640 SmallVector<SDOperand, 8> Ops;
641 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
642 for (unsigned i = 0; i != NumElements; ++i)
643 Ops.push_back(getValue(CP->getOperand(i)));
645 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
647 if (MVT::isFloatingPoint(PVT))
648 Op = DAG.getConstantFP(0, PVT);
650 Op = DAG.getConstant(0, PVT);
651 Ops.assign(NumElements, Op);
654 // Create a VBUILD_VECTOR node with generic Vector type.
655 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
656 Ops.push_back(DAG.getValueType(PVT));
657 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
659 // Canonicalize all constant ints to be unsigned.
660 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
664 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
665 std::map<const AllocaInst*, int>::iterator SI =
666 FuncInfo.StaticAllocaMap.find(AI);
667 if (SI != FuncInfo.StaticAllocaMap.end())
668 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
671 std::map<const Value*, unsigned>::const_iterator VMI =
672 FuncInfo.ValueMap.find(V);
673 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
675 unsigned InReg = VMI->second;
677 // If this type is not legal, make it so now.
678 if (VT != MVT::Vector) {
679 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
681 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
683 // Source must be expanded. This input value is actually coming from the
684 // register pair VMI->second and VMI->second+1.
685 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
686 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
687 } else if (DestVT > VT) { // Promotion case
688 if (MVT::isFloatingPoint(VT))
689 N = DAG.getNode(ISD::FP_ROUND, VT, N);
691 N = DAG.getNode(ISD::TRUNCATE, VT, N);
694 // Otherwise, if this is a vector, make it available as a generic vector
696 MVT::ValueType PTyElementVT, PTyLegalElementVT;
697 const PackedType *PTy = cast<PackedType>(VTy);
698 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
701 // Build a VBUILD_VECTOR with the input registers.
702 SmallVector<SDOperand, 8> Ops;
703 if (PTyElementVT == PTyLegalElementVT) {
704 // If the value types are legal, just VBUILD the CopyFromReg nodes.
705 for (unsigned i = 0; i != NE; ++i)
706 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
708 } else if (PTyElementVT < PTyLegalElementVT) {
709 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
710 for (unsigned i = 0; i != NE; ++i) {
711 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
713 if (MVT::isFloatingPoint(PTyElementVT))
714 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
716 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
720 // If the register was expanded, use BUILD_PAIR.
721 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
722 for (unsigned i = 0; i != NE/2; ++i) {
723 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
725 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
727 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
731 Ops.push_back(DAG.getConstant(NE, MVT::i32));
732 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
733 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
735 // Finally, use a VBIT_CONVERT to make this available as the appropriate
737 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
738 DAG.getConstant(PTy->getNumElements(),
740 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
747 void SelectionDAGLowering::visitRet(ReturnInst &I) {
748 if (I.getNumOperands() == 0) {
749 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
752 SmallVector<SDOperand, 8> NewValues;
753 NewValues.push_back(getRoot());
754 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
755 SDOperand RetOp = getValue(I.getOperand(i));
756 bool isSigned = I.getOperand(i)->getType()->isSigned();
758 // If this is an integer return value, we need to promote it ourselves to
759 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
761 // FIXME: C calling convention requires the return type to be promoted to
762 // at least 32-bit. But this is not necessary for non-C calling conventions.
763 if (MVT::isInteger(RetOp.getValueType()) &&
764 RetOp.getValueType() < MVT::i64) {
765 MVT::ValueType TmpVT;
766 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
767 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
772 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
774 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
776 NewValues.push_back(RetOp);
777 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
779 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
780 &NewValues[0], NewValues.size()));
783 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
784 /// the current basic block, add it to ValueMap now so that we'll get a
786 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
787 // No need to export constants.
788 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
791 if (FuncInfo.isExportedInst(V)) return;
793 unsigned Reg = FuncInfo.InitializeRegForValue(V);
794 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
797 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
798 const BasicBlock *FromBB) {
799 // The operands of the setcc have to be in this block. We don't know
800 // how to export them from some other block.
801 if (Instruction *VI = dyn_cast<Instruction>(V)) {
802 // Can export from current BB.
803 if (VI->getParent() == FromBB)
806 // Is already exported, noop.
807 return FuncInfo.isExportedInst(V);
810 // If this is an argument, we can export it if the BB is the entry block or
811 // if it is already exported.
812 if (isa<Argument>(V)) {
813 if (FromBB == &FromBB->getParent()->getEntryBlock())
816 // Otherwise, can only export this if it is already exported.
817 return FuncInfo.isExportedInst(V);
820 // Otherwise, constants can always be exported.
824 static bool InBlock(const Value *V, const BasicBlock *BB) {
825 if (const Instruction *I = dyn_cast<Instruction>(V))
826 return I->getParent() == BB;
830 /// FindMergedConditions - If Cond is an expression like
831 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
832 MachineBasicBlock *TBB,
833 MachineBasicBlock *FBB,
834 MachineBasicBlock *CurBB,
836 // If this node is not part of the or/and tree, emit it as a branch.
837 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
839 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
840 BOp->getParent() != CurBB->getBasicBlock() ||
841 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
842 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
843 const BasicBlock *BB = CurBB->getBasicBlock();
845 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
846 if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
847 II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
848 // The operands of the setcc have to be in this block. We don't know
849 // how to export them from some other block. If this is the first
850 // block of the sequence, no exporting is needed.
852 (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
853 isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
854 SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
855 II->getOperand(2), TBB, FBB, CurBB);
856 SwitchCases.push_back(CB);
861 // If the leaf of the tree is a setcond inst, merge the condition into the
863 if (BOp && isa<SetCondInst>(BOp) &&
864 // The operands of the setcc have to be in this block. We don't know
865 // how to export them from some other block. If this is the first block
866 // of the sequence, no exporting is needed.
868 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
869 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
870 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
871 switch (BOp->getOpcode()) {
872 default: assert(0 && "Unknown setcc opcode!");
873 case Instruction::SetEQ:
874 SignCond = ISD::SETEQ;
875 UnsCond = ISD::SETEQ;
876 FPCond = ISD::SETOEQ;
878 case Instruction::SetNE:
879 SignCond = ISD::SETNE;
880 UnsCond = ISD::SETNE;
881 FPCond = ISD::SETUNE;
883 case Instruction::SetLE:
884 SignCond = ISD::SETLE;
885 UnsCond = ISD::SETULE;
886 FPCond = ISD::SETOLE;
888 case Instruction::SetGE:
889 SignCond = ISD::SETGE;
890 UnsCond = ISD::SETUGE;
891 FPCond = ISD::SETOGE;
893 case Instruction::SetLT:
894 SignCond = ISD::SETLT;
895 UnsCond = ISD::SETULT;
896 FPCond = ISD::SETOLT;
898 case Instruction::SetGT:
899 SignCond = ISD::SETGT;
900 UnsCond = ISD::SETUGT;
901 FPCond = ISD::SETOGT;
905 const Type *OpType = BOp->getOperand(0)->getType();
906 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
907 OpType = PTy->getElementType();
909 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
911 else if (OpType->isUnsigned())
914 Condition = SignCond;
916 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
917 BOp->getOperand(1), TBB, FBB, CurBB);
918 SwitchCases.push_back(CB);
922 // Create a CaseBlock record representing this branch.
923 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
925 SwitchCases.push_back(CB);
930 // Create TmpBB after CurBB.
931 MachineFunction::iterator BBI = CurBB;
932 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
933 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
935 if (Opc == Instruction::Or) {
944 // Emit the LHS condition.
945 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
947 // Emit the RHS condition into TmpBB.
948 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
950 assert(Opc == Instruction::And && "Unknown merge op!");
958 // This requires creation of TmpBB after CurBB.
960 // Emit the LHS condition.
961 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
963 // Emit the RHS condition into TmpBB.
964 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
968 /// If the set of cases should be emitted as a series of branches, return true.
969 /// If we should emit this as a bunch of and/or'd together conditions, return
972 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
973 if (Cases.size() != 2) return true;
975 // If this is two comparisons of the same values or'd or and'd together, they
976 // will get folded into a single comparison, so don't emit two blocks.
977 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
978 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
979 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
980 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
987 void SelectionDAGLowering::visitBr(BranchInst &I) {
988 // Update machine-CFG edges.
989 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
991 // Figure out which block is immediately after the current one.
992 MachineBasicBlock *NextBlock = 0;
993 MachineFunction::iterator BBI = CurMBB;
994 if (++BBI != CurMBB->getParent()->end())
997 if (I.isUnconditional()) {
998 // If this is not a fall-through branch, emit the branch.
999 if (Succ0MBB != NextBlock)
1000 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1001 DAG.getBasicBlock(Succ0MBB)));
1003 // Update machine-CFG edges.
1004 CurMBB->addSuccessor(Succ0MBB);
1009 // If this condition is one of the special cases we handle, do special stuff
1011 Value *CondVal = I.getCondition();
1012 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1014 // If this is a series of conditions that are or'd or and'd together, emit
1015 // this as a sequence of branches instead of setcc's with and/or operations.
1016 // For example, instead of something like:
1029 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1030 if (BOp->hasOneUse() &&
1031 (BOp->getOpcode() == Instruction::And ||
1032 BOp->getOpcode() == Instruction::Or)) {
1033 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1034 // If the compares in later blocks need to use values not currently
1035 // exported from this block, export them now. This block should always
1036 // be the first entry.
1037 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1039 // Allow some cases to be rejected.
1040 if (ShouldEmitAsBranches(SwitchCases)) {
1041 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1042 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1043 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1046 // Emit the branch for this block.
1047 visitSwitchCase(SwitchCases[0]);
1048 SwitchCases.erase(SwitchCases.begin());
1052 // Okay, we decided not to do this, remove any inserted MBB's and clear
1054 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1055 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1057 SwitchCases.clear();
1061 // Create a CaseBlock record representing this branch.
1062 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
1063 Succ0MBB, Succ1MBB, CurMBB);
1064 // Use visitSwitchCase to actually insert the fast branch sequence for this
1066 visitSwitchCase(CB);
1069 /// visitSwitchCase - Emits the necessary code to represent a single node in
1070 /// the binary search tree resulting from lowering a switch instruction.
1071 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1073 SDOperand CondLHS = getValue(CB.CmpLHS);
1075 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1076 // handle common cases produced by branch lowering.
1077 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
1079 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1080 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1081 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1083 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1085 // Set NextBlock to be the MBB immediately after the current one, if any.
1086 // This is used to avoid emitting unnecessary branches to the next block.
1087 MachineBasicBlock *NextBlock = 0;
1088 MachineFunction::iterator BBI = CurMBB;
1089 if (++BBI != CurMBB->getParent()->end())
1092 // If the lhs block is the next block, invert the condition so that we can
1093 // fall through to the lhs instead of the rhs block.
1094 if (CB.TrueBB == NextBlock) {
1095 std::swap(CB.TrueBB, CB.FalseBB);
1096 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1097 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1099 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1100 DAG.getBasicBlock(CB.TrueBB));
1101 if (CB.FalseBB == NextBlock)
1102 DAG.setRoot(BrCond);
1104 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1105 DAG.getBasicBlock(CB.FalseBB)));
1106 // Update successor info
1107 CurMBB->addSuccessor(CB.TrueBB);
1108 CurMBB->addSuccessor(CB.FalseBB);
1111 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1112 // Emit the code for the jump table
1113 MVT::ValueType PTy = TLI.getPointerTy();
1114 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1115 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1116 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1121 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1122 // Figure out which block is immediately after the current one.
1123 MachineBasicBlock *NextBlock = 0;
1124 MachineFunction::iterator BBI = CurMBB;
1126 if (++BBI != CurMBB->getParent()->end())
1129 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1131 // If there is only the default destination, branch to it if it is not the
1132 // next basic block. Otherwise, just fall through.
1133 if (I.getNumOperands() == 2) {
1134 // Update machine-CFG edges.
1136 // If this is not a fall-through branch, emit the branch.
1137 if (Default != NextBlock)
1138 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1139 DAG.getBasicBlock(Default)));
1141 CurMBB->addSuccessor(Default);
1145 // If there are any non-default case statements, create a vector of Cases
1146 // representing each one, and sort the vector so that we can efficiently
1147 // create a binary search tree from them.
1148 std::vector<Case> Cases;
1150 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1151 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1152 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1155 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1157 // Get the Value to be switched on and default basic blocks, which will be
1158 // inserted into CaseBlock records, representing basic blocks in the binary
1160 Value *SV = I.getOperand(0);
1162 // Get the MachineFunction which holds the current MBB. This is used during
1163 // emission of jump tables, and when inserting any additional MBBs necessary
1164 // to represent the switch.
1165 MachineFunction *CurMF = CurMBB->getParent();
1166 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
1168 // If the switch has few cases (two or less) emit a series of specific
1170 if (Cases.size() < 3) {
1171 // TODO: If any two of the cases has the same destination, and if one value
1172 // is the same as the other, but has one bit unset that the other has set,
1173 // use bit manipulation to do two compares at once. For example:
1174 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1176 // Rearrange the case blocks so that the last one falls through if possible.
1177 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1178 // The last case block won't fall through into 'NextBlock' if we emit the
1179 // branches in this order. See if rearranging a case value would help.
1180 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1181 if (Cases[i].second == NextBlock) {
1182 std::swap(Cases[i], Cases.back());
1188 // Create a CaseBlock record representing a conditional branch to
1189 // the Case's target mbb if the value being switched on SV is equal
1191 MachineBasicBlock *CurBlock = CurMBB;
1192 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1193 MachineBasicBlock *FallThrough;
1195 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1196 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1198 // If the last case doesn't match, go to the default block.
1199 FallThrough = Default;
1202 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1203 Cases[i].second, FallThrough, CurBlock);
1205 // If emitting the first comparison, just call visitSwitchCase to emit the
1206 // code into the current block. Otherwise, push the CaseBlock onto the
1207 // vector to be later processed by SDISel, and insert the node's MBB
1208 // before the next MBB.
1209 if (CurBlock == CurMBB)
1210 visitSwitchCase(CB);
1212 SwitchCases.push_back(CB);
1214 CurBlock = FallThrough;
1219 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1220 // target supports indirect branches, then emit a jump table rather than
1221 // lowering the switch to a binary tree of conditional branches.
1222 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1223 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
1225 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1226 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
1227 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1229 if (Density >= 0.3125) {
1230 // Create a new basic block to hold the code for loading the address
1231 // of the jump table, and jumping to it. Update successor information;
1232 // we will either branch to the default case for the switch, or the jump
1234 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1235 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1236 CurMBB->addSuccessor(Default);
1237 CurMBB->addSuccessor(JumpTableBB);
1239 // Subtract the lowest switch case value from the value being switched on
1240 // and conditional branch to default mbb if the result is greater than the
1241 // difference between smallest and largest cases.
1242 SDOperand SwitchOp = getValue(SV);
1243 MVT::ValueType VT = SwitchOp.getValueType();
1244 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1245 DAG.getConstant(First, VT));
1247 // The SDNode we just created, which holds the value being switched on
1248 // minus the the smallest case value, needs to be copied to a virtual
1249 // register so it can be used as an index into the jump table in a
1250 // subsequent basic block. This value may be smaller or larger than the
1251 // target's pointer type, and therefore require extension or truncating.
1252 if (VT > TLI.getPointerTy())
1253 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1255 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1257 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1258 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1260 // Emit the range check for the jump table, and branch to the default
1261 // block for the switch statement if the value being switched on exceeds
1262 // the largest case in the switch.
1263 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1264 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1265 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1266 DAG.getBasicBlock(Default)));
1268 // Build a vector of destination BBs, corresponding to each target
1269 // of the jump table. If the value of the jump table slot corresponds to
1270 // a case statement, push the case's BB onto the vector, otherwise, push
1272 std::vector<MachineBasicBlock*> DestBBs;
1273 uint64_t TEI = First;
1274 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
1275 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
1276 DestBBs.push_back(ii->second);
1279 DestBBs.push_back(Default);
1282 // Update successor info. Add one edge to each unique successor.
1283 // Vector bool would be better, but vector<bool> is really slow.
1284 std::vector<unsigned char> SuccsHandled;
1285 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1287 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1288 E = DestBBs.end(); I != E; ++I) {
1289 if (!SuccsHandled[(*I)->getNumber()]) {
1290 SuccsHandled[(*I)->getNumber()] = true;
1291 JumpTableBB->addSuccessor(*I);
1295 // Create a jump table index for this jump table, or return an existing
1297 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1299 // Set the jump table information so that we can codegen it as a second
1300 // MachineBasicBlock
1301 JT.Reg = JumpTableReg;
1303 JT.MBB = JumpTableBB;
1304 JT.Default = Default;
1309 // Push the initial CaseRec onto the worklist
1310 std::vector<CaseRec> CaseVec;
1311 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1313 while (!CaseVec.empty()) {
1314 // Grab a record representing a case range to process off the worklist
1315 CaseRec CR = CaseVec.back();
1318 // Size is the number of Cases represented by this range. If Size is 1,
1319 // then we are processing a leaf of the binary search tree. Otherwise,
1320 // we need to pick a pivot, and push left and right ranges onto the
1322 unsigned Size = CR.Range.second - CR.Range.first;
1325 // Create a CaseBlock record representing a conditional branch to
1326 // the Case's target mbb if the value being switched on SV is equal
1327 // to C. Otherwise, branch to default.
1328 Constant *C = CR.Range.first->first;
1329 MachineBasicBlock *Target = CR.Range.first->second;
1330 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1333 // If the MBB representing the leaf node is the current MBB, then just
1334 // call visitSwitchCase to emit the code into the current block.
1335 // Otherwise, push the CaseBlock onto the vector to be later processed
1336 // by SDISel, and insert the node's MBB before the next MBB.
1337 if (CR.CaseBB == CurMBB)
1338 visitSwitchCase(CB);
1340 SwitchCases.push_back(CB);
1342 // split case range at pivot
1343 CaseItr Pivot = CR.Range.first + (Size / 2);
1344 CaseRange LHSR(CR.Range.first, Pivot);
1345 CaseRange RHSR(Pivot, CR.Range.second);
1346 Constant *C = Pivot->first;
1347 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1349 // We know that we branch to the LHS if the Value being switched on is
1350 // less than the Pivot value, C. We use this to optimize our binary
1351 // tree a bit, by recognizing that if SV is greater than or equal to the
1352 // LHS's Case Value, and that Case Value is exactly one less than the
1353 // Pivot's Value, then we can branch directly to the LHS's Target,
1354 // rather than creating a leaf node for it.
1355 if ((LHSR.second - LHSR.first) == 1 &&
1356 LHSR.first->first == CR.GE &&
1357 cast<ConstantIntegral>(C)->getZExtValue() ==
1358 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
1359 TrueBB = LHSR.first->second;
1361 TrueBB = new MachineBasicBlock(LLVMBB);
1362 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1363 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1366 // Similar to the optimization above, if the Value being switched on is
1367 // known to be less than the Constant CR.LT, and the current Case Value
1368 // is CR.LT - 1, then we can branch directly to the target block for
1369 // the current Case Value, rather than emitting a RHS leaf node for it.
1370 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1371 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1372 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
1373 FalseBB = RHSR.first->second;
1375 FalseBB = new MachineBasicBlock(LLVMBB);
1376 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1377 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1380 // Create a CaseBlock record representing a conditional branch to
1381 // the LHS node if the value being switched on SV is less than C.
1382 // Otherwise, branch to LHS.
1383 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1384 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
1386 if (CR.CaseBB == CurMBB)
1387 visitSwitchCase(CB);
1389 SwitchCases.push_back(CB);
1394 void SelectionDAGLowering::visitSub(User &I) {
1395 // -0.0 - X --> fneg
1396 if (I.getType()->isFloatingPoint()) {
1397 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1398 if (CFP->isExactlyValue(-0.0)) {
1399 SDOperand Op2 = getValue(I.getOperand(1));
1400 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1403 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1405 visitIntBinary(I, ISD::SUB, ISD::VSUB);
1409 SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
1410 const Type *Ty = I.getType();
1411 SDOperand Op1 = getValue(I.getOperand(0));
1412 SDOperand Op2 = getValue(I.getOperand(1));
1414 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1415 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1416 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1417 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1419 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1424 SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1425 const Type *Ty = I.getType();
1426 SDOperand Op1 = getValue(I.getOperand(0));
1427 SDOperand Op2 = getValue(I.getOperand(1));
1429 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1430 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1431 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1432 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1434 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1438 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1439 SDOperand Op1 = getValue(I.getOperand(0));
1440 SDOperand Op2 = getValue(I.getOperand(1));
1442 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1444 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1447 void SelectionDAGLowering::visitICmp(User &I) {
1448 ICmpInst *IC = cast<ICmpInst>(&I);
1449 SDOperand Op1 = getValue(IC->getOperand(0));
1450 SDOperand Op2 = getValue(IC->getOperand(1));
1451 ISD::CondCode Opcode;
1452 switch (IC->getPredicate()) {
1453 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1454 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1455 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1456 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1457 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1458 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1459 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1460 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1461 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1462 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1464 assert(!"Invalid ICmp predicate value");
1465 Opcode = ISD::SETEQ;
1468 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1471 void SelectionDAGLowering::visitFCmp(User &I) {
1472 FCmpInst *FC = cast<FCmpInst>(&I);
1473 SDOperand Op1 = getValue(FC->getOperand(0));
1474 SDOperand Op2 = getValue(FC->getOperand(1));
1475 ISD::CondCode Opcode;
1476 switch (FC->getPredicate()) {
1477 case FCmpInst::FCMP_FALSE : Opcode = ISD::SETFALSE;
1478 case FCmpInst::FCMP_OEQ : Opcode = ISD::SETOEQ;
1479 case FCmpInst::FCMP_OGT : Opcode = ISD::SETOGT;
1480 case FCmpInst::FCMP_OGE : Opcode = ISD::SETOGE;
1481 case FCmpInst::FCMP_OLT : Opcode = ISD::SETOLT;
1482 case FCmpInst::FCMP_OLE : Opcode = ISD::SETOLE;
1483 case FCmpInst::FCMP_ONE : Opcode = ISD::SETONE;
1484 case FCmpInst::FCMP_ORD : Opcode = ISD::SETO;
1485 case FCmpInst::FCMP_UNO : Opcode = ISD::SETUO;
1486 case FCmpInst::FCMP_UEQ : Opcode = ISD::SETUEQ;
1487 case FCmpInst::FCMP_UGT : Opcode = ISD::SETUGT;
1488 case FCmpInst::FCMP_UGE : Opcode = ISD::SETUGE;
1489 case FCmpInst::FCMP_ULT : Opcode = ISD::SETULT;
1490 case FCmpInst::FCMP_ULE : Opcode = ISD::SETULE;
1491 case FCmpInst::FCMP_UNE : Opcode = ISD::SETUNE;
1492 case FCmpInst::FCMP_TRUE : Opcode = ISD::SETTRUE;
1494 assert(!"Invalid FCmp predicate value");
1495 Opcode = ISD::SETFALSE;
1498 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1501 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
1502 ISD::CondCode UnsignedOpcode,
1503 ISD::CondCode FPOpcode) {
1504 SDOperand Op1 = getValue(I.getOperand(0));
1505 SDOperand Op2 = getValue(I.getOperand(1));
1506 ISD::CondCode Opcode = SignedOpcode;
1507 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
1509 else if (I.getOperand(0)->getType()->isUnsigned())
1510 Opcode = UnsignedOpcode;
1511 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1514 void SelectionDAGLowering::visitSelect(User &I) {
1515 SDOperand Cond = getValue(I.getOperand(0));
1516 SDOperand TrueVal = getValue(I.getOperand(1));
1517 SDOperand FalseVal = getValue(I.getOperand(2));
1518 if (!isa<PackedType>(I.getType())) {
1519 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1520 TrueVal, FalseVal));
1522 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1523 *(TrueVal.Val->op_end()-2),
1524 *(TrueVal.Val->op_end()-1)));
1528 void SelectionDAGLowering::visitCast(User &I) {
1529 SDOperand N = getValue(I.getOperand(0));
1530 MVT::ValueType SrcVT = N.getValueType();
1531 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1533 if (DestVT == MVT::Vector) {
1534 // This is a cast to a vector from something else. This is always a bit
1535 // convert. Get information about the input vector.
1536 const PackedType *DestTy = cast<PackedType>(I.getType());
1537 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1538 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1539 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1540 DAG.getValueType(EltVT)));
1541 } else if (SrcVT == DestVT) {
1542 setValue(&I, N); // noop cast.
1543 } else if (DestVT == MVT::i1) {
1544 // Cast to bool is a comparison against zero, not truncation to zero.
1545 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
1546 DAG.getConstantFP(0.0, N.getValueType());
1547 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
1548 } else if (isInteger(SrcVT)) {
1549 if (isInteger(DestVT)) { // Int -> Int cast
1550 if (DestVT < SrcVT) // Truncating cast?
1551 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1552 else if (I.getOperand(0)->getType()->isSigned())
1553 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1555 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1556 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
1557 if (I.getOperand(0)->getType()->isSigned())
1558 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1560 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1562 assert(0 && "Unknown cast!");
1564 } else if (isFloatingPoint(SrcVT)) {
1565 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1566 if (DestVT < SrcVT) // Rounding cast?
1567 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1569 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1570 } else if (isInteger(DestVT)) { // FP -> Int cast.
1571 if (I.getType()->isSigned())
1572 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1574 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1576 assert(0 && "Unknown cast!");
1579 assert(SrcVT == MVT::Vector && "Unknown cast!");
1580 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1581 // This is a cast from a vector to something else. This is always a bit
1582 // convert. Get information about the input vector.
1583 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1587 void SelectionDAGLowering::visitInsertElement(User &I) {
1588 SDOperand InVec = getValue(I.getOperand(0));
1589 SDOperand InVal = getValue(I.getOperand(1));
1590 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1591 getValue(I.getOperand(2)));
1593 SDOperand Num = *(InVec.Val->op_end()-2);
1594 SDOperand Typ = *(InVec.Val->op_end()-1);
1595 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1596 InVec, InVal, InIdx, Num, Typ));
1599 void SelectionDAGLowering::visitExtractElement(User &I) {
1600 SDOperand InVec = getValue(I.getOperand(0));
1601 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1602 getValue(I.getOperand(1)));
1603 SDOperand Typ = *(InVec.Val->op_end()-1);
1604 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1605 TLI.getValueType(I.getType()), InVec, InIdx));
1608 void SelectionDAGLowering::visitShuffleVector(User &I) {
1609 SDOperand V1 = getValue(I.getOperand(0));
1610 SDOperand V2 = getValue(I.getOperand(1));
1611 SDOperand Mask = getValue(I.getOperand(2));
1613 SDOperand Num = *(V1.Val->op_end()-2);
1614 SDOperand Typ = *(V2.Val->op_end()-1);
1615 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1616 V1, V2, Mask, Num, Typ));
1620 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1621 SDOperand N = getValue(I.getOperand(0));
1622 const Type *Ty = I.getOperand(0)->getType();
1624 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1627 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1628 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
1631 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1632 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1633 getIntPtrConstant(Offset));
1635 Ty = StTy->getElementType(Field);
1637 Ty = cast<SequentialType>(Ty)->getElementType();
1639 // If this is a constant subscript, handle it quickly.
1640 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1641 if (CI->getZExtValue() == 0) continue;
1643 if (CI->getType()->isSigned())
1645 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
1648 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
1649 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1653 // N = N + Idx * ElementSize;
1654 uint64_t ElementSize = TD->getTypeSize(Ty);
1655 SDOperand IdxN = getValue(Idx);
1657 // If the index is smaller or larger than intptr_t, truncate or extend
1659 if (IdxN.getValueType() < N.getValueType()) {
1660 if (Idx->getType()->isSigned())
1661 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1663 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1664 } else if (IdxN.getValueType() > N.getValueType())
1665 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1667 // If this is a multiply by a power of two, turn it into a shl
1668 // immediately. This is a very common case.
1669 if (isPowerOf2_64(ElementSize)) {
1670 unsigned Amt = Log2_64(ElementSize);
1671 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1672 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1673 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1677 SDOperand Scale = getIntPtrConstant(ElementSize);
1678 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1679 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1685 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1686 // If this is a fixed sized alloca in the entry block of the function,
1687 // allocate it statically on the stack.
1688 if (FuncInfo.StaticAllocaMap.count(&I))
1689 return; // getValue will auto-populate this.
1691 const Type *Ty = I.getAllocatedType();
1692 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1693 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
1696 SDOperand AllocSize = getValue(I.getArraySize());
1697 MVT::ValueType IntPtr = TLI.getPointerTy();
1698 if (IntPtr < AllocSize.getValueType())
1699 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1700 else if (IntPtr > AllocSize.getValueType())
1701 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1703 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1704 getIntPtrConstant(TySize));
1706 // Handle alignment. If the requested alignment is less than or equal to the
1707 // stack alignment, ignore it and round the size of the allocation up to the
1708 // stack alignment size. If the size is greater than the stack alignment, we
1709 // note this in the DYNAMIC_STACKALLOC node.
1710 unsigned StackAlign =
1711 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1712 if (Align <= StackAlign) {
1714 // Add SA-1 to the size.
1715 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1716 getIntPtrConstant(StackAlign-1));
1717 // Mask out the low bits for alignment purposes.
1718 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1719 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1722 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
1723 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1725 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
1726 DAG.setRoot(setValue(&I, DSA).getValue(1));
1728 // Inform the Frame Information that we have just allocated a variable-sized
1730 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1733 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1734 SDOperand Ptr = getValue(I.getOperand(0));
1740 // Do not serialize non-volatile loads against each other.
1741 Root = DAG.getRoot();
1744 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
1745 Root, I.isVolatile()));
1748 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1749 const Value *SV, SDOperand Root,
1752 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1753 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1754 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1755 DAG.getSrcValue(SV));
1757 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
1761 DAG.setRoot(L.getValue(1));
1763 PendingLoads.push_back(L.getValue(1));
1769 void SelectionDAGLowering::visitStore(StoreInst &I) {
1770 Value *SrcV = I.getOperand(0);
1771 SDOperand Src = getValue(SrcV);
1772 SDOperand Ptr = getValue(I.getOperand(1));
1773 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1777 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1778 /// access memory and has no other side effects at all.
1779 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1780 #define GET_NO_MEMORY_INTRINSICS
1781 #include "llvm/Intrinsics.gen"
1782 #undef GET_NO_MEMORY_INTRINSICS
1786 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1787 // have any side-effects or if it only reads memory.
1788 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1789 #define GET_SIDE_EFFECT_INFO
1790 #include "llvm/Intrinsics.gen"
1791 #undef GET_SIDE_EFFECT_INFO
1795 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1797 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1798 unsigned Intrinsic) {
1799 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1800 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1802 // Build the operand list.
1803 SmallVector<SDOperand, 8> Ops;
1804 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1806 // We don't need to serialize loads against other loads.
1807 Ops.push_back(DAG.getRoot());
1809 Ops.push_back(getRoot());
1813 // Add the intrinsic ID as an integer operand.
1814 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1816 // Add all operands of the call to the operand list.
1817 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1818 SDOperand Op = getValue(I.getOperand(i));
1820 // If this is a vector type, force it to the right packed type.
1821 if (Op.getValueType() == MVT::Vector) {
1822 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1823 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1825 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1826 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1827 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1830 assert(TLI.isTypeLegal(Op.getValueType()) &&
1831 "Intrinsic uses a non-legal type?");
1835 std::vector<MVT::ValueType> VTs;
1836 if (I.getType() != Type::VoidTy) {
1837 MVT::ValueType VT = TLI.getValueType(I.getType());
1838 if (VT == MVT::Vector) {
1839 const PackedType *DestTy = cast<PackedType>(I.getType());
1840 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1842 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1843 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1846 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1850 VTs.push_back(MVT::Other);
1852 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1857 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1858 &Ops[0], Ops.size());
1859 else if (I.getType() != Type::VoidTy)
1860 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1861 &Ops[0], Ops.size());
1863 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1864 &Ops[0], Ops.size());
1867 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1869 PendingLoads.push_back(Chain);
1873 if (I.getType() != Type::VoidTy) {
1874 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1875 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1876 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1877 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1878 DAG.getValueType(EVT));
1880 setValue(&I, Result);
1884 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1885 /// we want to emit this as a call to a named external function, return the name
1886 /// otherwise lower it and return null.
1888 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1889 switch (Intrinsic) {
1891 // By default, turn this into a target intrinsic node.
1892 visitTargetIntrinsic(I, Intrinsic);
1894 case Intrinsic::vastart: visitVAStart(I); return 0;
1895 case Intrinsic::vaend: visitVAEnd(I); return 0;
1896 case Intrinsic::vacopy: visitVACopy(I); return 0;
1897 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1898 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1899 case Intrinsic::setjmp:
1900 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1902 case Intrinsic::longjmp:
1903 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1905 case Intrinsic::memcpy_i32:
1906 case Intrinsic::memcpy_i64:
1907 visitMemIntrinsic(I, ISD::MEMCPY);
1909 case Intrinsic::memset_i32:
1910 case Intrinsic::memset_i64:
1911 visitMemIntrinsic(I, ISD::MEMSET);
1913 case Intrinsic::memmove_i32:
1914 case Intrinsic::memmove_i64:
1915 visitMemIntrinsic(I, ISD::MEMMOVE);
1918 case Intrinsic::dbg_stoppoint: {
1919 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1920 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1921 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1925 Ops[1] = getValue(SPI.getLineValue());
1926 Ops[2] = getValue(SPI.getColumnValue());
1928 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1929 assert(DD && "Not a debug information descriptor");
1930 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1932 Ops[3] = DAG.getString(CompileUnit->getFileName());
1933 Ops[4] = DAG.getString(CompileUnit->getDirectory());
1935 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
1940 case Intrinsic::dbg_region_start: {
1941 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1942 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1943 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1944 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1945 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1946 DAG.getConstant(LabelID, MVT::i32)));
1951 case Intrinsic::dbg_region_end: {
1952 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1953 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1954 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1955 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1956 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1957 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
1962 case Intrinsic::dbg_func_start: {
1963 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1964 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1965 if (DebugInfo && FSI.getSubprogram() &&
1966 DebugInfo->Verify(FSI.getSubprogram())) {
1967 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1968 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1969 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
1974 case Intrinsic::dbg_declare: {
1975 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1976 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1977 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1978 SDOperand AddressOp = getValue(DI.getAddress());
1979 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
1980 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1986 case Intrinsic::isunordered_f32:
1987 case Intrinsic::isunordered_f64:
1988 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1989 getValue(I.getOperand(2)), ISD::SETUO));
1992 case Intrinsic::sqrt_f32:
1993 case Intrinsic::sqrt_f64:
1994 setValue(&I, DAG.getNode(ISD::FSQRT,
1995 getValue(I.getOperand(1)).getValueType(),
1996 getValue(I.getOperand(1))));
1998 case Intrinsic::powi_f32:
1999 case Intrinsic::powi_f64:
2000 setValue(&I, DAG.getNode(ISD::FPOWI,
2001 getValue(I.getOperand(1)).getValueType(),
2002 getValue(I.getOperand(1)),
2003 getValue(I.getOperand(2))));
2005 case Intrinsic::pcmarker: {
2006 SDOperand Tmp = getValue(I.getOperand(1));
2007 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2010 case Intrinsic::readcyclecounter: {
2011 SDOperand Op = getRoot();
2012 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2013 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2016 DAG.setRoot(Tmp.getValue(1));
2019 case Intrinsic::bswap_i16:
2020 case Intrinsic::bswap_i32:
2021 case Intrinsic::bswap_i64:
2022 setValue(&I, DAG.getNode(ISD::BSWAP,
2023 getValue(I.getOperand(1)).getValueType(),
2024 getValue(I.getOperand(1))));
2026 case Intrinsic::cttz_i8:
2027 case Intrinsic::cttz_i16:
2028 case Intrinsic::cttz_i32:
2029 case Intrinsic::cttz_i64:
2030 setValue(&I, DAG.getNode(ISD::CTTZ,
2031 getValue(I.getOperand(1)).getValueType(),
2032 getValue(I.getOperand(1))));
2034 case Intrinsic::ctlz_i8:
2035 case Intrinsic::ctlz_i16:
2036 case Intrinsic::ctlz_i32:
2037 case Intrinsic::ctlz_i64:
2038 setValue(&I, DAG.getNode(ISD::CTLZ,
2039 getValue(I.getOperand(1)).getValueType(),
2040 getValue(I.getOperand(1))));
2042 case Intrinsic::ctpop_i8:
2043 case Intrinsic::ctpop_i16:
2044 case Intrinsic::ctpop_i32:
2045 case Intrinsic::ctpop_i64:
2046 setValue(&I, DAG.getNode(ISD::CTPOP,
2047 getValue(I.getOperand(1)).getValueType(),
2048 getValue(I.getOperand(1))));
2050 case Intrinsic::stacksave: {
2051 SDOperand Op = getRoot();
2052 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2053 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2055 DAG.setRoot(Tmp.getValue(1));
2058 case Intrinsic::stackrestore: {
2059 SDOperand Tmp = getValue(I.getOperand(1));
2060 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2063 case Intrinsic::prefetch:
2064 // FIXME: Currently discarding prefetches.
2070 void SelectionDAGLowering::visitCall(CallInst &I) {
2071 const char *RenameFn = 0;
2072 if (Function *F = I.getCalledFunction()) {
2073 if (F->isExternal())
2074 if (unsigned IID = F->getIntrinsicID()) {
2075 RenameFn = visitIntrinsicCall(I, IID);
2078 } else { // Not an LLVM intrinsic.
2079 const std::string &Name = F->getName();
2080 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2081 if (I.getNumOperands() == 3 && // Basic sanity checks.
2082 I.getOperand(1)->getType()->isFloatingPoint() &&
2083 I.getType() == I.getOperand(1)->getType() &&
2084 I.getType() == I.getOperand(2)->getType()) {
2085 SDOperand LHS = getValue(I.getOperand(1));
2086 SDOperand RHS = getValue(I.getOperand(2));
2087 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2091 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2092 if (I.getNumOperands() == 2 && // Basic sanity checks.
2093 I.getOperand(1)->getType()->isFloatingPoint() &&
2094 I.getType() == I.getOperand(1)->getType()) {
2095 SDOperand Tmp = getValue(I.getOperand(1));
2096 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2099 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2100 if (I.getNumOperands() == 2 && // Basic sanity checks.
2101 I.getOperand(1)->getType()->isFloatingPoint() &&
2102 I.getType() == I.getOperand(1)->getType()) {
2103 SDOperand Tmp = getValue(I.getOperand(1));
2104 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2107 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2108 if (I.getNumOperands() == 2 && // Basic sanity checks.
2109 I.getOperand(1)->getType()->isFloatingPoint() &&
2110 I.getType() == I.getOperand(1)->getType()) {
2111 SDOperand Tmp = getValue(I.getOperand(1));
2112 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2117 } else if (isa<InlineAsm>(I.getOperand(0))) {
2124 Callee = getValue(I.getOperand(0));
2126 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2127 std::vector<std::pair<SDOperand, const Type*> > Args;
2128 Args.reserve(I.getNumOperands());
2129 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2130 Value *Arg = I.getOperand(i);
2131 SDOperand ArgNode = getValue(Arg);
2132 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2135 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2136 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2138 std::pair<SDOperand,SDOperand> Result =
2139 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
2140 I.isTailCall(), Callee, Args, DAG);
2141 if (I.getType() != Type::VoidTy)
2142 setValue(&I, Result.first);
2143 DAG.setRoot(Result.second);
2146 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2147 SDOperand &Chain, SDOperand &Flag)const{
2148 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2149 Chain = Val.getValue(1);
2150 Flag = Val.getValue(2);
2152 // If the result was expanded, copy from the top part.
2153 if (Regs.size() > 1) {
2154 assert(Regs.size() == 2 &&
2155 "Cannot expand to more than 2 elts yet!");
2156 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2157 Chain = Hi.getValue(1);
2158 Flag = Hi.getValue(2);
2159 if (DAG.getTargetLoweringInfo().isLittleEndian())
2160 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2162 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2165 // Otherwise, if the return value was promoted or extended, truncate it to the
2166 // appropriate type.
2167 if (RegVT == ValueVT)
2170 if (MVT::isInteger(RegVT)) {
2171 if (ValueVT < RegVT)
2172 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2174 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2176 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2180 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2181 /// specified value into the registers specified by this object. This uses
2182 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2183 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2184 SDOperand &Chain, SDOperand &Flag,
2185 MVT::ValueType PtrVT) const {
2186 if (Regs.size() == 1) {
2187 // If there is a single register and the types differ, this must be
2189 if (RegVT != ValueVT) {
2190 if (MVT::isInteger(RegVT)) {
2191 if (RegVT < ValueVT)
2192 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2194 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2196 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2198 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2199 Flag = Chain.getValue(1);
2201 std::vector<unsigned> R(Regs);
2202 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2203 std::reverse(R.begin(), R.end());
2205 for (unsigned i = 0, e = R.size(); i != e; ++i) {
2206 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2207 DAG.getConstant(i, PtrVT));
2208 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2209 Flag = Chain.getValue(1);
2214 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2215 /// operand list. This adds the code marker and includes the number of
2216 /// values added into it.
2217 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2218 std::vector<SDOperand> &Ops) const {
2219 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2220 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2221 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2224 /// isAllocatableRegister - If the specified register is safe to allocate,
2225 /// i.e. it isn't a stack pointer or some other special register, return the
2226 /// register class for the register. Otherwise, return null.
2227 static const TargetRegisterClass *
2228 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2229 const TargetLowering &TLI, const MRegisterInfo *MRI) {
2230 MVT::ValueType FoundVT = MVT::Other;
2231 const TargetRegisterClass *FoundRC = 0;
2232 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2233 E = MRI->regclass_end(); RCI != E; ++RCI) {
2234 MVT::ValueType ThisVT = MVT::Other;
2236 const TargetRegisterClass *RC = *RCI;
2237 // If none of the the value types for this register class are valid, we
2238 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2239 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2241 if (TLI.isTypeLegal(*I)) {
2242 // If we have already found this register in a different register class,
2243 // choose the one with the largest VT specified. For example, on
2244 // PowerPC, we favor f64 register classes over f32.
2245 if (FoundVT == MVT::Other ||
2246 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2253 if (ThisVT == MVT::Other) continue;
2255 // NOTE: This isn't ideal. In particular, this might allocate the
2256 // frame pointer in functions that need it (due to them not being taken
2257 // out of allocation, because a variable sized allocation hasn't been seen
2258 // yet). This is a slight code pessimization, but should still work.
2259 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2260 E = RC->allocation_order_end(MF); I != E; ++I)
2262 // We found a matching register class. Keep looking at others in case
2263 // we find one with larger registers that this physreg is also in.
2272 RegsForValue SelectionDAGLowering::
2273 GetRegistersForValue(const std::string &ConstrCode,
2274 MVT::ValueType VT, bool isOutReg, bool isInReg,
2275 std::set<unsigned> &OutputRegs,
2276 std::set<unsigned> &InputRegs) {
2277 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2278 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2279 std::vector<unsigned> Regs;
2281 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2282 MVT::ValueType RegVT;
2283 MVT::ValueType ValueVT = VT;
2285 // If this is a constraint for a specific physical register, like {r17},
2287 if (PhysReg.first) {
2288 if (VT == MVT::Other)
2289 ValueVT = *PhysReg.second->vt_begin();
2291 // Get the actual register value type. This is important, because the user
2292 // may have asked for (e.g.) the AX register in i32 type. We need to
2293 // remember that AX is actually i16 to get the right extension.
2294 RegVT = *PhysReg.second->vt_begin();
2296 // This is a explicit reference to a physical register.
2297 Regs.push_back(PhysReg.first);
2299 // If this is an expanded reference, add the rest of the regs to Regs.
2301 TargetRegisterClass::iterator I = PhysReg.second->begin();
2302 TargetRegisterClass::iterator E = PhysReg.second->end();
2303 for (; *I != PhysReg.first; ++I)
2304 assert(I != E && "Didn't find reg!");
2306 // Already added the first reg.
2308 for (; NumRegs; --NumRegs, ++I) {
2309 assert(I != E && "Ran out of registers to allocate!");
2313 return RegsForValue(Regs, RegVT, ValueVT);
2316 // Otherwise, if this was a reference to an LLVM register class, create vregs
2317 // for this reference.
2318 std::vector<unsigned> RegClassRegs;
2319 if (PhysReg.second) {
2320 // If this is an early clobber or tied register, our regalloc doesn't know
2321 // how to maintain the constraint. If it isn't, go ahead and create vreg
2322 // and let the regalloc do the right thing.
2323 if (!isOutReg || !isInReg) {
2324 if (VT == MVT::Other)
2325 ValueVT = *PhysReg.second->vt_begin();
2326 RegVT = *PhysReg.second->vt_begin();
2328 // Create the appropriate number of virtual registers.
2329 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2330 for (; NumRegs; --NumRegs)
2331 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2333 return RegsForValue(Regs, RegVT, ValueVT);
2336 // Otherwise, we can't allocate it. Let the code below figure out how to
2337 // maintain these constraints.
2338 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2341 // This is a reference to a register class that doesn't directly correspond
2342 // to an LLVM register class. Allocate NumRegs consecutive, available,
2343 // registers from the class.
2344 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2347 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2348 MachineFunction &MF = *CurMBB->getParent();
2349 unsigned NumAllocated = 0;
2350 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2351 unsigned Reg = RegClassRegs[i];
2352 // See if this register is available.
2353 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2354 (isInReg && InputRegs.count(Reg))) { // Already used.
2355 // Make sure we find consecutive registers.
2360 // Check to see if this register is allocatable (i.e. don't give out the
2362 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
2364 // Make sure we find consecutive registers.
2369 // Okay, this register is good, we can use it.
2372 // If we allocated enough consecutive
2373 if (NumAllocated == NumRegs) {
2374 unsigned RegStart = (i-NumAllocated)+1;
2375 unsigned RegEnd = i+1;
2376 // Mark all of the allocated registers used.
2377 for (unsigned i = RegStart; i != RegEnd; ++i) {
2378 unsigned Reg = RegClassRegs[i];
2379 Regs.push_back(Reg);
2380 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2381 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2384 return RegsForValue(Regs, *RC->vt_begin(), VT);
2388 // Otherwise, we couldn't allocate enough registers for this.
2389 return RegsForValue();
2393 /// visitInlineAsm - Handle a call to an InlineAsm object.
2395 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2396 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2398 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2401 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
2402 std::vector<MVT::ValueType> ConstraintVTs;
2404 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2405 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2406 /// if it is a def of that register.
2407 std::vector<SDOperand> AsmNodeOperands;
2408 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2409 AsmNodeOperands.push_back(AsmStr);
2411 SDOperand Chain = getRoot();
2414 // We fully assign registers here at isel time. This is not optimal, but
2415 // should work. For register classes that correspond to LLVM classes, we
2416 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2417 // over the constraints, collecting fixed registers that we know we can't use.
2418 std::set<unsigned> OutputRegs, InputRegs;
2420 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2421 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2422 std::string &ConstraintCode = Constraints[i].Codes[0];
2424 MVT::ValueType OpVT;
2426 // Compute the value type for each operand and add it to ConstraintVTs.
2427 switch (Constraints[i].Type) {
2428 case InlineAsm::isOutput:
2429 if (!Constraints[i].isIndirectOutput) {
2430 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2431 OpVT = TLI.getValueType(I.getType());
2433 const Type *OpTy = I.getOperand(OpNum)->getType();
2434 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2435 OpNum++; // Consumes a call operand.
2438 case InlineAsm::isInput:
2439 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2440 OpNum++; // Consumes a call operand.
2442 case InlineAsm::isClobber:
2447 ConstraintVTs.push_back(OpVT);
2449 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2450 continue; // Not assigned a fixed reg.
2452 // Build a list of regs that this operand uses. This always has a single
2453 // element for promoted/expanded operands.
2454 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2456 OutputRegs, InputRegs);
2458 switch (Constraints[i].Type) {
2459 case InlineAsm::isOutput:
2460 // We can't assign any other output to this register.
2461 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2462 // If this is an early-clobber output, it cannot be assigned to the same
2463 // value as the input reg.
2464 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2465 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2467 case InlineAsm::isInput:
2468 // We can't assign any other input to this register.
2469 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2471 case InlineAsm::isClobber:
2472 // Clobbered regs cannot be used as inputs or outputs.
2473 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2474 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2479 // Loop over all of the inputs, copying the operand values into the
2480 // appropriate registers and processing the output regs.
2481 RegsForValue RetValRegs;
2482 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2485 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2486 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2487 std::string &ConstraintCode = Constraints[i].Codes[0];
2489 switch (Constraints[i].Type) {
2490 case InlineAsm::isOutput: {
2491 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2492 if (ConstraintCode.size() == 1) // not a physreg name.
2493 CTy = TLI.getConstraintType(ConstraintCode[0]);
2495 if (CTy == TargetLowering::C_Memory) {
2497 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2499 // Check that the operand (the address to store to) isn't a float.
2500 if (!MVT::isInteger(InOperandVal.getValueType()))
2501 assert(0 && "MATCH FAIL!");
2503 if (!Constraints[i].isIndirectOutput)
2504 assert(0 && "MATCH FAIL!");
2506 OpNum++; // Consumes a call operand.
2508 // Extend/truncate to the right pointer type if needed.
2509 MVT::ValueType PtrType = TLI.getPointerTy();
2510 if (InOperandVal.getValueType() < PtrType)
2511 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2512 else if (InOperandVal.getValueType() > PtrType)
2513 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2515 // Add information to the INLINEASM node to know about this output.
2516 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2517 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2518 AsmNodeOperands.push_back(InOperandVal);
2522 // Otherwise, this is a register output.
2523 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2525 // If this is an early-clobber output, or if there is an input
2526 // constraint that matches this, we need to reserve the input register
2527 // so no other inputs allocate to it.
2528 bool UsesInputRegister = false;
2529 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2530 UsesInputRegister = true;
2532 // Copy the output from the appropriate register. Find a register that
2535 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2536 true, UsesInputRegister,
2537 OutputRegs, InputRegs);
2538 if (Regs.Regs.empty()) {
2539 std::cerr << "Couldn't allocate output reg for contraint '"
2540 << ConstraintCode << "'!\n";
2544 if (!Constraints[i].isIndirectOutput) {
2545 assert(RetValRegs.Regs.empty() &&
2546 "Cannot have multiple output constraints yet!");
2547 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2550 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2551 I.getOperand(OpNum)));
2552 OpNum++; // Consumes a call operand.
2555 // Add information to the INLINEASM node to know that this register is
2557 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2560 case InlineAsm::isInput: {
2561 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2562 OpNum++; // Consumes a call operand.
2564 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2565 // If this is required to match an output register we have already set,
2566 // just use its register.
2567 unsigned OperandNo = atoi(ConstraintCode.c_str());
2569 // Scan until we find the definition we already emitted of this operand.
2570 // When we find it, create a RegsForValue operand.
2571 unsigned CurOp = 2; // The first operand.
2572 for (; OperandNo; --OperandNo) {
2573 // Advance to the next operand.
2575 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2576 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2577 (NumOps & 7) == 4 /*MEM*/) &&
2578 "Skipped past definitions?");
2579 CurOp += (NumOps>>3)+1;
2583 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2584 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2585 "Skipped past definitions?");
2587 // Add NumOps>>3 registers to MatchedRegs.
2588 RegsForValue MatchedRegs;
2589 MatchedRegs.ValueVT = InOperandVal.getValueType();
2590 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2591 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2592 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2593 MatchedRegs.Regs.push_back(Reg);
2596 // Use the produced MatchedRegs object to
2597 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2598 TLI.getPointerTy());
2599 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2603 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2604 if (ConstraintCode.size() == 1) // not a physreg name.
2605 CTy = TLI.getConstraintType(ConstraintCode[0]);
2607 if (CTy == TargetLowering::C_Other) {
2608 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2609 ConstraintCode[0], DAG);
2610 if (!InOperandVal.Val) {
2611 std::cerr << "Invalid operand for inline asm constraint '"
2612 << ConstraintCode << "'!\n";
2616 // Add information to the INLINEASM node to know about this input.
2617 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2618 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2619 AsmNodeOperands.push_back(InOperandVal);
2621 } else if (CTy == TargetLowering::C_Memory) {
2624 // Check that the operand isn't a float.
2625 if (!MVT::isInteger(InOperandVal.getValueType()))
2626 assert(0 && "MATCH FAIL!");
2628 // Extend/truncate to the right pointer type if needed.
2629 MVT::ValueType PtrType = TLI.getPointerTy();
2630 if (InOperandVal.getValueType() < PtrType)
2631 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2632 else if (InOperandVal.getValueType() > PtrType)
2633 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2635 // Add information to the INLINEASM node to know about this input.
2636 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2637 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2638 AsmNodeOperands.push_back(InOperandVal);
2642 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2644 // Copy the input into the appropriate registers.
2645 RegsForValue InRegs =
2646 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2647 false, true, OutputRegs, InputRegs);
2648 // FIXME: should be match fail.
2649 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2651 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
2653 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2656 case InlineAsm::isClobber: {
2657 RegsForValue ClobberedRegs =
2658 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2659 OutputRegs, InputRegs);
2660 // Add the clobbered value to the operand list, so that the register
2661 // allocator is aware that the physreg got clobbered.
2662 if (!ClobberedRegs.Regs.empty())
2663 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2669 // Finish up input operands.
2670 AsmNodeOperands[0] = Chain;
2671 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2673 Chain = DAG.getNode(ISD::INLINEASM,
2674 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
2675 &AsmNodeOperands[0], AsmNodeOperands.size());
2676 Flag = Chain.getValue(1);
2678 // If this asm returns a register value, copy the result from that register
2679 // and set it as the value of the call.
2680 if (!RetValRegs.Regs.empty())
2681 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2683 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2685 // Process indirect outputs, first output all of the flagged copies out of
2687 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2688 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2689 Value *Ptr = IndirectStoresToEmit[i].second;
2690 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2691 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2694 // Emit the non-flagged stores from the physregs.
2695 SmallVector<SDOperand, 8> OutChains;
2696 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2697 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
2698 getValue(StoresToEmit[i].second),
2699 StoresToEmit[i].second, 0));
2700 if (!OutChains.empty())
2701 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2702 &OutChains[0], OutChains.size());
2707 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2708 SDOperand Src = getValue(I.getOperand(0));
2710 MVT::ValueType IntPtr = TLI.getPointerTy();
2712 if (IntPtr < Src.getValueType())
2713 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2714 else if (IntPtr > Src.getValueType())
2715 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2717 // Scale the source by the type size.
2718 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2719 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2720 Src, getIntPtrConstant(ElementSize));
2722 std::vector<std::pair<SDOperand, const Type*> > Args;
2723 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
2725 std::pair<SDOperand,SDOperand> Result =
2726 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2727 DAG.getExternalSymbol("malloc", IntPtr),
2729 setValue(&I, Result.first); // Pointers always fit in registers
2730 DAG.setRoot(Result.second);
2733 void SelectionDAGLowering::visitFree(FreeInst &I) {
2734 std::vector<std::pair<SDOperand, const Type*> > Args;
2735 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2736 TLI.getTargetData()->getIntPtrType()));
2737 MVT::ValueType IntPtr = TLI.getPointerTy();
2738 std::pair<SDOperand,SDOperand> Result =
2739 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2740 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2741 DAG.setRoot(Result.second);
2744 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2745 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2746 // instructions are special in various ways, which require special support to
2747 // insert. The specified MachineInstr is created but not inserted into any
2748 // basic blocks, and the scheduler passes ownership of it to this method.
2749 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2750 MachineBasicBlock *MBB) {
2751 std::cerr << "If a target marks an instruction with "
2752 "'usesCustomDAGSchedInserter', it must implement "
2753 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2758 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2759 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2760 getValue(I.getOperand(1)),
2761 DAG.getSrcValue(I.getOperand(1))));
2764 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2765 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2766 getValue(I.getOperand(0)),
2767 DAG.getSrcValue(I.getOperand(0)));
2769 DAG.setRoot(V.getValue(1));
2772 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2773 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2774 getValue(I.getOperand(1)),
2775 DAG.getSrcValue(I.getOperand(1))));
2778 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2779 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2780 getValue(I.getOperand(1)),
2781 getValue(I.getOperand(2)),
2782 DAG.getSrcValue(I.getOperand(1)),
2783 DAG.getSrcValue(I.getOperand(2))));
2786 /// TargetLowering::LowerArguments - This is the default LowerArguments
2787 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
2788 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2789 /// integrated into SDISel.
2790 std::vector<SDOperand>
2791 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2792 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2793 std::vector<SDOperand> Ops;
2794 Ops.push_back(DAG.getRoot());
2795 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2796 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2798 // Add one result value for each formal argument.
2799 std::vector<MVT::ValueType> RetVals;
2800 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2801 MVT::ValueType VT = getValueType(I->getType());
2803 switch (getTypeAction(VT)) {
2804 default: assert(0 && "Unknown type action!");
2806 RetVals.push_back(VT);
2809 RetVals.push_back(getTypeToTransformTo(VT));
2812 if (VT != MVT::Vector) {
2813 // If this is a large integer, it needs to be broken up into small
2814 // integers. Figure out what the destination type is and how many small
2815 // integers it turns into.
2816 MVT::ValueType NVT = getTypeToTransformTo(VT);
2817 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2818 for (unsigned i = 0; i != NumVals; ++i)
2819 RetVals.push_back(NVT);
2821 // Otherwise, this is a vector type. We only support legal vectors
2823 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2824 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2826 // Figure out if there is a Packed type corresponding to this Vector
2827 // type. If so, convert to the packed type.
2828 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2829 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2830 RetVals.push_back(TVT);
2832 assert(0 && "Don't support illegal by-val vector arguments yet!");
2839 RetVals.push_back(MVT::Other);
2842 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2843 DAG.getNodeValueTypes(RetVals), RetVals.size(),
2844 &Ops[0], Ops.size()).Val;
2846 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
2848 // Set up the return result vector.
2851 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2852 MVT::ValueType VT = getValueType(I->getType());
2854 switch (getTypeAction(VT)) {
2855 default: assert(0 && "Unknown type action!");
2857 Ops.push_back(SDOperand(Result, i++));
2860 SDOperand Op(Result, i++);
2861 if (MVT::isInteger(VT)) {
2862 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2864 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2865 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2867 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2868 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2874 if (VT != MVT::Vector) {
2875 // If this is a large integer, it needs to be reassembled from small
2876 // integers. Figure out what the source elt type is and how many small
2878 MVT::ValueType NVT = getTypeToTransformTo(VT);
2879 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2881 SDOperand Lo = SDOperand(Result, i++);
2882 SDOperand Hi = SDOperand(Result, i++);
2884 if (!isLittleEndian())
2887 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2889 // Value scalarized into many values. Unimp for now.
2890 assert(0 && "Cannot expand i64 -> i16 yet!");
2893 // Otherwise, this is a vector type. We only support legal vectors
2895 const PackedType *PTy = cast<PackedType>(I->getType());
2896 unsigned NumElems = PTy->getNumElements();
2897 const Type *EltTy = PTy->getElementType();
2899 // Figure out if there is a Packed type corresponding to this Vector
2900 // type. If so, convert to the packed type.
2901 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2902 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2903 SDOperand N = SDOperand(Result, i++);
2904 // Handle copies from generic vectors to registers.
2905 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2906 DAG.getConstant(NumElems, MVT::i32),
2907 DAG.getValueType(getValueType(EltTy)));
2910 assert(0 && "Don't support illegal by-val vector arguments yet!");
2921 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
2922 /// implementation, which just inserts an ISD::CALL node, which is later custom
2923 /// lowered by the target to something concrete. FIXME: When all targets are
2924 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2925 std::pair<SDOperand, SDOperand>
2926 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2927 unsigned CallingConv, bool isTailCall,
2929 ArgListTy &Args, SelectionDAG &DAG) {
2930 SmallVector<SDOperand, 32> Ops;
2931 Ops.push_back(Chain); // Op#0 - Chain
2932 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2933 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2934 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2935 Ops.push_back(Callee);
2937 // Handle all of the outgoing arguments.
2938 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2939 MVT::ValueType VT = getValueType(Args[i].second);
2940 SDOperand Op = Args[i].first;
2941 bool isSigned = Args[i].second->isSigned();
2942 switch (getTypeAction(VT)) {
2943 default: assert(0 && "Unknown type action!");
2946 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2949 if (MVT::isInteger(VT)) {
2950 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2951 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2953 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2954 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2957 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2960 if (VT != MVT::Vector) {
2961 // If this is a large integer, it needs to be broken down into small
2962 // integers. Figure out what the source elt type is and how many small
2964 MVT::ValueType NVT = getTypeToTransformTo(VT);
2965 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2967 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2968 DAG.getConstant(0, getPointerTy()));
2969 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2970 DAG.getConstant(1, getPointerTy()));
2971 if (!isLittleEndian())
2975 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2977 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2979 // Value scalarized into many values. Unimp for now.
2980 assert(0 && "Cannot expand i64 -> i16 yet!");
2983 // Otherwise, this is a vector type. We only support legal vectors
2985 const PackedType *PTy = cast<PackedType>(Args[i].second);
2986 unsigned NumElems = PTy->getNumElements();
2987 const Type *EltTy = PTy->getElementType();
2989 // Figure out if there is a Packed type corresponding to this Vector
2990 // type. If so, convert to the packed type.
2991 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2992 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2993 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2994 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2996 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2998 assert(0 && "Don't support illegal by-val vector call args yet!");
3006 // Figure out the result value types.
3007 SmallVector<MVT::ValueType, 4> RetTys;
3009 if (RetTy != Type::VoidTy) {
3010 MVT::ValueType VT = getValueType(RetTy);
3011 switch (getTypeAction(VT)) {
3012 default: assert(0 && "Unknown type action!");
3014 RetTys.push_back(VT);
3017 RetTys.push_back(getTypeToTransformTo(VT));
3020 if (VT != MVT::Vector) {
3021 // If this is a large integer, it needs to be reassembled from small
3022 // integers. Figure out what the source elt type is and how many small
3024 MVT::ValueType NVT = getTypeToTransformTo(VT);
3025 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
3026 for (unsigned i = 0; i != NumVals; ++i)
3027 RetTys.push_back(NVT);
3029 // Otherwise, this is a vector type. We only support legal vectors
3031 const PackedType *PTy = cast<PackedType>(RetTy);
3032 unsigned NumElems = PTy->getNumElements();
3033 const Type *EltTy = PTy->getElementType();
3035 // Figure out if there is a Packed type corresponding to this Vector
3036 // type. If so, convert to the packed type.
3037 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3038 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3039 RetTys.push_back(TVT);
3041 assert(0 && "Don't support illegal by-val vector call results yet!");
3048 RetTys.push_back(MVT::Other); // Always has a chain.
3050 // Finally, create the CALL node.
3051 SDOperand Res = DAG.getNode(ISD::CALL,
3052 DAG.getVTList(&RetTys[0], RetTys.size()),
3053 &Ops[0], Ops.size());
3055 // This returns a pair of operands. The first element is the
3056 // return value for the function (if RetTy is not VoidTy). The second
3057 // element is the outgoing token chain.
3059 if (RetTys.size() != 1) {
3060 MVT::ValueType VT = getValueType(RetTy);
3061 if (RetTys.size() == 2) {
3064 // If this value was promoted, truncate it down.
3065 if (ResVal.getValueType() != VT) {
3066 if (VT == MVT::Vector) {
3067 // Insert a VBITCONVERT to convert from the packed result type to the
3068 // MVT::Vector type.
3069 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3070 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3072 // Figure out if there is a Packed type corresponding to this Vector
3073 // type. If so, convert to the packed type.
3074 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3075 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3076 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3077 // "N x PTyElementVT" MVT::Vector type.
3078 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
3079 DAG.getConstant(NumElems, MVT::i32),
3080 DAG.getValueType(getValueType(EltTy)));
3084 } else if (MVT::isInteger(VT)) {
3085 unsigned AssertOp = RetTy->isSigned() ?
3086 ISD::AssertSext : ISD::AssertZext;
3087 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3088 DAG.getValueType(VT));
3089 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3091 assert(MVT::isFloatingPoint(VT));
3092 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3095 } else if (RetTys.size() == 3) {
3096 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3097 Res.getValue(0), Res.getValue(1));
3100 assert(0 && "Case not handled yet!");
3104 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3109 // It is always conservatively correct for llvm.returnaddress and
3110 // llvm.frameaddress to return 0.
3112 // FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3113 // expanded to 0 if the target wants.
3114 std::pair<SDOperand, SDOperand>
3115 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3116 unsigned Depth, SelectionDAG &DAG) {
3117 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
3120 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3121 assert(0 && "LowerOperation not implemented for this target!");
3126 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3127 SelectionDAG &DAG) {
3128 assert(0 && "CustomPromoteOperation not implemented for this target!");
3133 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
3134 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
3135 std::pair<SDOperand,SDOperand> Result =
3136 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
3137 setValue(&I, Result.first);
3138 DAG.setRoot(Result.second);
3141 /// getMemsetValue - Vectorized representation of the memset value
3143 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
3144 SelectionDAG &DAG) {
3145 MVT::ValueType CurVT = VT;
3146 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3147 uint64_t Val = C->getValue() & 255;
3149 while (CurVT != MVT::i8) {
3150 Val = (Val << Shift) | Val;
3152 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3154 return DAG.getConstant(Val, VT);
3156 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3158 while (CurVT != MVT::i8) {
3160 DAG.getNode(ISD::OR, VT,
3161 DAG.getNode(ISD::SHL, VT, Value,
3162 DAG.getConstant(Shift, MVT::i8)), Value);
3164 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3171 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3172 /// used when a memcpy is turned into a memset when the source is a constant
3174 static SDOperand getMemsetStringVal(MVT::ValueType VT,
3175 SelectionDAG &DAG, TargetLowering &TLI,
3176 std::string &Str, unsigned Offset) {
3178 unsigned MSB = getSizeInBits(VT) / 8;
3179 if (TLI.isLittleEndian())
3180 Offset = Offset + MSB - 1;
3181 for (unsigned i = 0; i != MSB; ++i) {
3182 Val = (Val << 8) | Str[Offset];
3183 Offset += TLI.isLittleEndian() ? -1 : 1;
3185 return DAG.getConstant(Val, VT);
3188 /// getMemBasePlusOffset - Returns base and offset node for the
3189 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3190 SelectionDAG &DAG, TargetLowering &TLI) {
3191 MVT::ValueType VT = Base.getValueType();
3192 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3195 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3196 /// to replace the memset / memcpy is below the threshold. It also returns the
3197 /// types of the sequence of memory ops to perform memset / memcpy.
3198 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3199 unsigned Limit, uint64_t Size,
3200 unsigned Align, TargetLowering &TLI) {
3203 if (TLI.allowsUnalignedMemoryAccesses()) {
3206 switch (Align & 7) {
3222 MVT::ValueType LVT = MVT::i64;
3223 while (!TLI.isTypeLegal(LVT))
3224 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3225 assert(MVT::isInteger(LVT));
3230 unsigned NumMemOps = 0;
3232 unsigned VTSize = getSizeInBits(VT) / 8;
3233 while (VTSize > Size) {
3234 VT = (MVT::ValueType)((unsigned)VT - 1);
3237 assert(MVT::isInteger(VT));
3239 if (++NumMemOps > Limit)
3241 MemOps.push_back(VT);
3248 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
3249 SDOperand Op1 = getValue(I.getOperand(1));
3250 SDOperand Op2 = getValue(I.getOperand(2));
3251 SDOperand Op3 = getValue(I.getOperand(3));
3252 SDOperand Op4 = getValue(I.getOperand(4));
3253 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3254 if (Align == 0) Align = 1;
3256 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3257 std::vector<MVT::ValueType> MemOps;
3259 // Expand memset / memcpy to a series of load / store ops
3260 // if the size operand falls below a certain threshold.
3261 SmallVector<SDOperand, 8> OutChains;
3263 default: break; // Do nothing for now.
3265 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3266 Size->getValue(), Align, TLI)) {
3267 unsigned NumMemOps = MemOps.size();
3268 unsigned Offset = 0;
3269 for (unsigned i = 0; i < NumMemOps; i++) {
3270 MVT::ValueType VT = MemOps[i];
3271 unsigned VTSize = getSizeInBits(VT) / 8;
3272 SDOperand Value = getMemsetValue(Op2, VT, DAG);
3273 SDOperand Store = DAG.getStore(getRoot(), Value,
3274 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
3275 I.getOperand(1), Offset);
3276 OutChains.push_back(Store);
3283 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3284 Size->getValue(), Align, TLI)) {
3285 unsigned NumMemOps = MemOps.size();
3286 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
3287 GlobalAddressSDNode *G = NULL;
3289 bool CopyFromStr = false;
3291 if (Op2.getOpcode() == ISD::GlobalAddress)
3292 G = cast<GlobalAddressSDNode>(Op2);
3293 else if (Op2.getOpcode() == ISD::ADD &&
3294 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3295 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3296 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
3297 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
3300 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3302 Str = GV->getStringValue(false);
3310 for (unsigned i = 0; i < NumMemOps; i++) {
3311 MVT::ValueType VT = MemOps[i];
3312 unsigned VTSize = getSizeInBits(VT) / 8;
3313 SDOperand Value, Chain, Store;
3316 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3319 DAG.getStore(Chain, Value,
3320 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3321 I.getOperand(1), DstOff);
3323 Value = DAG.getLoad(VT, getRoot(),
3324 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
3325 I.getOperand(2), SrcOff);
3326 Chain = Value.getValue(1);
3328 DAG.getStore(Chain, Value,
3329 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3330 I.getOperand(1), DstOff);
3332 OutChains.push_back(Store);
3341 if (!OutChains.empty()) {
3342 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3343 &OutChains[0], OutChains.size()));
3348 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
3351 //===----------------------------------------------------------------------===//
3352 // SelectionDAGISel code
3353 //===----------------------------------------------------------------------===//
3355 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3356 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3359 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
3360 // FIXME: we only modify the CFG to split critical edges. This
3361 // updates dom and loop info.
3362 AU.addRequired<AliasAnalysis>();
3366 /// OptimizeNoopCopyExpression - We have determined that the specified cast
3367 /// instruction is a noop copy (e.g. it's casting from one pointer type to
3368 /// another, int->uint, or int->sbyte on PPC.
3370 /// Return true if any changes are made.
3371 static bool OptimizeNoopCopyExpression(CastInst *CI) {
3372 BasicBlock *DefBB = CI->getParent();
3374 /// InsertedCasts - Only insert a cast in each block once.
3375 std::map<BasicBlock*, CastInst*> InsertedCasts;
3377 bool MadeChange = false;
3378 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3380 Use &TheUse = UI.getUse();
3381 Instruction *User = cast<Instruction>(*UI);
3383 // Figure out which BB this cast is used in. For PHI's this is the
3384 // appropriate predecessor block.
3385 BasicBlock *UserBB = User->getParent();
3386 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3387 unsigned OpVal = UI.getOperandNo()/2;
3388 UserBB = PN->getIncomingBlock(OpVal);
3391 // Preincrement use iterator so we don't invalidate it.
3394 // If this user is in the same block as the cast, don't change the cast.
3395 if (UserBB == DefBB) continue;
3397 // If we have already inserted a cast into this block, use it.
3398 CastInst *&InsertedCast = InsertedCasts[UserBB];
3400 if (!InsertedCast) {
3401 BasicBlock::iterator InsertPt = UserBB->begin();
3402 while (isa<PHINode>(InsertPt)) ++InsertPt;
3405 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3409 // Replace a use of the cast with a use of the new casat.
3410 TheUse = InsertedCast;
3413 // If we removed all uses, nuke the cast.
3414 if (CI->use_empty())
3415 CI->eraseFromParent();
3420 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3421 /// casting to the type of GEPI.
3422 static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3423 Instruction *GEPI, Value *Ptr,
3425 if (V) return V; // Already computed.
3427 BasicBlock::iterator InsertPt;
3428 if (BB == GEPI->getParent()) {
3429 // If insert into the GEP's block, insert right after the GEP.
3433 // Otherwise, insert at the top of BB, after any PHI nodes
3434 InsertPt = BB->begin();
3435 while (isa<PHINode>(InsertPt)) ++InsertPt;
3438 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3439 // BB so that there is only one value live across basic blocks (the cast
3441 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3442 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3443 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3445 // Add the offset, cast it to the right type.
3446 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
3447 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
3450 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3451 /// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3452 /// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3453 /// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3454 /// sink PtrOffset into user blocks where doing so will likely allow us to fold
3455 /// the constant add into a load or store instruction. Additionally, if a user
3456 /// is a pointer-pointer cast, we look through it to find its users.
3457 static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3458 Constant *PtrOffset, BasicBlock *DefBB,
3459 GetElementPtrInst *GEPI,
3460 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
3461 while (!RepPtr->use_empty()) {
3462 Instruction *User = cast<Instruction>(RepPtr->use_back());
3464 // If the user is a Pointer-Pointer cast, recurse.
3465 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3466 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3468 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3469 // could invalidate an iterator.
3470 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3474 // If this is a load of the pointer, or a store through the pointer, emit
3475 // the increment into the load/store block.
3476 Instruction *NewVal;
3477 if (isa<LoadInst>(User) ||
3478 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3479 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3480 User->getParent(), GEPI,
3483 // If this use is not foldable into the addressing mode, use a version
3484 // emitted in the GEP block.
3485 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3489 if (GEPI->getType() != RepPtr->getType()) {
3490 BasicBlock::iterator IP = NewVal;
3492 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3494 User->replaceUsesOfWith(RepPtr, NewVal);
3499 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3500 /// selection, we want to be a bit careful about some things. In particular, if
3501 /// we have a GEP instruction that is used in a different block than it is
3502 /// defined, the addressing expression of the GEP cannot be folded into loads or
3503 /// stores that use it. In this case, decompose the GEP and move constant
3504 /// indices into blocks that use it.
3505 static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
3506 const TargetData *TD) {
3507 // If this GEP is only used inside the block it is defined in, there is no
3508 // need to rewrite it.
3509 bool isUsedOutsideDefBB = false;
3510 BasicBlock *DefBB = GEPI->getParent();
3511 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3513 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3514 isUsedOutsideDefBB = true;
3518 if (!isUsedOutsideDefBB) return false;
3520 // If this GEP has no non-zero constant indices, there is nothing we can do,
3522 bool hasConstantIndex = false;
3523 bool hasVariableIndex = false;
3524 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3525 E = GEPI->op_end(); OI != E; ++OI) {
3526 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
3527 if (CI->getZExtValue()) {
3528 hasConstantIndex = true;
3532 hasVariableIndex = true;
3536 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3537 if (!hasConstantIndex && !hasVariableIndex) {
3538 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3539 GEPI->getName(), GEPI);
3540 GEPI->replaceAllUsesWith(NC);
3541 GEPI->eraseFromParent();
3545 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
3546 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3549 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3550 // constant offset (which we now know is non-zero) and deal with it later.
3551 uint64_t ConstantOffset = 0;
3552 const Type *UIntPtrTy = TD->getIntPtrType();
3553 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3554 const Type *Ty = GEPI->getOperand(0)->getType();
3556 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3557 E = GEPI->op_end(); OI != E; ++OI) {
3559 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3560 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
3562 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
3563 Ty = StTy->getElementType(Field);
3565 Ty = cast<SequentialType>(Ty)->getElementType();
3567 // Handle constant subscripts.
3568 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3569 if (CI->getZExtValue() == 0) continue;
3570 if (CI->getType()->isSigned())
3571 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
3573 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
3577 // Ptr = Ptr + Idx * ElementSize;
3579 // Cast Idx to UIntPtrTy if needed.
3580 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3582 uint64_t ElementSize = TD->getTypeSize(Ty);
3583 // Mask off bits that should not be set.
3584 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3585 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
3587 // Multiply by the element size and add to the base.
3588 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3589 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3593 // Make sure that the offset fits in uintptr_t.
3594 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3595 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
3597 // Okay, we have now emitted all of the variable index parts to the BB that
3598 // the GEP is defined in. Loop over all of the using instructions, inserting
3599 // an "add Ptr, ConstantOffset" into each block that uses it and update the
3600 // instruction to use the newly computed value, making GEPI dead. When the
3601 // user is a load or store instruction address, we emit the add into the user
3602 // block, otherwise we use a canonical version right next to the gep (these
3603 // won't be foldable as addresses, so we might as well share the computation).
3605 std::map<BasicBlock*,Instruction*> InsertedExprs;
3606 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3608 // Finally, the GEP is dead, remove it.
3609 GEPI->eraseFromParent();
3615 /// SplitEdgeNicely - Split the critical edge from TI to it's specified
3616 /// successor if it will improve codegen. We only do this if the successor has
3617 /// phi nodes (otherwise critical edges are ok). If there is already another
3618 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
3619 /// instead of introducing a new block.
3620 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3621 BasicBlock *TIBB = TI->getParent();
3622 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3623 assert(isa<PHINode>(Dest->begin()) &&
3624 "This should only be called if Dest has a PHI!");
3626 /// TIPHIValues - This array is lazily computed to determine the values of
3627 /// PHIs in Dest that TI would provide.
3628 std::vector<Value*> TIPHIValues;
3630 // Check to see if Dest has any blocks that can be used as a split edge for
3632 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3633 BasicBlock *Pred = *PI;
3634 // To be usable, the pred has to end with an uncond branch to the dest.
3635 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3636 if (!PredBr || !PredBr->isUnconditional() ||
3637 // Must be empty other than the branch.
3638 &Pred->front() != PredBr)
3641 // Finally, since we know that Dest has phi nodes in it, we have to make
3642 // sure that jumping to Pred will have the same affect as going to Dest in
3643 // terms of PHI values.
3646 bool FoundMatch = true;
3647 for (BasicBlock::iterator I = Dest->begin();
3648 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3649 if (PHINo == TIPHIValues.size())
3650 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3652 // If the PHI entry doesn't work, we can't use this pred.
3653 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3659 // If we found a workable predecessor, change TI to branch to Succ.
3661 Dest->removePredecessor(TIBB);
3662 TI->setSuccessor(SuccNum, Pred);
3667 SplitCriticalEdge(TI, SuccNum, P, true);
3671 bool SelectionDAGISel::runOnFunction(Function &Fn) {
3672 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3673 RegMap = MF.getSSARegMap();
3674 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3676 // First, split all critical edges.
3678 // In this pass we also look for GEP and cast instructions that are used
3679 // across basic blocks and rewrite them to improve basic-block-at-a-time
3682 bool MadeChange = true;
3683 while (MadeChange) {
3685 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
3686 // Split all critical edges where the dest block has a PHI.
3687 TerminatorInst *BBTI = BB->getTerminator();
3688 if (BBTI->getNumSuccessors() > 1) {
3689 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
3690 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3691 isCriticalEdge(BBTI, i, true))
3692 SplitEdgeNicely(BBTI, i, this);
3696 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3697 Instruction *I = BBI++;
3698 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3699 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3700 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3701 // If the source of the cast is a constant, then this should have
3702 // already been constant folded. The only reason NOT to constant fold
3703 // it is if something (e.g. LSR) was careful to place the constant
3704 // evaluation in a block other than then one that uses it (e.g. to hoist
3705 // the address of globals out of a loop). If this is the case, we don't
3706 // want to forward-subst the cast.
3707 if (isa<Constant>(CI->getOperand(0)))
3710 // If this is a noop copy, sink it into user blocks to reduce the number
3711 // of virtual registers that must be created and coallesced.
3712 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3713 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3715 // This is an fp<->int conversion?
3716 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3719 // If this is an extension, it will be a zero or sign extension, which
3721 if (SrcVT < DstVT) continue;
3723 // If these values will be promoted, find out what they will be promoted
3724 // to. This helps us consider truncates on PPC as noop copies when they
3726 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3727 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3728 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3729 DstVT = TLI.getTypeToTransformTo(DstVT);
3731 // If, after promotion, these are the same types, this is a noop copy.
3733 MadeChange |= OptimizeNoopCopyExpression(CI);
3739 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3741 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3742 SelectBasicBlock(I, MF, FuncInfo);
3747 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3749 SDOperand Op = getValue(V);
3750 assert((Op.getOpcode() != ISD::CopyFromReg ||
3751 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3752 "Copy from a reg to the same reg!");
3754 // If this type is not legal, we must make sure to not create an invalid
3756 MVT::ValueType SrcVT = Op.getValueType();
3757 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3758 if (SrcVT == DestVT) {
3759 return DAG.getCopyToReg(getRoot(), Reg, Op);
3760 } else if (SrcVT == MVT::Vector) {
3761 // Handle copies from generic vectors to registers.
3762 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3763 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3764 PTyElementVT, PTyLegalElementVT);
3766 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3767 // MVT::Vector type.
3768 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3769 DAG.getConstant(NE, MVT::i32),
3770 DAG.getValueType(PTyElementVT));
3772 // Loop over all of the elements of the resultant vector,
3773 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3774 // copying them into output registers.
3775 SmallVector<SDOperand, 8> OutChains;
3776 SDOperand Root = getRoot();
3777 for (unsigned i = 0; i != NE; ++i) {
3778 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3779 Op, DAG.getConstant(i, TLI.getPointerTy()));
3780 if (PTyElementVT == PTyLegalElementVT) {
3781 // Elements are legal.
3782 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3783 } else if (PTyLegalElementVT > PTyElementVT) {
3784 // Elements are promoted.
3785 if (MVT::isFloatingPoint(PTyLegalElementVT))
3786 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3788 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3789 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3791 // Elements are expanded.
3792 // The src value is expanded into multiple registers.
3793 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3794 Elt, DAG.getConstant(0, TLI.getPointerTy()));
3795 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3796 Elt, DAG.getConstant(1, TLI.getPointerTy()));
3797 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3798 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3801 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3802 &OutChains[0], OutChains.size());
3803 } else if (SrcVT < DestVT) {
3804 // The src value is promoted to the register.
3805 if (MVT::isFloatingPoint(SrcVT))
3806 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3808 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3809 return DAG.getCopyToReg(getRoot(), Reg, Op);
3811 // The src value is expanded into multiple registers.
3812 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3813 Op, DAG.getConstant(0, TLI.getPointerTy()));
3814 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3815 Op, DAG.getConstant(1, TLI.getPointerTy()));
3816 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
3817 return DAG.getCopyToReg(Op, Reg+1, Hi);
3821 void SelectionDAGISel::
3822 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3823 std::vector<SDOperand> &UnorderedChains) {
3824 // If this is the entry block, emit arguments.
3825 Function &F = *BB->getParent();
3826 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3827 SDOperand OldRoot = SDL.DAG.getRoot();
3828 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3831 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3833 if (!AI->use_empty()) {
3834 SDL.setValue(AI, Args[a]);
3836 // If this argument is live outside of the entry block, insert a copy from
3837 // whereever we got it to the vreg that other BB's will reference it as.
3838 if (FuncInfo.ValueMap.count(AI)) {
3840 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
3841 UnorderedChains.push_back(Copy);
3845 // Finally, if the target has anything special to do, allow it to do so.
3846 // FIXME: this should insert code into the DAG!
3847 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3850 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3851 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3852 FunctionLoweringInfo &FuncInfo) {
3853 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3855 std::vector<SDOperand> UnorderedChains;
3857 // Lower any arguments needed in this block if this is the entry block.
3858 if (LLVMBB == &LLVMBB->getParent()->front())
3859 LowerArguments(LLVMBB, SDL, UnorderedChains);
3861 BB = FuncInfo.MBBMap[LLVMBB];
3862 SDL.setCurrentBasicBlock(BB);
3864 // Lower all of the non-terminator instructions.
3865 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3869 // Ensure that all instructions which are used outside of their defining
3870 // blocks are available as virtual registers.
3871 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3872 if (!I->use_empty() && !isa<PHINode>(I)) {
3873 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3874 if (VMI != FuncInfo.ValueMap.end())
3875 UnorderedChains.push_back(
3876 SDL.CopyValueToVirtualRegister(I, VMI->second));
3879 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3880 // ensure constants are generated when needed. Remember the virtual registers
3881 // that need to be added to the Machine PHI nodes as input. We cannot just
3882 // directly add them, because expansion might result in multiple MBB's for one
3883 // BB. As such, the start of the BB might correspond to a different MBB than
3886 TerminatorInst *TI = LLVMBB->getTerminator();
3888 // Emit constants only once even if used by multiple PHI nodes.
3889 std::map<Constant*, unsigned> ConstantsOut;
3891 // Vector bool would be better, but vector<bool> is really slow.
3892 std::vector<unsigned char> SuccsHandled;
3893 if (TI->getNumSuccessors())
3894 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3896 // Check successor nodes PHI nodes that expect a constant to be available from
3898 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3899 BasicBlock *SuccBB = TI->getSuccessor(succ);
3900 if (!isa<PHINode>(SuccBB->begin())) continue;
3901 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
3903 // If this terminator has multiple identical successors (common for
3904 // switches), only handle each succ once.
3905 unsigned SuccMBBNo = SuccMBB->getNumber();
3906 if (SuccsHandled[SuccMBBNo]) continue;
3907 SuccsHandled[SuccMBBNo] = true;
3909 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
3912 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3913 // nodes and Machine PHI nodes, but the incoming operands have not been
3915 for (BasicBlock::iterator I = SuccBB->begin();
3916 (PN = dyn_cast<PHINode>(I)); ++I) {
3917 // Ignore dead phi's.
3918 if (PN->use_empty()) continue;
3921 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3922 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3923 unsigned &RegOut = ConstantsOut[C];
3925 RegOut = FuncInfo.CreateRegForValue(C);
3926 UnorderedChains.push_back(
3927 SDL.CopyValueToVirtualRegister(C, RegOut));
3931 Reg = FuncInfo.ValueMap[PHIOp];
3933 assert(isa<AllocaInst>(PHIOp) &&
3934 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3935 "Didn't codegen value into a register!??");
3936 Reg = FuncInfo.CreateRegForValue(PHIOp);
3937 UnorderedChains.push_back(
3938 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
3942 // Remember that this register needs to added to the machine PHI node as
3943 // the input for this MBB.
3944 MVT::ValueType VT = TLI.getValueType(PN->getType());
3945 unsigned NumElements;
3946 if (VT != MVT::Vector)
3947 NumElements = TLI.getNumElements(VT);
3949 MVT::ValueType VT1,VT2;
3951 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3954 for (unsigned i = 0, e = NumElements; i != e; ++i)
3955 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3958 ConstantsOut.clear();
3960 // Turn all of the unordered chains into one factored node.
3961 if (!UnorderedChains.empty()) {
3962 SDOperand Root = SDL.getRoot();
3963 if (Root.getOpcode() != ISD::EntryToken) {
3964 unsigned i = 0, e = UnorderedChains.size();
3965 for (; i != e; ++i) {
3966 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3967 if (UnorderedChains[i].Val->getOperand(0) == Root)
3968 break; // Don't add the root if we already indirectly depend on it.
3972 UnorderedChains.push_back(Root);
3974 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3975 &UnorderedChains[0], UnorderedChains.size()));
3978 // Lower the terminator after the copies are emitted.
3979 SDL.visit(*LLVMBB->getTerminator());
3981 // Copy over any CaseBlock records that may now exist due to SwitchInst
3982 // lowering, as well as any jump table information.
3983 SwitchCases.clear();
3984 SwitchCases = SDL.SwitchCases;
3987 // Make sure the root of the DAG is up-to-date.
3988 DAG.setRoot(SDL.getRoot());
3991 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
3992 // Get alias analysis for load/store combining.
3993 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3995 // Run the DAG combiner in pre-legalize mode.
3996 DAG.Combine(false, AA);
3998 DEBUG(std::cerr << "Lowered selection DAG:\n");
4001 // Second step, hack on the DAG until it only uses operations and types that
4002 // the target supports.
4005 DEBUG(std::cerr << "Legalized selection DAG:\n");
4008 // Run the DAG combiner in post-legalize mode.
4009 DAG.Combine(true, AA);
4011 if (ViewISelDAGs) DAG.viewGraph();
4013 // Third, instruction select all of the operations to machine code, adding the
4014 // code to the MachineBasicBlock.
4015 InstructionSelectBasicBlock(DAG);
4017 DEBUG(std::cerr << "Selected machine code:\n");
4021 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4022 FunctionLoweringInfo &FuncInfo) {
4023 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4025 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4028 // First step, lower LLVM code to some DAG. This DAG may use operations and
4029 // types that are not supported by the target.
4030 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4032 // Second step, emit the lowered DAG as machine code.
4033 CodeGenAndEmitDAG(DAG);
4036 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4037 // PHI nodes in successors.
4038 if (SwitchCases.empty() && JT.Reg == 0) {
4039 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4040 MachineInstr *PHI = PHINodesToUpdate[i].first;
4041 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4042 "This is not a machine PHI node that we are updating!");
4043 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4044 PHI->addMachineBasicBlockOperand(BB);
4049 // If the JumpTable record is filled in, then we need to emit a jump table.
4050 // Updating the PHI nodes is tricky in this case, since we need to determine
4051 // whether the PHI is a successor of the range check MBB or the jump table MBB
4053 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4054 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4056 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4057 MachineBasicBlock *RangeBB = BB;
4058 // Set the current basic block to the mbb we wish to insert the code into
4060 SDL.setCurrentBasicBlock(BB);
4062 SDL.visitJumpTable(JT);
4063 SDAG.setRoot(SDL.getRoot());
4064 CodeGenAndEmitDAG(SDAG);
4066 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4067 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4068 MachineBasicBlock *PHIBB = PHI->getParent();
4069 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4070 "This is not a machine PHI node that we are updating!");
4071 if (PHIBB == JT.Default) {
4072 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4073 PHI->addMachineBasicBlockOperand(RangeBB);
4075 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4076 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4077 PHI->addMachineBasicBlockOperand(BB);
4083 // If the switch block involved a branch to one of the actual successors, we
4084 // need to update PHI nodes in that block.
4085 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4086 MachineInstr *PHI = PHINodesToUpdate[i].first;
4087 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4088 "This is not a machine PHI node that we are updating!");
4089 if (BB->isSuccessor(PHI->getParent())) {
4090 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4091 PHI->addMachineBasicBlockOperand(BB);
4095 // If we generated any switch lowering information, build and codegen any
4096 // additional DAGs necessary.
4097 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4098 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4100 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4102 // Set the current basic block to the mbb we wish to insert the code into
4103 BB = SwitchCases[i].ThisBB;
4104 SDL.setCurrentBasicBlock(BB);
4107 SDL.visitSwitchCase(SwitchCases[i]);
4108 SDAG.setRoot(SDL.getRoot());
4109 CodeGenAndEmitDAG(SDAG);
4111 // Handle any PHI nodes in successors of this chunk, as if we were coming
4112 // from the original BB before switch expansion. Note that PHI nodes can
4113 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4114 // handle them the right number of times.
4115 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4116 for (MachineBasicBlock::iterator Phi = BB->begin();
4117 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4118 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4119 for (unsigned pn = 0; ; ++pn) {
4120 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4121 if (PHINodesToUpdate[pn].first == Phi) {
4122 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4123 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4129 // Don't process RHS if same block as LHS.
4130 if (BB == SwitchCases[i].FalseBB)
4131 SwitchCases[i].FalseBB = 0;
4133 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4134 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4135 SwitchCases[i].FalseBB = 0;
4137 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4142 //===----------------------------------------------------------------------===//
4143 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4144 /// target node in the graph.
4145 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4146 if (ViewSchedDAGs) DAG.viewGraph();
4148 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4152 RegisterScheduler::setDefault(Ctor);
4155 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4161 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4162 return new HazardRecognizer();
4165 //===----------------------------------------------------------------------===//
4166 // Helper functions used by the generated instruction selector.
4167 //===----------------------------------------------------------------------===//
4168 // Calls to these methods are generated by tblgen.
4170 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
4171 /// the dag combiner simplified the 255, we still want to match. RHS is the
4172 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4173 /// specified in the .td file (e.g. 255).
4174 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4175 int64_t DesiredMaskS) {
4176 uint64_t ActualMask = RHS->getValue();
4177 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4179 // If the actual mask exactly matches, success!
4180 if (ActualMask == DesiredMask)
4183 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4184 if (ActualMask & ~DesiredMask)
4187 // Otherwise, the DAG Combiner may have proven that the value coming in is
4188 // either already zero or is not demanded. Check for known zero input bits.
4189 uint64_t NeededMask = DesiredMask & ~ActualMask;
4190 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4193 // TODO: check to see if missing bits are just not demanded.
4195 // Otherwise, this pattern doesn't match.
4199 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
4200 /// the dag combiner simplified the 255, we still want to match. RHS is the
4201 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4202 /// specified in the .td file (e.g. 255).
4203 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4204 int64_t DesiredMaskS) {
4205 uint64_t ActualMask = RHS->getValue();
4206 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4208 // If the actual mask exactly matches, success!
4209 if (ActualMask == DesiredMask)
4212 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4213 if (ActualMask & ~DesiredMask)
4216 // Otherwise, the DAG Combiner may have proven that the value coming in is
4217 // either already zero or is not demanded. Check for known zero input bits.
4218 uint64_t NeededMask = DesiredMask & ~ActualMask;
4220 uint64_t KnownZero, KnownOne;
4221 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4223 // If all the missing bits in the or are already known to be set, match!
4224 if ((NeededMask & KnownOne) == NeededMask)
4227 // TODO: check to see if missing bits are just not demanded.
4229 // Otherwise, this pattern doesn't match.
4234 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4235 /// by tblgen. Others should not call it.
4236 void SelectionDAGISel::
4237 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4238 std::vector<SDOperand> InOps;
4239 std::swap(InOps, Ops);
4241 Ops.push_back(InOps[0]); // input chain.
4242 Ops.push_back(InOps[1]); // input asm string.
4244 unsigned i = 2, e = InOps.size();
4245 if (InOps[e-1].getValueType() == MVT::Flag)
4246 --e; // Don't process a flag operand if it is here.
4249 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4250 if ((Flags & 7) != 4 /*MEM*/) {
4251 // Just skip over this operand, copying the operands verbatim.
4252 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4253 i += (Flags >> 3) + 1;
4255 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4256 // Otherwise, this is a memory operand. Ask the target to select it.
4257 std::vector<SDOperand> SelOps;
4258 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4259 std::cerr << "Could not match memory address. Inline asm failure!\n";
4263 // Add this to the output node.
4264 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4265 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4270 // Add the flag input back if present.
4271 if (e != InOps.size())
4272 Ops.push_back(InOps.back());