1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/ParameterAttributes.h"
29 #include "llvm/CodeGen/Collector.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SchedulerRegistry.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetFrameInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/Compiler.h"
53 ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
56 ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
59 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
60 cl::desc("Pop up a window to show SUnit dags after they are processed"));
62 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
65 //===---------------------------------------------------------------------===//
67 /// RegisterScheduler class - Track the registration of instruction schedulers.
69 //===---------------------------------------------------------------------===//
70 MachinePassRegistry RegisterScheduler::Registry;
72 //===---------------------------------------------------------------------===//
74 /// ISHeuristic command line option for instruction schedulers.
76 //===---------------------------------------------------------------------===//
77 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
78 RegisterPassParser<RegisterScheduler> >
79 ISHeuristic("pre-RA-sched",
80 cl::init(&createDefaultScheduler),
81 cl::desc("Instruction schedulers available (before register"
84 static RegisterScheduler
85 defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
88 namespace { struct SDISelAsmOperandInfo; }
90 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
91 /// insertvalue or extractvalue indices that identify a member, return
92 /// the linearized index of the start of the member.
94 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
95 const unsigned *Indices,
96 const unsigned *IndicesEnd,
97 unsigned CurIndex = 0) {
98 // Base case: We're done.
99 if (Indices == IndicesEnd)
102 // Otherwise we need to recurse. A non-negative value is used to
103 // indicate the final result value; a negative value carries the
104 // complemented position to continue the search.
105 CurIndex = ~CurIndex;
107 // Given a struct type, recursively traverse the elements.
108 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
109 for (StructType::element_iterator EI = STy->element_begin(),
110 EE = STy->element_end();
112 CurIndex = ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd,
114 if ((int)CurIndex >= 0)
118 // Given an array type, recursively traverse the elements.
119 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
120 const Type *EltTy = ATy->getElementType();
121 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
122 CurIndex = ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd,
124 if ((int)CurIndex >= 0)
128 // We haven't found the type we're looking for, so keep searching.
132 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
133 /// MVTs that represent all the individual underlying
134 /// non-aggregate types that comprise it.
136 /// If Offsets is non-null, it points to a vector to be filled in
137 /// with the in-memory offsets of each of the individual values.
139 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
140 SmallVectorImpl<MVT> &ValueVTs,
141 SmallVectorImpl<uint64_t> *Offsets = 0,
142 uint64_t StartingOffset = 0) {
143 // Given a struct type, recursively traverse the elements.
144 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
145 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
146 for (StructType::element_iterator EB = STy->element_begin(),
148 EE = STy->element_end();
150 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
151 StartingOffset + SL->getElementOffset(EI - EB));
154 // Given an array type, recursively traverse the elements.
155 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
156 const Type *EltTy = ATy->getElementType();
157 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
158 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
159 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
160 StartingOffset + i * EltSize);
163 // Base case: we can get an MVT for this LLVM IR type.
164 ValueVTs.push_back(TLI.getValueType(Ty));
166 Offsets->push_back(StartingOffset);
170 /// RegsForValue - This struct represents the registers (physical or virtual)
171 /// that a particular set of values is assigned, and the type information about
172 /// the value. The most common situation is to represent one value at a time,
173 /// but struct or array values are handled element-wise as multiple values.
174 /// The splitting of aggregates is performed recursively, so that we never
175 /// have aggregate-typed registers. The values at this point do not necessarily
176 /// have legal types, so each value may require one or more registers of some
179 struct VISIBILITY_HIDDEN RegsForValue {
180 /// TLI - The TargetLowering object.
182 const TargetLowering *TLI;
184 /// ValueVTs - The value types of the values, which may not be legal, and
185 /// may need be promoted or synthesized from one or more registers.
187 SmallVector<MVT, 4> ValueVTs;
189 /// RegVTs - The value types of the registers. This is the same size as
190 /// ValueVTs and it records, for each value, what the type of the assigned
191 /// register or registers are. (Individual values are never synthesized
192 /// from more than one type of register.)
194 /// With virtual registers, the contents of RegVTs is redundant with TLI's
195 /// getRegisterType member function, however when with physical registers
196 /// it is necessary to have a separate record of the types.
198 SmallVector<MVT, 4> RegVTs;
200 /// Regs - This list holds the registers assigned to the values.
201 /// Each legal or promoted value requires one register, and each
202 /// expanded value requires multiple registers.
204 SmallVector<unsigned, 4> Regs;
206 RegsForValue() : TLI(0) {}
208 RegsForValue(const TargetLowering &tli,
209 const SmallVector<unsigned, 4> ®s,
210 MVT regvt, MVT valuevt)
211 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
212 RegsForValue(const TargetLowering &tli,
213 const SmallVector<unsigned, 4> ®s,
214 const SmallVector<MVT, 4> ®vts,
215 const SmallVector<MVT, 4> &valuevts)
216 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
217 RegsForValue(const TargetLowering &tli,
218 unsigned Reg, const Type *Ty) : TLI(&tli) {
219 ComputeValueVTs(tli, Ty, ValueVTs);
221 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
222 MVT ValueVT = ValueVTs[Value];
223 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
224 MVT RegisterVT = TLI->getRegisterType(ValueVT);
225 for (unsigned i = 0; i != NumRegs; ++i)
226 Regs.push_back(Reg + i);
227 RegVTs.push_back(RegisterVT);
232 /// append - Add the specified values to this one.
233 void append(const RegsForValue &RHS) {
235 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
236 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
237 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
241 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
242 /// this value and returns the result as a ValueVTs value. This uses
243 /// Chain/Flag as the input and updates them for the output Chain/Flag.
244 /// If the Flag pointer is NULL, no flag is used.
245 SDOperand getCopyFromRegs(SelectionDAG &DAG,
246 SDOperand &Chain, SDOperand *Flag) const;
248 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
249 /// specified value into the registers specified by this object. This uses
250 /// Chain/Flag as the input and updates them for the output Chain/Flag.
251 /// If the Flag pointer is NULL, no flag is used.
252 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
253 SDOperand &Chain, SDOperand *Flag) const;
255 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
256 /// operand list. This adds the code marker and includes the number of
257 /// values added into it.
258 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
259 std::vector<SDOperand> &Ops) const;
264 //===--------------------------------------------------------------------===//
265 /// createDefaultScheduler - This creates an instruction scheduler appropriate
267 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
269 MachineBasicBlock *BB) {
270 TargetLowering &TLI = IS->getTargetLowering();
272 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
273 return createTDListDAGScheduler(IS, DAG, BB);
275 assert(TLI.getSchedulingPreference() ==
276 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
277 return createBURRListDAGScheduler(IS, DAG, BB);
282 //===--------------------------------------------------------------------===//
283 /// FunctionLoweringInfo - This contains information that is global to a
284 /// function that is used when lowering a region of the function.
285 class FunctionLoweringInfo {
290 MachineRegisterInfo &RegInfo;
292 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
294 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
295 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
297 /// ValueMap - Since we emit code for the function a basic block at a time,
298 /// we must remember which virtual registers hold the values for
299 /// cross-basic-block values.
300 DenseMap<const Value*, unsigned> ValueMap;
302 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
303 /// the entry block. This allows the allocas to be efficiently referenced
304 /// anywhere in the function.
305 std::map<const AllocaInst*, int> StaticAllocaMap;
308 SmallSet<Instruction*, 8> CatchInfoLost;
309 SmallSet<Instruction*, 8> CatchInfoFound;
312 unsigned MakeReg(MVT VT) {
313 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
316 /// isExportedInst - Return true if the specified value is an instruction
317 /// exported from its block.
318 bool isExportedInst(const Value *V) {
319 return ValueMap.count(V);
322 unsigned CreateRegForValue(const Value *V);
324 unsigned InitializeRegForValue(const Value *V) {
325 unsigned &R = ValueMap[V];
326 assert(R == 0 && "Already initialized this value register!");
327 return R = CreateRegForValue(V);
332 /// isSelector - Return true if this instruction is a call to the
333 /// eh.selector intrinsic.
334 static bool isSelector(Instruction *I) {
335 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
336 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
337 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
341 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
342 /// PHI nodes or outside of the basic block that defines it, or used by a
343 /// switch or atomic instruction, which may expand to multiple basic blocks.
344 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
345 if (isa<PHINode>(I)) return true;
346 BasicBlock *BB = I->getParent();
347 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
348 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
349 // FIXME: Remove switchinst special case.
350 isa<SwitchInst>(*UI))
355 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
356 /// entry block, return true. This includes arguments used by switches, since
357 /// the switch may expand into multiple basic blocks.
358 static bool isOnlyUsedInEntryBlock(Argument *A) {
359 BasicBlock *Entry = A->getParent()->begin();
360 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
361 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
362 return false; // Use not in entry block.
366 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
367 Function &fn, MachineFunction &mf)
368 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
370 // Create a vreg for each argument register that is not dead and is used
371 // outside of the entry block for the function.
372 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
374 if (!isOnlyUsedInEntryBlock(AI))
375 InitializeRegForValue(AI);
377 // Initialize the mapping of values to registers. This is only set up for
378 // instruction values that are used outside of the block that defines
380 Function::iterator BB = Fn.begin(), EB = Fn.end();
381 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
382 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
383 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
384 const Type *Ty = AI->getAllocatedType();
385 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
387 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
390 TySize *= CUI->getZExtValue(); // Get total allocated size.
391 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
392 StaticAllocaMap[AI] =
393 MF.getFrameInfo()->CreateStackObject(TySize, Align);
396 for (; BB != EB; ++BB)
397 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
398 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
399 if (!isa<AllocaInst>(I) ||
400 !StaticAllocaMap.count(cast<AllocaInst>(I)))
401 InitializeRegForValue(I);
403 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
404 // also creates the initial PHI MachineInstrs, though none of the input
405 // operands are populated.
406 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
407 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
409 MF.getBasicBlockList().push_back(MBB);
411 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
414 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
415 if (PN->use_empty()) continue;
417 MVT VT = TLI.getValueType(PN->getType());
418 unsigned NumRegisters = TLI.getNumRegisters(VT);
419 unsigned PHIReg = ValueMap[PN];
420 assert(PHIReg && "PHI node does not have an assigned virtual register!");
421 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
422 for (unsigned i = 0; i != NumRegisters; ++i)
423 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
428 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
429 /// the correctly promoted or expanded types. Assign these registers
430 /// consecutive vreg numbers and return the first assigned number.
432 /// In the case that the given value has struct or array type, this function
433 /// will assign registers for each member or element.
435 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
436 SmallVector<MVT, 4> ValueVTs;
437 ComputeValueVTs(TLI, V->getType(), ValueVTs);
439 unsigned FirstReg = 0;
440 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
441 MVT ValueVT = ValueVTs[Value];
442 MVT RegisterVT = TLI.getRegisterType(ValueVT);
444 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
445 for (unsigned i = 0; i != NumRegs; ++i) {
446 unsigned R = MakeReg(RegisterVT);
447 if (!FirstReg) FirstReg = R;
453 //===----------------------------------------------------------------------===//
454 /// SelectionDAGLowering - This is the common target-independent lowering
455 /// implementation that is parameterized by a TargetLowering object.
456 /// Also, targets can overload any lowering method.
459 class SelectionDAGLowering {
460 MachineBasicBlock *CurMBB;
462 DenseMap<const Value*, SDOperand> NodeMap;
464 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
465 /// them up and then emit token factor nodes when possible. This allows us to
466 /// get simple disambiguation between loads without worrying about alias
468 std::vector<SDOperand> PendingLoads;
470 /// PendingExports - CopyToReg nodes that copy values to virtual registers
471 /// for export to other blocks need to be emitted before any terminator
472 /// instruction, but they have no other ordering requirements. We bunch them
473 /// up and the emit a single tokenfactor for them just before terminator
475 std::vector<SDOperand> PendingExports;
477 /// Case - A struct to record the Value for a switch case, and the
478 /// case's target basic block.
482 MachineBasicBlock* BB;
484 Case() : Low(0), High(0), BB(0) { }
485 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
486 Low(low), High(high), BB(bb) { }
487 uint64_t size() const {
488 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
489 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
490 return (rHigh - rLow + 1ULL);
496 MachineBasicBlock* BB;
499 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
500 Mask(mask), BB(bb), Bits(bits) { }
503 typedef std::vector<Case> CaseVector;
504 typedef std::vector<CaseBits> CaseBitsVector;
505 typedef CaseVector::iterator CaseItr;
506 typedef std::pair<CaseItr, CaseItr> CaseRange;
508 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
509 /// of conditional branches.
511 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
512 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
514 /// CaseBB - The MBB in which to emit the compare and branch
515 MachineBasicBlock *CaseBB;
516 /// LT, GE - If nonzero, we know the current case value must be less-than or
517 /// greater-than-or-equal-to these Constants.
520 /// Range - A pair of iterators representing the range of case values to be
521 /// processed at this point in the binary search tree.
525 typedef std::vector<CaseRec> CaseRecVector;
527 /// The comparison function for sorting the switch case values in the vector.
528 /// WARNING: Case ranges should be disjoint!
530 bool operator () (const Case& C1, const Case& C2) {
531 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
532 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
533 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
534 return CI1->getValue().slt(CI2->getValue());
539 bool operator () (const CaseBits& C1, const CaseBits& C2) {
540 return C1.Bits > C2.Bits;
544 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
547 // TLI - This is information that describes the available target features we
548 // need for lowering. This indicates when operations are unavailable,
549 // implemented with a libcall, etc.
552 const TargetData *TD;
555 /// SwitchCases - Vector of CaseBlock structures used to communicate
556 /// SwitchInst code generation information.
557 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
558 /// JTCases - Vector of JumpTable structures used to communicate
559 /// SwitchInst code generation information.
560 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
561 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
563 /// FuncInfo - Information about the function as a whole.
565 FunctionLoweringInfo &FuncInfo;
567 /// GCI - Garbage collection metadata for the function.
568 CollectorMetadata *GCI;
570 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
572 FunctionLoweringInfo &funcinfo,
573 CollectorMetadata *gci)
574 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
575 FuncInfo(funcinfo), GCI(gci) {
578 /// getRoot - Return the current virtual root of the Selection DAG,
579 /// flushing any PendingLoad items. This must be done before emitting
580 /// a store or any other node that may need to be ordered after any
581 /// prior load instructions.
583 SDOperand getRoot() {
584 if (PendingLoads.empty())
585 return DAG.getRoot();
587 if (PendingLoads.size() == 1) {
588 SDOperand Root = PendingLoads[0];
590 PendingLoads.clear();
594 // Otherwise, we have to make a token factor node.
595 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
596 &PendingLoads[0], PendingLoads.size());
597 PendingLoads.clear();
602 /// getControlRoot - Similar to getRoot, but instead of flushing all the
603 /// PendingLoad items, flush all the PendingExports items. It is necessary
604 /// to do this before emitting a terminator instruction.
606 SDOperand getControlRoot() {
607 SDOperand Root = DAG.getRoot();
609 if (PendingExports.empty())
612 // Turn all of the CopyToReg chains into one factored node.
613 if (Root.getOpcode() != ISD::EntryToken) {
614 unsigned i = 0, e = PendingExports.size();
615 for (; i != e; ++i) {
616 assert(PendingExports[i].Val->getNumOperands() > 1);
617 if (PendingExports[i].Val->getOperand(0) == Root)
618 break; // Don't add the root if we already indirectly depend on it.
622 PendingExports.push_back(Root);
625 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
627 PendingExports.size());
628 PendingExports.clear();
633 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
635 void visit(Instruction &I) { visit(I.getOpcode(), I); }
637 void visit(unsigned Opcode, User &I) {
638 // Note: this doesn't use InstVisitor, because it has to work with
639 // ConstantExpr's in addition to instructions.
641 default: assert(0 && "Unknown instruction type encountered!");
643 // Build the switch statement using the Instruction.def file.
644 #define HANDLE_INST(NUM, OPCODE, CLASS) \
645 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
646 #include "llvm/Instruction.def"
650 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
652 SDOperand getValue(const Value *V);
654 void setValue(const Value *V, SDOperand NewN) {
655 SDOperand &N = NodeMap[V];
656 assert(N.Val == 0 && "Already set a value for this node!");
660 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
661 std::set<unsigned> &OutputRegs,
662 std::set<unsigned> &InputRegs);
664 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
665 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
667 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
668 void ExportFromCurrentBlock(Value *V);
669 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
670 MachineBasicBlock *LandingPad = NULL);
672 // Terminator instructions.
673 void visitRet(ReturnInst &I);
674 void visitBr(BranchInst &I);
675 void visitSwitch(SwitchInst &I);
676 void visitUnreachable(UnreachableInst &I) { /* noop */ }
678 // Helpers for visitSwitch
679 bool handleSmallSwitchRange(CaseRec& CR,
680 CaseRecVector& WorkList,
682 MachineBasicBlock* Default);
683 bool handleJTSwitchCase(CaseRec& CR,
684 CaseRecVector& WorkList,
686 MachineBasicBlock* Default);
687 bool handleBTSplitSwitchCase(CaseRec& CR,
688 CaseRecVector& WorkList,
690 MachineBasicBlock* Default);
691 bool handleBitTestsSwitchCase(CaseRec& CR,
692 CaseRecVector& WorkList,
694 MachineBasicBlock* Default);
695 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
696 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
697 void visitBitTestCase(MachineBasicBlock* NextMBB,
699 SelectionDAGISel::BitTestCase &B);
700 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
701 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
702 SelectionDAGISel::JumpTableHeader &JTH);
704 // These all get lowered before this pass.
705 void visitInvoke(InvokeInst &I);
706 void visitUnwind(UnwindInst &I);
708 void visitBinary(User &I, unsigned OpCode);
709 void visitShift(User &I, unsigned Opcode);
710 void visitAdd(User &I) {
711 if (I.getType()->isFPOrFPVector())
712 visitBinary(I, ISD::FADD);
714 visitBinary(I, ISD::ADD);
716 void visitSub(User &I);
717 void visitMul(User &I) {
718 if (I.getType()->isFPOrFPVector())
719 visitBinary(I, ISD::FMUL);
721 visitBinary(I, ISD::MUL);
723 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
724 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
725 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
726 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
727 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
728 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
729 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
730 void visitOr (User &I) { visitBinary(I, ISD::OR); }
731 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
732 void visitShl (User &I) { visitShift(I, ISD::SHL); }
733 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
734 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
735 void visitICmp(User &I);
736 void visitFCmp(User &I);
737 void visitVICmp(User &I);
738 void visitVFCmp(User &I);
739 // Visit the conversion instructions
740 void visitTrunc(User &I);
741 void visitZExt(User &I);
742 void visitSExt(User &I);
743 void visitFPTrunc(User &I);
744 void visitFPExt(User &I);
745 void visitFPToUI(User &I);
746 void visitFPToSI(User &I);
747 void visitUIToFP(User &I);
748 void visitSIToFP(User &I);
749 void visitPtrToInt(User &I);
750 void visitIntToPtr(User &I);
751 void visitBitCast(User &I);
753 void visitExtractElement(User &I);
754 void visitInsertElement(User &I);
755 void visitShuffleVector(User &I);
757 void visitExtractValue(ExtractValueInst &I);
758 void visitInsertValue(InsertValueInst &I);
760 void visitGetElementPtr(User &I);
761 void visitSelect(User &I);
763 void visitMalloc(MallocInst &I);
764 void visitFree(FreeInst &I);
765 void visitAlloca(AllocaInst &I);
766 void visitLoad(LoadInst &I);
767 void visitStore(StoreInst &I);
768 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
769 void visitCall(CallInst &I);
770 void visitInlineAsm(CallSite CS);
771 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
772 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
774 void visitVAStart(CallInst &I);
775 void visitVAArg(VAArgInst &I);
776 void visitVAEnd(CallInst &I);
777 void visitVACopy(CallInst &I);
779 void visitGetResult(GetResultInst &I);
781 void visitUserOp1(Instruction &I) {
782 assert(0 && "UserOp1 should not exist at instruction selection time!");
785 void visitUserOp2(Instruction &I) {
786 assert(0 && "UserOp2 should not exist at instruction selection time!");
791 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
794 } // end namespace llvm
797 /// getCopyFromParts - Create a value that contains the specified legal parts
798 /// combined into the value they represent. If the parts combine to a type
799 /// larger then ValueVT then AssertOp can be used to specify whether the extra
800 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
801 /// (ISD::AssertSext).
802 static SDOperand getCopyFromParts(SelectionDAG &DAG,
803 const SDOperand *Parts,
807 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
808 assert(NumParts > 0 && "No parts to assemble!");
809 TargetLowering &TLI = DAG.getTargetLoweringInfo();
810 SDOperand Val = Parts[0];
813 // Assemble the value from multiple parts.
814 if (!ValueVT.isVector()) {
815 unsigned PartBits = PartVT.getSizeInBits();
816 unsigned ValueBits = ValueVT.getSizeInBits();
818 // Assemble the power of 2 part.
819 unsigned RoundParts = NumParts & (NumParts - 1) ?
820 1 << Log2_32(NumParts) : NumParts;
821 unsigned RoundBits = PartBits * RoundParts;
822 MVT RoundVT = RoundBits == ValueBits ?
823 ValueVT : MVT::getIntegerVT(RoundBits);
826 if (RoundParts > 2) {
827 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
828 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
829 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
835 if (TLI.isBigEndian())
837 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
839 if (RoundParts < NumParts) {
840 // Assemble the trailing non-power-of-2 part.
841 unsigned OddParts = NumParts - RoundParts;
842 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
843 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
845 // Combine the round and odd parts.
847 if (TLI.isBigEndian())
849 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
850 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
851 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
852 DAG.getConstant(Lo.getValueType().getSizeInBits(),
853 TLI.getShiftAmountTy()));
854 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
855 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
858 // Handle a multi-element vector.
859 MVT IntermediateVT, RegisterVT;
860 unsigned NumIntermediates;
862 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
864 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
865 NumParts = NumRegs; // Silence a compiler warning.
866 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
867 assert(RegisterVT == Parts[0].getValueType() &&
868 "Part type doesn't match part!");
870 // Assemble the parts into intermediate operands.
871 SmallVector<SDOperand, 8> Ops(NumIntermediates);
872 if (NumIntermediates == NumParts) {
873 // If the register was not expanded, truncate or copy the value,
875 for (unsigned i = 0; i != NumParts; ++i)
876 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
877 PartVT, IntermediateVT);
878 } else if (NumParts > 0) {
879 // If the intermediate type was expanded, build the intermediate operands
881 assert(NumParts % NumIntermediates == 0 &&
882 "Must expand into a divisible number of parts!");
883 unsigned Factor = NumParts / NumIntermediates;
884 for (unsigned i = 0; i != NumIntermediates; ++i)
885 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
886 PartVT, IntermediateVT);
889 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
891 Val = DAG.getNode(IntermediateVT.isVector() ?
892 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
893 ValueVT, &Ops[0], NumIntermediates);
897 // There is now one part, held in Val. Correct it to match ValueVT.
898 PartVT = Val.getValueType();
900 if (PartVT == ValueVT)
903 if (PartVT.isVector()) {
904 assert(ValueVT.isVector() && "Unknown vector conversion!");
905 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
908 if (ValueVT.isVector()) {
909 assert(ValueVT.getVectorElementType() == PartVT &&
910 ValueVT.getVectorNumElements() == 1 &&
911 "Only trivial scalar-to-vector conversions should get here!");
912 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
915 if (PartVT.isInteger() &&
916 ValueVT.isInteger()) {
917 if (ValueVT.bitsLT(PartVT)) {
918 // For a truncate, see if we have any information to
919 // indicate whether the truncated bits will always be
920 // zero or sign-extension.
921 if (AssertOp != ISD::DELETED_NODE)
922 Val = DAG.getNode(AssertOp, PartVT, Val,
923 DAG.getValueType(ValueVT));
924 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
926 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
930 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
931 if (ValueVT.bitsLT(Val.getValueType()))
932 // FP_ROUND's are always exact here.
933 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
934 DAG.getIntPtrConstant(1));
935 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
938 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
939 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
941 assert(0 && "Unknown mismatch!");
945 /// getCopyToParts - Create a series of nodes that contain the specified value
946 /// split into legal parts. If the parts contain more bits than Val, then, for
947 /// integers, ExtendKind can be used to specify how to generate the extra bits.
948 static void getCopyToParts(SelectionDAG &DAG,
953 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
954 TargetLowering &TLI = DAG.getTargetLoweringInfo();
955 MVT PtrVT = TLI.getPointerTy();
956 MVT ValueVT = Val.getValueType();
957 unsigned PartBits = PartVT.getSizeInBits();
958 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
963 if (!ValueVT.isVector()) {
964 if (PartVT == ValueVT) {
965 assert(NumParts == 1 && "No-op copy with multiple parts!");
970 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
971 // If the parts cover more bits than the value has, promote the value.
972 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
973 assert(NumParts == 1 && "Do not know what to promote to!");
974 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
975 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
976 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
977 Val = DAG.getNode(ExtendKind, ValueVT, Val);
979 assert(0 && "Unknown mismatch!");
981 } else if (PartBits == ValueVT.getSizeInBits()) {
982 // Different types of the same size.
983 assert(NumParts == 1 && PartVT != ValueVT);
984 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
985 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
986 // If the parts cover less bits than value has, truncate the value.
987 if (PartVT.isInteger() && ValueVT.isInteger()) {
988 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
989 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
991 assert(0 && "Unknown mismatch!");
995 // The value may have changed - recompute ValueVT.
996 ValueVT = Val.getValueType();
997 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
998 "Failed to tile the value with PartVT!");
1000 if (NumParts == 1) {
1001 assert(PartVT == ValueVT && "Type conversion failed!");
1006 // Expand the value into multiple parts.
1007 if (NumParts & (NumParts - 1)) {
1008 // The number of parts is not a power of 2. Split off and copy the tail.
1009 assert(PartVT.isInteger() && ValueVT.isInteger() &&
1010 "Do not know what to expand to!");
1011 unsigned RoundParts = 1 << Log2_32(NumParts);
1012 unsigned RoundBits = RoundParts * PartBits;
1013 unsigned OddParts = NumParts - RoundParts;
1014 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
1015 DAG.getConstant(RoundBits,
1016 TLI.getShiftAmountTy()));
1017 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1018 if (TLI.isBigEndian())
1019 // The odd parts were reversed by getCopyToParts - unreverse them.
1020 std::reverse(Parts + RoundParts, Parts + NumParts);
1021 NumParts = RoundParts;
1022 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
1023 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1026 // The number of parts is a power of 2. Repeatedly bisect the value using
1028 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
1029 MVT::getIntegerVT(ValueVT.getSizeInBits()),
1031 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1032 for (unsigned i = 0; i < NumParts; i += StepSize) {
1033 unsigned ThisBits = StepSize * PartBits / 2;
1034 MVT ThisVT = MVT::getIntegerVT (ThisBits);
1035 SDOperand &Part0 = Parts[i];
1036 SDOperand &Part1 = Parts[i+StepSize/2];
1038 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1039 DAG.getConstant(1, PtrVT));
1040 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1041 DAG.getConstant(0, PtrVT));
1043 if (ThisBits == PartBits && ThisVT != PartVT) {
1044 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1045 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1050 if (TLI.isBigEndian())
1051 std::reverse(Parts, Parts + NumParts);
1057 if (NumParts == 1) {
1058 if (PartVT != ValueVT) {
1059 if (PartVT.isVector()) {
1060 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1062 assert(ValueVT.getVectorElementType() == PartVT &&
1063 ValueVT.getVectorNumElements() == 1 &&
1064 "Only trivial vector-to-scalar conversions should get here!");
1065 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1066 DAG.getConstant(0, PtrVT));
1074 // Handle a multi-element vector.
1075 MVT IntermediateVT, RegisterVT;
1076 unsigned NumIntermediates;
1078 DAG.getTargetLoweringInfo()
1079 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1081 unsigned NumElements = ValueVT.getVectorNumElements();
1083 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1084 NumParts = NumRegs; // Silence a compiler warning.
1085 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1087 // Split the vector into intermediate operands.
1088 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1089 for (unsigned i = 0; i != NumIntermediates; ++i)
1090 if (IntermediateVT.isVector())
1091 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1092 IntermediateVT, Val,
1093 DAG.getConstant(i * (NumElements / NumIntermediates),
1096 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1097 IntermediateVT, Val,
1098 DAG.getConstant(i, PtrVT));
1100 // Split the intermediate operands into legal parts.
1101 if (NumParts == NumIntermediates) {
1102 // If the register was not expanded, promote or copy the value,
1104 for (unsigned i = 0; i != NumParts; ++i)
1105 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1106 } else if (NumParts > 0) {
1107 // If the intermediate type was expanded, split each the value into
1109 assert(NumParts % NumIntermediates == 0 &&
1110 "Must expand into a divisible number of parts!");
1111 unsigned Factor = NumParts / NumIntermediates;
1112 for (unsigned i = 0; i != NumIntermediates; ++i)
1113 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1118 SDOperand SelectionDAGLowering::getValue(const Value *V) {
1119 SDOperand &N = NodeMap[V];
1120 if (N.Val) return N;
1122 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1123 MVT VT = TLI.getValueType(V->getType(), true);
1125 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1126 return N = DAG.getConstant(CI->getValue(), VT);
1128 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1129 return N = DAG.getGlobalAddress(GV, VT);
1131 if (isa<ConstantPointerNull>(C))
1132 return N = DAG.getConstant(0, TLI.getPointerTy());
1134 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1135 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1137 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1138 !V->getType()->isAggregateType())
1139 return N = DAG.getNode(ISD::UNDEF, VT);
1141 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1142 visit(CE->getOpcode(), *CE);
1143 SDOperand N1 = NodeMap[V];
1144 assert(N1.Val && "visit didn't populate the ValueMap!");
1148 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1149 SmallVector<SDOperand, 4> Constants;
1150 SmallVector<MVT, 4> ValueVTs;
1151 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1153 SDNode *Val = getValue(*OI).Val;
1154 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) {
1155 Constants.push_back(SDOperand(Val, i));
1156 ValueVTs.push_back(Val->getValueType(i));
1159 return DAG.getNode(ISD::MERGE_VALUES,
1160 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1161 &Constants[0], Constants.size());
1164 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
1165 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1166 "Unknown array constant!");
1167 unsigned NumElts = ATy->getNumElements();
1169 return SDOperand(); // empty array
1170 MVT EltVT = TLI.getValueType(ATy->getElementType());
1171 SmallVector<SDOperand, 4> Constants(NumElts);
1172 SmallVector<MVT, 4> ValueVTs(NumElts, EltVT);
1173 for (unsigned i = 0, e = NumElts; i != e; ++i) {
1174 if (isa<UndefValue>(C))
1175 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1176 else if (EltVT.isFloatingPoint())
1177 Constants[i] = DAG.getConstantFP(0, EltVT);
1179 Constants[i] = DAG.getConstant(0, EltVT);
1181 return DAG.getNode(ISD::MERGE_VALUES,
1182 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1183 &Constants[0], Constants.size());
1186 if (const StructType *STy = dyn_cast<StructType>(C->getType())) {
1187 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1188 "Unknown struct constant!");
1189 unsigned NumElts = STy->getNumElements();
1191 return SDOperand(); // empty struct
1192 SmallVector<SDOperand, 4> Constants(NumElts);
1193 SmallVector<MVT, 4> ValueVTs(NumElts);
1194 for (unsigned i = 0, e = NumElts; i != e; ++i) {
1195 MVT EltVT = TLI.getValueType(STy->getElementType(i));
1196 ValueVTs[i] = EltVT;
1197 if (isa<UndefValue>(C))
1198 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1199 else if (EltVT.isFloatingPoint())
1200 Constants[i] = DAG.getConstantFP(0, EltVT);
1202 Constants[i] = DAG.getConstant(0, EltVT);
1204 return DAG.getNode(ISD::MERGE_VALUES,
1205 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1206 &Constants[0], Constants.size());
1209 const VectorType *VecTy = cast<VectorType>(V->getType());
1210 unsigned NumElements = VecTy->getNumElements();
1212 // Now that we know the number and type of the elements, get that number of
1213 // elements into the Ops array based on what kind of constant it is.
1214 SmallVector<SDOperand, 16> Ops;
1215 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1216 for (unsigned i = 0; i != NumElements; ++i)
1217 Ops.push_back(getValue(CP->getOperand(i)));
1219 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1220 "Unknown vector constant!");
1221 MVT EltVT = TLI.getValueType(VecTy->getElementType());
1224 if (isa<UndefValue>(C))
1225 Op = DAG.getNode(ISD::UNDEF, EltVT);
1226 else if (EltVT.isFloatingPoint())
1227 Op = DAG.getConstantFP(0, EltVT);
1229 Op = DAG.getConstant(0, EltVT);
1230 Ops.assign(NumElements, Op);
1233 // Create a BUILD_VECTOR node.
1234 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1237 // If this is a static alloca, generate it as the frameindex instead of
1239 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1240 std::map<const AllocaInst*, int>::iterator SI =
1241 FuncInfo.StaticAllocaMap.find(AI);
1242 if (SI != FuncInfo.StaticAllocaMap.end())
1243 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1246 unsigned InReg = FuncInfo.ValueMap[V];
1247 assert(InReg && "Value not in map!");
1249 RegsForValue RFV(TLI, InReg, V->getType());
1250 SDOperand Chain = DAG.getEntryNode();
1251 return RFV.getCopyFromRegs(DAG, Chain, NULL);
1255 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1256 if (I.getNumOperands() == 0) {
1257 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1261 SmallVector<SDOperand, 8> NewValues;
1262 NewValues.push_back(getControlRoot());
1263 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1264 SDOperand RetOp = getValue(I.getOperand(i));
1265 MVT VT = RetOp.getValueType();
1267 // FIXME: C calling convention requires the return type to be promoted to
1268 // at least 32-bit. But this is not necessary for non-C calling conventions.
1269 if (VT.isInteger()) {
1270 MVT MinVT = TLI.getRegisterType(MVT::i32);
1271 if (VT.bitsLT(MinVT))
1275 unsigned NumParts = TLI.getNumRegisters(VT);
1276 MVT PartVT = TLI.getRegisterType(VT);
1277 SmallVector<SDOperand, 4> Parts(NumParts);
1278 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1280 const Function *F = I.getParent()->getParent();
1281 if (F->paramHasAttr(0, ParamAttr::SExt))
1282 ExtendKind = ISD::SIGN_EXTEND;
1283 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1284 ExtendKind = ISD::ZERO_EXTEND;
1286 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1288 for (unsigned i = 0; i < NumParts; ++i) {
1289 NewValues.push_back(Parts[i]);
1290 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1293 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1294 &NewValues[0], NewValues.size()));
1297 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1298 /// the current basic block, add it to ValueMap now so that we'll get a
1300 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1301 // No need to export constants.
1302 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1304 // Already exported?
1305 if (FuncInfo.isExportedInst(V)) return;
1307 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1308 CopyValueToVirtualRegister(V, Reg);
1311 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1312 const BasicBlock *FromBB) {
1313 // The operands of the setcc have to be in this block. We don't know
1314 // how to export them from some other block.
1315 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1316 // Can export from current BB.
1317 if (VI->getParent() == FromBB)
1320 // Is already exported, noop.
1321 return FuncInfo.isExportedInst(V);
1324 // If this is an argument, we can export it if the BB is the entry block or
1325 // if it is already exported.
1326 if (isa<Argument>(V)) {
1327 if (FromBB == &FromBB->getParent()->getEntryBlock())
1330 // Otherwise, can only export this if it is already exported.
1331 return FuncInfo.isExportedInst(V);
1334 // Otherwise, constants can always be exported.
1338 static bool InBlock(const Value *V, const BasicBlock *BB) {
1339 if (const Instruction *I = dyn_cast<Instruction>(V))
1340 return I->getParent() == BB;
1344 /// FindMergedConditions - If Cond is an expression like
1345 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1346 MachineBasicBlock *TBB,
1347 MachineBasicBlock *FBB,
1348 MachineBasicBlock *CurBB,
1350 // If this node is not part of the or/and tree, emit it as a branch.
1351 Instruction *BOp = dyn_cast<Instruction>(Cond);
1353 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1354 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1355 BOp->getParent() != CurBB->getBasicBlock() ||
1356 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1357 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1358 const BasicBlock *BB = CurBB->getBasicBlock();
1360 // If the leaf of the tree is a comparison, merge the condition into
1362 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1363 // The operands of the cmp have to be in this block. We don't know
1364 // how to export them from some other block. If this is the first block
1365 // of the sequence, no exporting is needed.
1367 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1368 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1369 BOp = cast<Instruction>(Cond);
1370 ISD::CondCode Condition;
1371 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1372 switch (IC->getPredicate()) {
1373 default: assert(0 && "Unknown icmp predicate opcode!");
1374 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1375 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1376 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1377 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1378 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1379 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1380 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1381 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1382 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1383 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1385 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1386 ISD::CondCode FPC, FOC;
1387 switch (FC->getPredicate()) {
1388 default: assert(0 && "Unknown fcmp predicate opcode!");
1389 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1390 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1391 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1392 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1393 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1394 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1395 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1396 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1397 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1398 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1399 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1400 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1401 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1402 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1403 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1404 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1406 if (FiniteOnlyFPMath())
1411 Condition = ISD::SETEQ; // silence warning.
1412 assert(0 && "Unknown compare instruction");
1415 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1416 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1417 SwitchCases.push_back(CB);
1421 // Create a CaseBlock record representing this branch.
1422 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1423 NULL, TBB, FBB, CurBB);
1424 SwitchCases.push_back(CB);
1429 // Create TmpBB after CurBB.
1430 MachineFunction::iterator BBI = CurBB;
1431 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1432 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1434 if (Opc == Instruction::Or) {
1435 // Codegen X | Y as:
1443 // Emit the LHS condition.
1444 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1446 // Emit the RHS condition into TmpBB.
1447 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1449 assert(Opc == Instruction::And && "Unknown merge op!");
1450 // Codegen X & Y as:
1457 // This requires creation of TmpBB after CurBB.
1459 // Emit the LHS condition.
1460 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1462 // Emit the RHS condition into TmpBB.
1463 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1467 /// If the set of cases should be emitted as a series of branches, return true.
1468 /// If we should emit this as a bunch of and/or'd together conditions, return
1471 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1472 if (Cases.size() != 2) return true;
1474 // If this is two comparisons of the same values or'd or and'd together, they
1475 // will get folded into a single comparison, so don't emit two blocks.
1476 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1477 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1478 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1479 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1486 void SelectionDAGLowering::visitBr(BranchInst &I) {
1487 // Update machine-CFG edges.
1488 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1490 // Figure out which block is immediately after the current one.
1491 MachineBasicBlock *NextBlock = 0;
1492 MachineFunction::iterator BBI = CurMBB;
1493 if (++BBI != CurMBB->getParent()->end())
1496 if (I.isUnconditional()) {
1497 // Update machine-CFG edges.
1498 CurMBB->addSuccessor(Succ0MBB);
1500 // If this is not a fall-through branch, emit the branch.
1501 if (Succ0MBB != NextBlock)
1502 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1503 DAG.getBasicBlock(Succ0MBB)));
1507 // If this condition is one of the special cases we handle, do special stuff
1509 Value *CondVal = I.getCondition();
1510 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1512 // If this is a series of conditions that are or'd or and'd together, emit
1513 // this as a sequence of branches instead of setcc's with and/or operations.
1514 // For example, instead of something like:
1527 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1528 if (BOp->hasOneUse() &&
1529 (BOp->getOpcode() == Instruction::And ||
1530 BOp->getOpcode() == Instruction::Or)) {
1531 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1532 // If the compares in later blocks need to use values not currently
1533 // exported from this block, export them now. This block should always
1534 // be the first entry.
1535 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1537 // Allow some cases to be rejected.
1538 if (ShouldEmitAsBranches(SwitchCases)) {
1539 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1540 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1541 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1544 // Emit the branch for this block.
1545 visitSwitchCase(SwitchCases[0]);
1546 SwitchCases.erase(SwitchCases.begin());
1550 // Okay, we decided not to do this, remove any inserted MBB's and clear
1552 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1553 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1555 SwitchCases.clear();
1559 // Create a CaseBlock record representing this branch.
1560 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1561 NULL, Succ0MBB, Succ1MBB, CurMBB);
1562 // Use visitSwitchCase to actually insert the fast branch sequence for this
1564 visitSwitchCase(CB);
1567 /// visitSwitchCase - Emits the necessary code to represent a single node in
1568 /// the binary search tree resulting from lowering a switch instruction.
1569 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1571 SDOperand CondLHS = getValue(CB.CmpLHS);
1573 // Build the setcc now.
1574 if (CB.CmpMHS == NULL) {
1575 // Fold "(X == true)" to X and "(X == false)" to !X to
1576 // handle common cases produced by branch lowering.
1577 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1579 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1580 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1581 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1583 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1585 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1587 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1588 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1590 SDOperand CmpOp = getValue(CB.CmpMHS);
1591 MVT VT = CmpOp.getValueType();
1593 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1594 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1596 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1597 Cond = DAG.getSetCC(MVT::i1, SUB,
1598 DAG.getConstant(High-Low, VT), ISD::SETULE);
1602 // Update successor info
1603 CurMBB->addSuccessor(CB.TrueBB);
1604 CurMBB->addSuccessor(CB.FalseBB);
1606 // Set NextBlock to be the MBB immediately after the current one, if any.
1607 // This is used to avoid emitting unnecessary branches to the next block.
1608 MachineBasicBlock *NextBlock = 0;
1609 MachineFunction::iterator BBI = CurMBB;
1610 if (++BBI != CurMBB->getParent()->end())
1613 // If the lhs block is the next block, invert the condition so that we can
1614 // fall through to the lhs instead of the rhs block.
1615 if (CB.TrueBB == NextBlock) {
1616 std::swap(CB.TrueBB, CB.FalseBB);
1617 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1618 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1620 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1621 DAG.getBasicBlock(CB.TrueBB));
1622 if (CB.FalseBB == NextBlock)
1623 DAG.setRoot(BrCond);
1625 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1626 DAG.getBasicBlock(CB.FalseBB)));
1629 /// visitJumpTable - Emit JumpTable node in the current MBB
1630 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1631 // Emit the code for the jump table
1632 assert(JT.Reg != -1U && "Should lower JT Header first!");
1633 MVT PTy = TLI.getPointerTy();
1634 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1635 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1636 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1641 /// visitJumpTableHeader - This function emits necessary code to produce index
1642 /// in the JumpTable from switch case.
1643 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1644 SelectionDAGISel::JumpTableHeader &JTH) {
1645 // Subtract the lowest switch case value from the value being switched on
1646 // and conditional branch to default mbb if the result is greater than the
1647 // difference between smallest and largest cases.
1648 SDOperand SwitchOp = getValue(JTH.SValue);
1649 MVT VT = SwitchOp.getValueType();
1650 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1651 DAG.getConstant(JTH.First, VT));
1653 // The SDNode we just created, which holds the value being switched on
1654 // minus the the smallest case value, needs to be copied to a virtual
1655 // register so it can be used as an index into the jump table in a
1656 // subsequent basic block. This value may be smaller or larger than the
1657 // target's pointer type, and therefore require extension or truncating.
1658 if (VT.bitsGT(TLI.getPointerTy()))
1659 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1661 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1663 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1664 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1665 JT.Reg = JumpTableReg;
1667 // Emit the range check for the jump table, and branch to the default
1668 // block for the switch statement if the value being switched on exceeds
1669 // the largest case in the switch.
1670 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1671 DAG.getConstant(JTH.Last-JTH.First,VT),
1674 // Set NextBlock to be the MBB immediately after the current one, if any.
1675 // This is used to avoid emitting unnecessary branches to the next block.
1676 MachineBasicBlock *NextBlock = 0;
1677 MachineFunction::iterator BBI = CurMBB;
1678 if (++BBI != CurMBB->getParent()->end())
1681 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1682 DAG.getBasicBlock(JT.Default));
1684 if (JT.MBB == NextBlock)
1685 DAG.setRoot(BrCond);
1687 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1688 DAG.getBasicBlock(JT.MBB)));
1693 /// visitBitTestHeader - This function emits necessary code to produce value
1694 /// suitable for "bit tests"
1695 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1696 // Subtract the minimum value
1697 SDOperand SwitchOp = getValue(B.SValue);
1698 MVT VT = SwitchOp.getValueType();
1699 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1700 DAG.getConstant(B.First, VT));
1703 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1704 DAG.getConstant(B.Range, VT),
1708 if (VT.bitsGT(TLI.getShiftAmountTy()))
1709 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1711 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1713 // Make desired shift
1714 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1715 DAG.getConstant(1, TLI.getPointerTy()),
1718 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1719 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1722 // Set NextBlock to be the MBB immediately after the current one, if any.
1723 // This is used to avoid emitting unnecessary branches to the next block.
1724 MachineBasicBlock *NextBlock = 0;
1725 MachineFunction::iterator BBI = CurMBB;
1726 if (++BBI != CurMBB->getParent()->end())
1729 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1731 CurMBB->addSuccessor(B.Default);
1732 CurMBB->addSuccessor(MBB);
1734 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1735 DAG.getBasicBlock(B.Default));
1737 if (MBB == NextBlock)
1738 DAG.setRoot(BrRange);
1740 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1741 DAG.getBasicBlock(MBB)));
1746 /// visitBitTestCase - this function produces one "bit test"
1747 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1749 SelectionDAGISel::BitTestCase &B) {
1750 // Emit bit tests and jumps
1751 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
1753 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1755 DAG.getConstant(B.Mask,
1756 TLI.getPointerTy()));
1757 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1758 DAG.getConstant(0, TLI.getPointerTy()),
1761 CurMBB->addSuccessor(B.TargetBB);
1762 CurMBB->addSuccessor(NextMBB);
1764 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1765 AndCmp, DAG.getBasicBlock(B.TargetBB));
1767 // Set NextBlock to be the MBB immediately after the current one, if any.
1768 // This is used to avoid emitting unnecessary branches to the next block.
1769 MachineBasicBlock *NextBlock = 0;
1770 MachineFunction::iterator BBI = CurMBB;
1771 if (++BBI != CurMBB->getParent()->end())
1774 if (NextMBB == NextBlock)
1777 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1778 DAG.getBasicBlock(NextMBB)));
1783 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1784 // Retrieve successors.
1785 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1786 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1788 if (isa<InlineAsm>(I.getCalledValue()))
1791 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1793 // If the value of the invoke is used outside of its defining block, make it
1794 // available as a virtual register.
1795 if (!I.use_empty()) {
1796 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1797 if (VMI != FuncInfo.ValueMap.end())
1798 CopyValueToVirtualRegister(&I, VMI->second);
1801 // Update successor info
1802 CurMBB->addSuccessor(Return);
1803 CurMBB->addSuccessor(LandingPad);
1805 // Drop into normal successor.
1806 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1807 DAG.getBasicBlock(Return)));
1810 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1813 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1814 /// small case ranges).
1815 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1816 CaseRecVector& WorkList,
1818 MachineBasicBlock* Default) {
1819 Case& BackCase = *(CR.Range.second-1);
1821 // Size is the number of Cases represented by this range.
1822 unsigned Size = CR.Range.second - CR.Range.first;
1826 // Get the MachineFunction which holds the current MBB. This is used when
1827 // inserting any additional MBBs necessary to represent the switch.
1828 MachineFunction *CurMF = CurMBB->getParent();
1830 // Figure out which block is immediately after the current one.
1831 MachineBasicBlock *NextBlock = 0;
1832 MachineFunction::iterator BBI = CR.CaseBB;
1834 if (++BBI != CurMBB->getParent()->end())
1837 // TODO: If any two of the cases has the same destination, and if one value
1838 // is the same as the other, but has one bit unset that the other has set,
1839 // use bit manipulation to do two compares at once. For example:
1840 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1842 // Rearrange the case blocks so that the last one falls through if possible.
1843 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1844 // The last case block won't fall through into 'NextBlock' if we emit the
1845 // branches in this order. See if rearranging a case value would help.
1846 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1847 if (I->BB == NextBlock) {
1848 std::swap(*I, BackCase);
1854 // Create a CaseBlock record representing a conditional branch to
1855 // the Case's target mbb if the value being switched on SV is equal
1857 MachineBasicBlock *CurBlock = CR.CaseBB;
1858 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1859 MachineBasicBlock *FallThrough;
1861 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1862 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1864 // If the last case doesn't match, go to the default block.
1865 FallThrough = Default;
1868 Value *RHS, *LHS, *MHS;
1870 if (I->High == I->Low) {
1871 // This is just small small case range :) containing exactly 1 case
1873 LHS = SV; RHS = I->High; MHS = NULL;
1876 LHS = I->Low; MHS = SV; RHS = I->High;
1878 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1879 I->BB, FallThrough, CurBlock);
1881 // If emitting the first comparison, just call visitSwitchCase to emit the
1882 // code into the current block. Otherwise, push the CaseBlock onto the
1883 // vector to be later processed by SDISel, and insert the node's MBB
1884 // before the next MBB.
1885 if (CurBlock == CurMBB)
1886 visitSwitchCase(CB);
1888 SwitchCases.push_back(CB);
1890 CurBlock = FallThrough;
1896 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1897 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1898 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1901 /// handleJTSwitchCase - Emit jumptable for current switch case range
1902 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1903 CaseRecVector& WorkList,
1905 MachineBasicBlock* Default) {
1906 Case& FrontCase = *CR.Range.first;
1907 Case& BackCase = *(CR.Range.second-1);
1909 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1910 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1913 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1917 if (!areJTsAllowed(TLI) || TSize <= 3)
1920 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1924 DOUT << "Lowering jump table\n"
1925 << "First entry: " << First << ". Last entry: " << Last << "\n"
1926 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1928 // Get the MachineFunction which holds the current MBB. This is used when
1929 // inserting any additional MBBs necessary to represent the switch.
1930 MachineFunction *CurMF = CurMBB->getParent();
1932 // Figure out which block is immediately after the current one.
1933 MachineBasicBlock *NextBlock = 0;
1934 MachineFunction::iterator BBI = CR.CaseBB;
1936 if (++BBI != CurMBB->getParent()->end())
1939 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1941 // Create a new basic block to hold the code for loading the address
1942 // of the jump table, and jumping to it. Update successor information;
1943 // we will either branch to the default case for the switch, or the jump
1945 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1946 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1947 CR.CaseBB->addSuccessor(Default);
1948 CR.CaseBB->addSuccessor(JumpTableBB);
1950 // Build a vector of destination BBs, corresponding to each target
1951 // of the jump table. If the value of the jump table slot corresponds to
1952 // a case statement, push the case's BB onto the vector, otherwise, push
1954 std::vector<MachineBasicBlock*> DestBBs;
1955 int64_t TEI = First;
1956 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1957 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1958 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1960 if ((Low <= TEI) && (TEI <= High)) {
1961 DestBBs.push_back(I->BB);
1965 DestBBs.push_back(Default);
1969 // Update successor info. Add one edge to each unique successor.
1970 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1971 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1972 E = DestBBs.end(); I != E; ++I) {
1973 if (!SuccsHandled[(*I)->getNumber()]) {
1974 SuccsHandled[(*I)->getNumber()] = true;
1975 JumpTableBB->addSuccessor(*I);
1979 // Create a jump table index for this jump table, or return an existing
1981 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1983 // Set the jump table information so that we can codegen it as a second
1984 // MachineBasicBlock
1985 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1986 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1987 (CR.CaseBB == CurMBB));
1988 if (CR.CaseBB == CurMBB)
1989 visitJumpTableHeader(JT, JTH);
1991 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1996 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1998 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1999 CaseRecVector& WorkList,
2001 MachineBasicBlock* Default) {
2002 // Get the MachineFunction which holds the current MBB. This is used when
2003 // inserting any additional MBBs necessary to represent the switch.
2004 MachineFunction *CurMF = CurMBB->getParent();
2006 // Figure out which block is immediately after the current one.
2007 MachineBasicBlock *NextBlock = 0;
2008 MachineFunction::iterator BBI = CR.CaseBB;
2010 if (++BBI != CurMBB->getParent()->end())
2013 Case& FrontCase = *CR.Range.first;
2014 Case& BackCase = *(CR.Range.second-1);
2015 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2017 // Size is the number of Cases represented by this range.
2018 unsigned Size = CR.Range.second - CR.Range.first;
2020 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2021 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
2023 CaseItr Pivot = CR.Range.first + Size/2;
2025 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2026 // (heuristically) allow us to emit JumpTable's later.
2028 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2032 uint64_t LSize = FrontCase.size();
2033 uint64_t RSize = TSize-LSize;
2034 DOUT << "Selecting best pivot: \n"
2035 << "First: " << First << ", Last: " << Last <<"\n"
2036 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
2037 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2039 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2040 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
2041 assert((RBegin-LEnd>=1) && "Invalid case distance");
2042 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2043 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
2044 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
2045 // Should always split in some non-trivial place
2047 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2048 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2049 << "Metric: " << Metric << "\n";
2050 if (FMetric < Metric) {
2053 DOUT << "Current metric set to: " << FMetric << "\n";
2059 if (areJTsAllowed(TLI)) {
2060 // If our case is dense we *really* should handle it earlier!
2061 assert((FMetric > 0) && "Should handle dense range earlier!");
2063 Pivot = CR.Range.first + Size/2;
2066 CaseRange LHSR(CR.Range.first, Pivot);
2067 CaseRange RHSR(Pivot, CR.Range.second);
2068 Constant *C = Pivot->Low;
2069 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2071 // We know that we branch to the LHS if the Value being switched on is
2072 // less than the Pivot value, C. We use this to optimize our binary
2073 // tree a bit, by recognizing that if SV is greater than or equal to the
2074 // LHS's Case Value, and that Case Value is exactly one less than the
2075 // Pivot's Value, then we can branch directly to the LHS's Target,
2076 // rather than creating a leaf node for it.
2077 if ((LHSR.second - LHSR.first) == 1 &&
2078 LHSR.first->High == CR.GE &&
2079 cast<ConstantInt>(C)->getSExtValue() ==
2080 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2081 TrueBB = LHSR.first->BB;
2083 TrueBB = new MachineBasicBlock(LLVMBB);
2084 CurMF->getBasicBlockList().insert(BBI, TrueBB);
2085 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2088 // Similar to the optimization above, if the Value being switched on is
2089 // known to be less than the Constant CR.LT, and the current Case Value
2090 // is CR.LT - 1, then we can branch directly to the target block for
2091 // the current Case Value, rather than emitting a RHS leaf node for it.
2092 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2093 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2094 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2095 FalseBB = RHSR.first->BB;
2097 FalseBB = new MachineBasicBlock(LLVMBB);
2098 CurMF->getBasicBlockList().insert(BBI, FalseBB);
2099 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2102 // Create a CaseBlock record representing a conditional branch to
2103 // the LHS node if the value being switched on SV is less than C.
2104 // Otherwise, branch to LHS.
2105 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
2106 TrueBB, FalseBB, CR.CaseBB);
2108 if (CR.CaseBB == CurMBB)
2109 visitSwitchCase(CB);
2111 SwitchCases.push_back(CB);
2116 /// handleBitTestsSwitchCase - if current case range has few destination and
2117 /// range span less, than machine word bitwidth, encode case range into series
2118 /// of masks and emit bit tests with these masks.
2119 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2120 CaseRecVector& WorkList,
2122 MachineBasicBlock* Default){
2123 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
2125 Case& FrontCase = *CR.Range.first;
2126 Case& BackCase = *(CR.Range.second-1);
2128 // Get the MachineFunction which holds the current MBB. This is used when
2129 // inserting any additional MBBs necessary to represent the switch.
2130 MachineFunction *CurMF = CurMBB->getParent();
2132 unsigned numCmps = 0;
2133 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2135 // Single case counts one, case range - two.
2136 if (I->Low == I->High)
2142 // Count unique destinations
2143 SmallSet<MachineBasicBlock*, 4> Dests;
2144 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2145 Dests.insert(I->BB);
2146 if (Dests.size() > 3)
2147 // Don't bother the code below, if there are too much unique destinations
2150 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2151 << "Total number of comparisons: " << numCmps << "\n";
2153 // Compute span of values.
2154 Constant* minValue = FrontCase.Low;
2155 Constant* maxValue = BackCase.High;
2156 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2157 cast<ConstantInt>(minValue)->getSExtValue();
2158 DOUT << "Compare range: " << range << "\n"
2159 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2160 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2162 if (range>=IntPtrBits ||
2163 (!(Dests.size() == 1 && numCmps >= 3) &&
2164 !(Dests.size() == 2 && numCmps >= 5) &&
2165 !(Dests.size() >= 3 && numCmps >= 6)))
2168 DOUT << "Emitting bit tests\n";
2169 int64_t lowBound = 0;
2171 // Optimize the case where all the case values fit in a
2172 // word without having to subtract minValue. In this case,
2173 // we can optimize away the subtraction.
2174 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2175 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
2176 range = cast<ConstantInt>(maxValue)->getSExtValue();
2178 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2181 CaseBitsVector CasesBits;
2182 unsigned i, count = 0;
2184 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2185 MachineBasicBlock* Dest = I->BB;
2186 for (i = 0; i < count; ++i)
2187 if (Dest == CasesBits[i].BB)
2191 assert((count < 3) && "Too much destinations to test!");
2192 CasesBits.push_back(CaseBits(0, Dest, 0));
2196 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2197 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2199 for (uint64_t j = lo; j <= hi; j++) {
2200 CasesBits[i].Mask |= 1ULL << j;
2201 CasesBits[i].Bits++;
2205 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2207 SelectionDAGISel::BitTestInfo BTC;
2209 // Figure out which block is immediately after the current one.
2210 MachineFunction::iterator BBI = CR.CaseBB;
2213 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2216 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2217 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2218 << ", BB: " << CasesBits[i].BB << "\n";
2220 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2221 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2222 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2227 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2228 -1U, (CR.CaseBB == CurMBB),
2229 CR.CaseBB, Default, BTC);
2231 if (CR.CaseBB == CurMBB)
2232 visitBitTestHeader(BTB);
2234 BitTestCases.push_back(BTB);
2240 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2241 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2242 const SwitchInst& SI) {
2243 unsigned numCmps = 0;
2245 // Start with "simple" cases
2246 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2247 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2248 Cases.push_back(Case(SI.getSuccessorValue(i),
2249 SI.getSuccessorValue(i),
2252 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2254 // Merge case into clusters
2255 if (Cases.size()>=2)
2256 // Must recompute end() each iteration because it may be
2257 // invalidated by erase if we hold on to it
2258 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2259 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2260 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2261 MachineBasicBlock* nextBB = J->BB;
2262 MachineBasicBlock* currentBB = I->BB;
2264 // If the two neighboring cases go to the same destination, merge them
2265 // into a single case.
2266 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2274 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2275 if (I->Low != I->High)
2276 // A range counts double, since it requires two compares.
2283 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2284 // Figure out which block is immediately after the current one.
2285 MachineBasicBlock *NextBlock = 0;
2286 MachineFunction::iterator BBI = CurMBB;
2288 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2290 // If there is only the default destination, branch to it if it is not the
2291 // next basic block. Otherwise, just fall through.
2292 if (SI.getNumOperands() == 2) {
2293 // Update machine-CFG edges.
2295 // If this is not a fall-through branch, emit the branch.
2296 CurMBB->addSuccessor(Default);
2297 if (Default != NextBlock)
2298 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2299 DAG.getBasicBlock(Default)));
2304 // If there are any non-default case statements, create a vector of Cases
2305 // representing each one, and sort the vector so that we can efficiently
2306 // create a binary search tree from them.
2308 unsigned numCmps = Clusterify(Cases, SI);
2309 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2310 << ". Total compares: " << numCmps << "\n";
2312 // Get the Value to be switched on and default basic blocks, which will be
2313 // inserted into CaseBlock records, representing basic blocks in the binary
2315 Value *SV = SI.getOperand(0);
2317 // Push the initial CaseRec onto the worklist
2318 CaseRecVector WorkList;
2319 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2321 while (!WorkList.empty()) {
2322 // Grab a record representing a case range to process off the worklist
2323 CaseRec CR = WorkList.back();
2324 WorkList.pop_back();
2326 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2329 // If the range has few cases (two or less) emit a series of specific
2331 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2334 // If the switch has more than 5 blocks, and at least 40% dense, and the
2335 // target supports indirect branches, then emit a jump table rather than
2336 // lowering the switch to a binary tree of conditional branches.
2337 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2340 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2341 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2342 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2347 void SelectionDAGLowering::visitSub(User &I) {
2348 // -0.0 - X --> fneg
2349 const Type *Ty = I.getType();
2350 if (isa<VectorType>(Ty)) {
2351 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2352 const VectorType *DestTy = cast<VectorType>(I.getType());
2353 const Type *ElTy = DestTy->getElementType();
2354 if (ElTy->isFloatingPoint()) {
2355 unsigned VL = DestTy->getNumElements();
2356 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2357 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2359 SDOperand Op2 = getValue(I.getOperand(1));
2360 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2366 if (Ty->isFloatingPoint()) {
2367 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2368 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2369 SDOperand Op2 = getValue(I.getOperand(1));
2370 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2375 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2378 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2379 SDOperand Op1 = getValue(I.getOperand(0));
2380 SDOperand Op2 = getValue(I.getOperand(1));
2382 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2385 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2386 SDOperand Op1 = getValue(I.getOperand(0));
2387 SDOperand Op2 = getValue(I.getOperand(1));
2389 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2390 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2391 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2392 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2394 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2397 void SelectionDAGLowering::visitICmp(User &I) {
2398 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2399 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2400 predicate = IC->getPredicate();
2401 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2402 predicate = ICmpInst::Predicate(IC->getPredicate());
2403 SDOperand Op1 = getValue(I.getOperand(0));
2404 SDOperand Op2 = getValue(I.getOperand(1));
2405 ISD::CondCode Opcode;
2406 switch (predicate) {
2407 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2408 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2409 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2410 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2411 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2412 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2413 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2414 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2415 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2416 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2418 assert(!"Invalid ICmp predicate value");
2419 Opcode = ISD::SETEQ;
2422 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2425 void SelectionDAGLowering::visitFCmp(User &I) {
2426 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2427 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2428 predicate = FC->getPredicate();
2429 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2430 predicate = FCmpInst::Predicate(FC->getPredicate());
2431 SDOperand Op1 = getValue(I.getOperand(0));
2432 SDOperand Op2 = getValue(I.getOperand(1));
2433 ISD::CondCode Condition, FOC, FPC;
2434 switch (predicate) {
2435 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2436 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2437 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2438 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2439 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2440 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2441 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2442 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2443 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2444 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2445 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2446 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2447 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2448 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2449 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2450 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2452 assert(!"Invalid FCmp predicate value");
2453 FOC = FPC = ISD::SETFALSE;
2456 if (FiniteOnlyFPMath())
2460 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2463 void SelectionDAGLowering::visitVICmp(User &I) {
2464 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2465 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2466 predicate = IC->getPredicate();
2467 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2468 predicate = ICmpInst::Predicate(IC->getPredicate());
2469 SDOperand Op1 = getValue(I.getOperand(0));
2470 SDOperand Op2 = getValue(I.getOperand(1));
2471 ISD::CondCode Opcode;
2472 switch (predicate) {
2473 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2474 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2475 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2476 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2477 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2478 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2479 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2480 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2481 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2482 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2484 assert(!"Invalid ICmp predicate value");
2485 Opcode = ISD::SETEQ;
2488 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2491 void SelectionDAGLowering::visitVFCmp(User &I) {
2492 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2493 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2494 predicate = FC->getPredicate();
2495 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2496 predicate = FCmpInst::Predicate(FC->getPredicate());
2497 SDOperand Op1 = getValue(I.getOperand(0));
2498 SDOperand Op2 = getValue(I.getOperand(1));
2499 ISD::CondCode Condition, FOC, FPC;
2500 switch (predicate) {
2501 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2502 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2503 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2504 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2505 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2506 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2507 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2508 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2509 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2510 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2511 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2512 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2513 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2514 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2515 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2516 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2518 assert(!"Invalid VFCmp predicate value");
2519 FOC = FPC = ISD::SETFALSE;
2522 if (FiniteOnlyFPMath())
2527 MVT DestVT = TLI.getValueType(I.getType());
2529 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2532 void SelectionDAGLowering::visitSelect(User &I) {
2533 SDOperand Cond = getValue(I.getOperand(0));
2534 SDOperand TrueVal = getValue(I.getOperand(1));
2535 SDOperand FalseVal = getValue(I.getOperand(2));
2536 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2537 TrueVal, FalseVal));
2541 void SelectionDAGLowering::visitTrunc(User &I) {
2542 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2543 SDOperand N = getValue(I.getOperand(0));
2544 MVT DestVT = TLI.getValueType(I.getType());
2545 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2548 void SelectionDAGLowering::visitZExt(User &I) {
2549 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2550 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2551 SDOperand N = getValue(I.getOperand(0));
2552 MVT DestVT = TLI.getValueType(I.getType());
2553 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2556 void SelectionDAGLowering::visitSExt(User &I) {
2557 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2558 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2559 SDOperand N = getValue(I.getOperand(0));
2560 MVT DestVT = TLI.getValueType(I.getType());
2561 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2564 void SelectionDAGLowering::visitFPTrunc(User &I) {
2565 // FPTrunc is never a no-op cast, no need to check
2566 SDOperand N = getValue(I.getOperand(0));
2567 MVT DestVT = TLI.getValueType(I.getType());
2568 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2571 void SelectionDAGLowering::visitFPExt(User &I){
2572 // FPTrunc is never a no-op cast, no need to check
2573 SDOperand N = getValue(I.getOperand(0));
2574 MVT DestVT = TLI.getValueType(I.getType());
2575 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2578 void SelectionDAGLowering::visitFPToUI(User &I) {
2579 // FPToUI is never a no-op cast, no need to check
2580 SDOperand N = getValue(I.getOperand(0));
2581 MVT DestVT = TLI.getValueType(I.getType());
2582 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2585 void SelectionDAGLowering::visitFPToSI(User &I) {
2586 // FPToSI is never a no-op cast, no need to check
2587 SDOperand N = getValue(I.getOperand(0));
2588 MVT DestVT = TLI.getValueType(I.getType());
2589 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2592 void SelectionDAGLowering::visitUIToFP(User &I) {
2593 // UIToFP is never a no-op cast, no need to check
2594 SDOperand N = getValue(I.getOperand(0));
2595 MVT DestVT = TLI.getValueType(I.getType());
2596 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2599 void SelectionDAGLowering::visitSIToFP(User &I){
2600 // UIToFP is never a no-op cast, no need to check
2601 SDOperand N = getValue(I.getOperand(0));
2602 MVT DestVT = TLI.getValueType(I.getType());
2603 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2606 void SelectionDAGLowering::visitPtrToInt(User &I) {
2607 // What to do depends on the size of the integer and the size of the pointer.
2608 // We can either truncate, zero extend, or no-op, accordingly.
2609 SDOperand N = getValue(I.getOperand(0));
2610 MVT SrcVT = N.getValueType();
2611 MVT DestVT = TLI.getValueType(I.getType());
2613 if (DestVT.bitsLT(SrcVT))
2614 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2616 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2617 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2618 setValue(&I, Result);
2621 void SelectionDAGLowering::visitIntToPtr(User &I) {
2622 // What to do depends on the size of the integer and the size of the pointer.
2623 // We can either truncate, zero extend, or no-op, accordingly.
2624 SDOperand N = getValue(I.getOperand(0));
2625 MVT SrcVT = N.getValueType();
2626 MVT DestVT = TLI.getValueType(I.getType());
2627 if (DestVT.bitsLT(SrcVT))
2628 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2630 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2631 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2634 void SelectionDAGLowering::visitBitCast(User &I) {
2635 SDOperand N = getValue(I.getOperand(0));
2636 MVT DestVT = TLI.getValueType(I.getType());
2638 // BitCast assures us that source and destination are the same size so this
2639 // is either a BIT_CONVERT or a no-op.
2640 if (DestVT != N.getValueType())
2641 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2643 setValue(&I, N); // noop cast.
2646 void SelectionDAGLowering::visitInsertElement(User &I) {
2647 SDOperand InVec = getValue(I.getOperand(0));
2648 SDOperand InVal = getValue(I.getOperand(1));
2649 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2650 getValue(I.getOperand(2)));
2652 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2653 TLI.getValueType(I.getType()),
2654 InVec, InVal, InIdx));
2657 void SelectionDAGLowering::visitExtractElement(User &I) {
2658 SDOperand InVec = getValue(I.getOperand(0));
2659 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2660 getValue(I.getOperand(1)));
2661 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2662 TLI.getValueType(I.getType()), InVec, InIdx));
2665 void SelectionDAGLowering::visitShuffleVector(User &I) {
2666 SDOperand V1 = getValue(I.getOperand(0));
2667 SDOperand V2 = getValue(I.getOperand(1));
2668 SDOperand Mask = getValue(I.getOperand(2));
2670 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2671 TLI.getValueType(I.getType()),
2675 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2676 const Value *Op0 = I.getOperand(0);
2677 const Value *Op1 = I.getOperand(1);
2678 const Type *AggTy = I.getType();
2679 const Type *ValTy = Op1->getType();
2680 bool IntoUndef = isa<UndefValue>(Op0);
2681 bool FromUndef = isa<UndefValue>(Op1);
2683 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2684 I.idx_begin(), I.idx_end());
2686 SmallVector<MVT, 4> AggValueVTs;
2687 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2688 SmallVector<MVT, 4> ValValueVTs;
2689 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2691 unsigned NumAggValues = AggValueVTs.size();
2692 unsigned NumValValues = ValValueVTs.size();
2693 SmallVector<SDOperand, 4> Values(NumAggValues);
2695 SDOperand Agg = getValue(Op0);
2696 SDOperand Val = getValue(Op1);
2698 // Copy the beginning value(s) from the original aggregate.
2699 for (; i != LinearIndex; ++i)
2700 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2701 SDOperand(Agg.Val, Agg.ResNo + i);
2702 // Copy values from the inserted value(s).
2703 for (; i != LinearIndex + NumValValues; ++i)
2704 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2705 SDOperand(Val.Val, Val.ResNo + i - LinearIndex);
2706 // Copy remaining value(s) from the original aggregate.
2707 for (; i != NumAggValues; ++i)
2708 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2709 SDOperand(Agg.Val, Agg.ResNo + i);
2711 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2712 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2713 &Values[0], NumAggValues));
2716 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2717 const Value *Op0 = I.getOperand(0);
2718 const Type *AggTy = Op0->getType();
2719 const Type *ValTy = I.getType();
2720 bool OutOfUndef = isa<UndefValue>(Op0);
2722 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2723 I.idx_begin(), I.idx_end());
2725 SmallVector<MVT, 4> ValValueVTs;
2726 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2728 unsigned NumValValues = ValValueVTs.size();
2729 SmallVector<SDOperand, 4> Values(NumValValues);
2731 SDOperand Agg = getValue(Op0);
2732 // Copy out the selected value(s).
2733 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2734 Values[i - LinearIndex] =
2735 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(i)) :
2736 SDOperand(Agg.Val, Agg.ResNo + i - LinearIndex);
2738 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2739 DAG.getVTList(&ValValueVTs[0], NumValValues),
2740 &Values[0], NumValValues));
2744 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2745 SDOperand N = getValue(I.getOperand(0));
2746 const Type *Ty = I.getOperand(0)->getType();
2748 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2751 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2752 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2755 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2756 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2757 DAG.getIntPtrConstant(Offset));
2759 Ty = StTy->getElementType(Field);
2761 Ty = cast<SequentialType>(Ty)->getElementType();
2763 // If this is a constant subscript, handle it quickly.
2764 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2765 if (CI->getZExtValue() == 0) continue;
2767 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2768 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2769 DAG.getIntPtrConstant(Offs));
2773 // N = N + Idx * ElementSize;
2774 uint64_t ElementSize = TD->getABITypeSize(Ty);
2775 SDOperand IdxN = getValue(Idx);
2777 // If the index is smaller or larger than intptr_t, truncate or extend
2779 if (IdxN.getValueType().bitsLT(N.getValueType())) {
2780 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2781 } else if (IdxN.getValueType().bitsGT(N.getValueType()))
2782 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2784 // If this is a multiply by a power of two, turn it into a shl
2785 // immediately. This is a very common case.
2786 if (isPowerOf2_64(ElementSize)) {
2787 unsigned Amt = Log2_64(ElementSize);
2788 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2789 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2790 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2794 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
2795 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2796 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2802 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2803 // If this is a fixed sized alloca in the entry block of the function,
2804 // allocate it statically on the stack.
2805 if (FuncInfo.StaticAllocaMap.count(&I))
2806 return; // getValue will auto-populate this.
2808 const Type *Ty = I.getAllocatedType();
2809 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2811 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2814 SDOperand AllocSize = getValue(I.getArraySize());
2815 MVT IntPtr = TLI.getPointerTy();
2816 if (IntPtr.bitsLT(AllocSize.getValueType()))
2817 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2818 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2819 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2821 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2822 DAG.getIntPtrConstant(TySize));
2824 // Handle alignment. If the requested alignment is less than or equal to
2825 // the stack alignment, ignore it. If the size is greater than or equal to
2826 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2827 unsigned StackAlign =
2828 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2829 if (Align <= StackAlign)
2832 // Round the size of the allocation up to the stack alignment size
2833 // by add SA-1 to the size.
2834 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2835 DAG.getIntPtrConstant(StackAlign-1));
2836 // Mask out the low bits for alignment purposes.
2837 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2838 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2840 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2841 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2843 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2845 DAG.setRoot(DSA.getValue(1));
2847 // Inform the Frame Information that we have just allocated a variable-sized
2849 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2852 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2853 const Value *SV = I.getOperand(0);
2854 SDOperand Ptr = getValue(SV);
2856 const Type *Ty = I.getType();
2857 bool isVolatile = I.isVolatile();
2858 unsigned Alignment = I.getAlignment();
2860 SmallVector<MVT, 4> ValueVTs;
2861 SmallVector<uint64_t, 4> Offsets;
2862 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2863 unsigned NumValues = ValueVTs.size();
2871 // Do not serialize non-volatile loads against each other.
2872 Root = DAG.getRoot();
2875 SmallVector<SDOperand, 4> Values(NumValues);
2876 SmallVector<SDOperand, 4> Chains(NumValues);
2877 MVT PtrVT = Ptr.getValueType();
2878 for (unsigned i = 0; i != NumValues; ++i) {
2879 SDOperand L = DAG.getLoad(ValueVTs[i], Root,
2880 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2881 DAG.getConstant(Offsets[i], PtrVT)),
2883 isVolatile, Alignment);
2885 Chains[i] = L.getValue(1);
2888 SDOperand Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2889 &Chains[0], NumValues);
2893 PendingLoads.push_back(Chain);
2895 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2896 DAG.getVTList(&ValueVTs[0], NumValues),
2897 &Values[0], NumValues));
2901 void SelectionDAGLowering::visitStore(StoreInst &I) {
2902 Value *SrcV = I.getOperand(0);
2903 SDOperand Src = getValue(SrcV);
2904 Value *PtrV = I.getOperand(1);
2905 SDOperand Ptr = getValue(PtrV);
2907 SmallVector<MVT, 4> ValueVTs;
2908 SmallVector<uint64_t, 4> Offsets;
2909 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2910 unsigned NumValues = ValueVTs.size();
2914 SDOperand Root = getRoot();
2915 SmallVector<SDOperand, 4> Chains(NumValues);
2916 MVT PtrVT = Ptr.getValueType();
2917 bool isVolatile = I.isVolatile();
2918 unsigned Alignment = I.getAlignment();
2919 for (unsigned i = 0; i != NumValues; ++i)
2920 Chains[i] = DAG.getStore(Root, SDOperand(Src.Val, Src.ResNo + i),
2921 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2922 DAG.getConstant(Offsets[i], PtrVT)),
2924 isVolatile, Alignment);
2926 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2929 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2931 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2932 unsigned Intrinsic) {
2933 bool HasChain = !I.doesNotAccessMemory();
2934 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2936 // Build the operand list.
2937 SmallVector<SDOperand, 8> Ops;
2938 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2940 // We don't need to serialize loads against other loads.
2941 Ops.push_back(DAG.getRoot());
2943 Ops.push_back(getRoot());
2947 // Add the intrinsic ID as an integer operand.
2948 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2950 // Add all operands of the call to the operand list.
2951 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2952 SDOperand Op = getValue(I.getOperand(i));
2953 assert(TLI.isTypeLegal(Op.getValueType()) &&
2954 "Intrinsic uses a non-legal type?");
2958 std::vector<MVT> VTs;
2959 if (I.getType() != Type::VoidTy) {
2960 MVT VT = TLI.getValueType(I.getType());
2961 if (VT.isVector()) {
2962 const VectorType *DestTy = cast<VectorType>(I.getType());
2963 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2965 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2966 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2969 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2973 VTs.push_back(MVT::Other);
2975 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2980 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2981 &Ops[0], Ops.size());
2982 else if (I.getType() != Type::VoidTy)
2983 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2984 &Ops[0], Ops.size());
2986 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2987 &Ops[0], Ops.size());
2990 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2992 PendingLoads.push_back(Chain);
2996 if (I.getType() != Type::VoidTy) {
2997 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2998 MVT VT = TLI.getValueType(PTy);
2999 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
3001 setValue(&I, Result);
3005 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3006 static GlobalVariable *ExtractTypeInfo (Value *V) {
3007 V = V->stripPointerCasts();
3008 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3009 assert ((GV || isa<ConstantPointerNull>(V)) &&
3010 "TypeInfo must be a global variable or NULL");
3014 /// addCatchInfo - Extract the personality and type infos from an eh.selector
3015 /// call, and add them to the specified machine basic block.
3016 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3017 MachineBasicBlock *MBB) {
3018 // Inform the MachineModuleInfo of the personality for this landing pad.
3019 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3020 assert(CE->getOpcode() == Instruction::BitCast &&
3021 isa<Function>(CE->getOperand(0)) &&
3022 "Personality should be a function");
3023 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3025 // Gather all the type infos for this landing pad and pass them along to
3026 // MachineModuleInfo.
3027 std::vector<GlobalVariable *> TyInfo;
3028 unsigned N = I.getNumOperands();
3030 for (unsigned i = N - 1; i > 2; --i) {
3031 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3032 unsigned FilterLength = CI->getZExtValue();
3033 unsigned FirstCatch = i + FilterLength + !FilterLength;
3034 assert (FirstCatch <= N && "Invalid filter length");
3036 if (FirstCatch < N) {
3037 TyInfo.reserve(N - FirstCatch);
3038 for (unsigned j = FirstCatch; j < N; ++j)
3039 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3040 MMI->addCatchTypeInfo(MBB, TyInfo);
3044 if (!FilterLength) {
3046 MMI->addCleanup(MBB);
3049 TyInfo.reserve(FilterLength - 1);
3050 for (unsigned j = i + 1; j < FirstCatch; ++j)
3051 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3052 MMI->addFilterTypeInfo(MBB, TyInfo);
3061 TyInfo.reserve(N - 3);
3062 for (unsigned j = 3; j < N; ++j)
3063 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3064 MMI->addCatchTypeInfo(MBB, TyInfo);
3069 /// Inlined utility function to implement binary input atomic intrinsics for
3070 // visitIntrinsicCall: I is a call instruction
3071 // Op is the associated NodeType for I
3073 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3074 SDOperand Root = getRoot();
3075 SDOperand O2 = getValue(I.getOperand(2));
3076 SDOperand L = DAG.getAtomic(Op, Root,
3077 getValue(I.getOperand(1)),
3078 O2, O2.getValueType());
3080 DAG.setRoot(L.getValue(1));
3084 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3085 /// we want to emit this as a call to a named external function, return the name
3086 /// otherwise lower it and return null.
3088 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3089 switch (Intrinsic) {
3091 // By default, turn this into a target intrinsic node.
3092 visitTargetIntrinsic(I, Intrinsic);
3094 case Intrinsic::vastart: visitVAStart(I); return 0;
3095 case Intrinsic::vaend: visitVAEnd(I); return 0;
3096 case Intrinsic::vacopy: visitVACopy(I); return 0;
3097 case Intrinsic::returnaddress:
3098 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3099 getValue(I.getOperand(1))));
3101 case Intrinsic::frameaddress:
3102 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3103 getValue(I.getOperand(1))));
3105 case Intrinsic::setjmp:
3106 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3108 case Intrinsic::longjmp:
3109 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3111 case Intrinsic::memcpy_i32:
3112 case Intrinsic::memcpy_i64: {
3113 SDOperand Op1 = getValue(I.getOperand(1));
3114 SDOperand Op2 = getValue(I.getOperand(2));
3115 SDOperand Op3 = getValue(I.getOperand(3));
3116 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3117 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3118 I.getOperand(1), 0, I.getOperand(2), 0));
3121 case Intrinsic::memset_i32:
3122 case Intrinsic::memset_i64: {
3123 SDOperand Op1 = getValue(I.getOperand(1));
3124 SDOperand Op2 = getValue(I.getOperand(2));
3125 SDOperand Op3 = getValue(I.getOperand(3));
3126 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3127 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3128 I.getOperand(1), 0));
3131 case Intrinsic::memmove_i32:
3132 case Intrinsic::memmove_i64: {
3133 SDOperand Op1 = getValue(I.getOperand(1));
3134 SDOperand Op2 = getValue(I.getOperand(2));
3135 SDOperand Op3 = getValue(I.getOperand(3));
3136 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3138 // If the source and destination are known to not be aliases, we can
3139 // lower memmove as memcpy.
3140 uint64_t Size = -1ULL;
3141 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3142 Size = C->getValue();
3143 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3144 AliasAnalysis::NoAlias) {
3145 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3146 I.getOperand(1), 0, I.getOperand(2), 0));
3150 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3151 I.getOperand(1), 0, I.getOperand(2), 0));
3154 case Intrinsic::dbg_stoppoint: {
3155 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3156 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3157 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3161 Ops[1] = getValue(SPI.getLineValue());
3162 Ops[2] = getValue(SPI.getColumnValue());
3164 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3165 assert(DD && "Not a debug information descriptor");
3166 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
3168 Ops[3] = DAG.getString(CompileUnit->getFileName());
3169 Ops[4] = DAG.getString(CompileUnit->getDirectory());
3171 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
3176 case Intrinsic::dbg_region_start: {
3177 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3178 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3179 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3180 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3181 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3182 DAG.getConstant(LabelID, MVT::i32),
3183 DAG.getConstant(0, MVT::i32)));
3188 case Intrinsic::dbg_region_end: {
3189 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3190 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3191 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3192 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3193 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3194 DAG.getConstant(LabelID, MVT::i32),
3195 DAG.getConstant(0, MVT::i32)));
3200 case Intrinsic::dbg_func_start: {
3201 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3203 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3204 Value *SP = FSI.getSubprogram();
3205 if (SP && MMI->Verify(SP)) {
3206 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3207 // what (most?) gdb expects.
3208 DebugInfoDesc *DD = MMI->getDescFor(SP);
3209 assert(DD && "Not a debug information descriptor");
3210 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3211 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3212 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
3213 CompileUnit->getFileName());
3214 // Record the source line but does create a label. It will be emitted
3215 // at asm emission time.
3216 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3221 case Intrinsic::dbg_declare: {
3222 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3223 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3224 Value *Variable = DI.getVariable();
3225 if (MMI && Variable && MMI->Verify(Variable))
3226 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3227 getValue(DI.getAddress()), getValue(Variable)));
3231 case Intrinsic::eh_exception: {
3232 if (!CurMBB->isLandingPad()) {
3233 // FIXME: Mark exception register as live in. Hack for PR1508.
3234 unsigned Reg = TLI.getExceptionAddressRegister();
3235 if (Reg) CurMBB->addLiveIn(Reg);
3237 // Insert the EXCEPTIONADDR instruction.
3238 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3240 Ops[0] = DAG.getRoot();
3241 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3243 DAG.setRoot(Op.getValue(1));
3247 case Intrinsic::eh_selector_i32:
3248 case Intrinsic::eh_selector_i64: {
3249 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3250 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3251 MVT::i32 : MVT::i64);
3254 if (CurMBB->isLandingPad())
3255 addCatchInfo(I, MMI, CurMBB);
3258 FuncInfo.CatchInfoLost.insert(&I);
3260 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3261 unsigned Reg = TLI.getExceptionSelectorRegister();
3262 if (Reg) CurMBB->addLiveIn(Reg);
3265 // Insert the EHSELECTION instruction.
3266 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3268 Ops[0] = getValue(I.getOperand(1));
3270 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3272 DAG.setRoot(Op.getValue(1));
3274 setValue(&I, DAG.getConstant(0, VT));
3280 case Intrinsic::eh_typeid_for_i32:
3281 case Intrinsic::eh_typeid_for_i64: {
3282 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3283 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3284 MVT::i32 : MVT::i64);
3287 // Find the type id for the given typeinfo.
3288 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3290 unsigned TypeID = MMI->getTypeIDFor(GV);
3291 setValue(&I, DAG.getConstant(TypeID, VT));
3293 // Return something different to eh_selector.
3294 setValue(&I, DAG.getConstant(1, VT));
3300 case Intrinsic::eh_return: {
3301 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3304 MMI->setCallsEHReturn(true);
3305 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3308 getValue(I.getOperand(1)),
3309 getValue(I.getOperand(2))));
3311 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3317 case Intrinsic::eh_unwind_init: {
3318 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3319 MMI->setCallsUnwindInit(true);
3325 case Intrinsic::eh_dwarf_cfa: {
3326 MVT VT = getValue(I.getOperand(1)).getValueType();
3328 if (VT.bitsGT(TLI.getPointerTy()))
3329 CfaArg = DAG.getNode(ISD::TRUNCATE,
3330 TLI.getPointerTy(), getValue(I.getOperand(1)));
3332 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3333 TLI.getPointerTy(), getValue(I.getOperand(1)));
3335 SDOperand Offset = DAG.getNode(ISD::ADD,
3337 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3338 TLI.getPointerTy()),
3340 setValue(&I, DAG.getNode(ISD::ADD,
3342 DAG.getNode(ISD::FRAMEADDR,
3345 TLI.getPointerTy())),
3350 case Intrinsic::sqrt:
3351 setValue(&I, DAG.getNode(ISD::FSQRT,
3352 getValue(I.getOperand(1)).getValueType(),
3353 getValue(I.getOperand(1))));
3355 case Intrinsic::powi:
3356 setValue(&I, DAG.getNode(ISD::FPOWI,
3357 getValue(I.getOperand(1)).getValueType(),
3358 getValue(I.getOperand(1)),
3359 getValue(I.getOperand(2))));
3361 case Intrinsic::sin:
3362 setValue(&I, DAG.getNode(ISD::FSIN,
3363 getValue(I.getOperand(1)).getValueType(),
3364 getValue(I.getOperand(1))));
3366 case Intrinsic::cos:
3367 setValue(&I, DAG.getNode(ISD::FCOS,
3368 getValue(I.getOperand(1)).getValueType(),
3369 getValue(I.getOperand(1))));
3371 case Intrinsic::pow:
3372 setValue(&I, DAG.getNode(ISD::FPOW,
3373 getValue(I.getOperand(1)).getValueType(),
3374 getValue(I.getOperand(1)),
3375 getValue(I.getOperand(2))));
3377 case Intrinsic::pcmarker: {
3378 SDOperand Tmp = getValue(I.getOperand(1));
3379 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3382 case Intrinsic::readcyclecounter: {
3383 SDOperand Op = getRoot();
3384 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3385 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3388 DAG.setRoot(Tmp.getValue(1));
3391 case Intrinsic::part_select: {
3392 // Currently not implemented: just abort
3393 assert(0 && "part_select intrinsic not implemented");
3396 case Intrinsic::part_set: {
3397 // Currently not implemented: just abort
3398 assert(0 && "part_set intrinsic not implemented");
3401 case Intrinsic::bswap:
3402 setValue(&I, DAG.getNode(ISD::BSWAP,
3403 getValue(I.getOperand(1)).getValueType(),
3404 getValue(I.getOperand(1))));
3406 case Intrinsic::cttz: {
3407 SDOperand Arg = getValue(I.getOperand(1));
3408 MVT Ty = Arg.getValueType();
3409 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3410 setValue(&I, result);
3413 case Intrinsic::ctlz: {
3414 SDOperand Arg = getValue(I.getOperand(1));
3415 MVT Ty = Arg.getValueType();
3416 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3417 setValue(&I, result);
3420 case Intrinsic::ctpop: {
3421 SDOperand Arg = getValue(I.getOperand(1));
3422 MVT Ty = Arg.getValueType();
3423 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3424 setValue(&I, result);
3427 case Intrinsic::stacksave: {
3428 SDOperand Op = getRoot();
3429 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3430 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3432 DAG.setRoot(Tmp.getValue(1));
3435 case Intrinsic::stackrestore: {
3436 SDOperand Tmp = getValue(I.getOperand(1));
3437 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3440 case Intrinsic::var_annotation:
3441 // Discard annotate attributes
3444 case Intrinsic::init_trampoline: {
3445 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3449 Ops[1] = getValue(I.getOperand(1));
3450 Ops[2] = getValue(I.getOperand(2));
3451 Ops[3] = getValue(I.getOperand(3));
3452 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3453 Ops[5] = DAG.getSrcValue(F);
3455 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3456 DAG.getNodeValueTypes(TLI.getPointerTy(),
3461 DAG.setRoot(Tmp.getValue(1));
3465 case Intrinsic::gcroot:
3467 Value *Alloca = I.getOperand(1);
3468 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3470 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3471 GCI->addStackRoot(FI->getIndex(), TypeMap);
3475 case Intrinsic::gcread:
3476 case Intrinsic::gcwrite:
3477 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3480 case Intrinsic::flt_rounds: {
3481 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3485 case Intrinsic::trap: {
3486 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3489 case Intrinsic::prefetch: {
3492 Ops[1] = getValue(I.getOperand(1));
3493 Ops[2] = getValue(I.getOperand(2));
3494 Ops[3] = getValue(I.getOperand(3));
3495 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3499 case Intrinsic::memory_barrier: {
3502 for (int x = 1; x < 6; ++x)
3503 Ops[x] = getValue(I.getOperand(x));
3505 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3508 case Intrinsic::atomic_lcs: {
3509 SDOperand Root = getRoot();
3510 SDOperand O3 = getValue(I.getOperand(3));
3511 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3512 getValue(I.getOperand(1)),
3513 getValue(I.getOperand(2)),
3514 O3, O3.getValueType());
3516 DAG.setRoot(L.getValue(1));
3519 case Intrinsic::atomic_las:
3520 return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3521 case Intrinsic::atomic_lss:
3522 return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3523 case Intrinsic::atomic_load_and:
3524 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3525 case Intrinsic::atomic_load_or:
3526 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3527 case Intrinsic::atomic_load_xor:
3528 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3529 case Intrinsic::atomic_load_nand:
3530 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
3531 case Intrinsic::atomic_load_min:
3532 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3533 case Intrinsic::atomic_load_max:
3534 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3535 case Intrinsic::atomic_load_umin:
3536 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3537 case Intrinsic::atomic_load_umax:
3538 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3539 case Intrinsic::atomic_swap:
3540 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
3545 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
3547 MachineBasicBlock *LandingPad) {
3548 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3549 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3550 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3551 unsigned BeginLabel = 0, EndLabel = 0;
3553 TargetLowering::ArgListTy Args;
3554 TargetLowering::ArgListEntry Entry;
3555 Args.reserve(CS.arg_size());
3556 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3558 SDOperand ArgNode = getValue(*i);
3559 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3561 unsigned attrInd = i - CS.arg_begin() + 1;
3562 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3563 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3564 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3565 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3566 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3567 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3568 Entry.Alignment = CS.getParamAlignment(attrInd);
3569 Args.push_back(Entry);
3572 if (LandingPad && MMI) {
3573 // Insert a label before the invoke call to mark the try range. This can be
3574 // used to detect deletion of the invoke via the MachineModuleInfo.
3575 BeginLabel = MMI->NextLabelID();
3576 // Both PendingLoads and PendingExports must be flushed here;
3577 // this call might not return.
3579 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
3580 DAG.getConstant(BeginLabel, MVT::i32),
3581 DAG.getConstant(1, MVT::i32)));
3584 std::pair<SDOperand,SDOperand> Result =
3585 TLI.LowerCallTo(getRoot(), CS.getType(),
3586 CS.paramHasAttr(0, ParamAttr::SExt),
3587 CS.paramHasAttr(0, ParamAttr::ZExt),
3588 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3590 if (CS.getType() != Type::VoidTy)
3591 setValue(CS.getInstruction(), Result.first);
3592 DAG.setRoot(Result.second);
3594 if (LandingPad && MMI) {
3595 // Insert a label at the end of the invoke call to mark the try range. This
3596 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3597 EndLabel = MMI->NextLabelID();
3598 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3599 DAG.getConstant(EndLabel, MVT::i32),
3600 DAG.getConstant(1, MVT::i32)));
3602 // Inform MachineModuleInfo of range.
3603 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3608 void SelectionDAGLowering::visitCall(CallInst &I) {
3609 const char *RenameFn = 0;
3610 if (Function *F = I.getCalledFunction()) {
3611 if (F->isDeclaration()) {
3612 if (unsigned IID = F->getIntrinsicID()) {
3613 RenameFn = visitIntrinsicCall(I, IID);
3619 // Check for well-known libc/libm calls. If the function is internal, it
3620 // can't be a library call.
3621 unsigned NameLen = F->getNameLen();
3622 if (!F->hasInternalLinkage() && NameLen) {
3623 const char *NameStr = F->getNameStart();
3624 if (NameStr[0] == 'c' &&
3625 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3626 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3627 if (I.getNumOperands() == 3 && // Basic sanity checks.
3628 I.getOperand(1)->getType()->isFloatingPoint() &&
3629 I.getType() == I.getOperand(1)->getType() &&
3630 I.getType() == I.getOperand(2)->getType()) {
3631 SDOperand LHS = getValue(I.getOperand(1));
3632 SDOperand RHS = getValue(I.getOperand(2));
3633 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3637 } else if (NameStr[0] == 'f' &&
3638 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3639 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3640 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3641 if (I.getNumOperands() == 2 && // Basic sanity checks.
3642 I.getOperand(1)->getType()->isFloatingPoint() &&
3643 I.getType() == I.getOperand(1)->getType()) {
3644 SDOperand Tmp = getValue(I.getOperand(1));
3645 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3648 } else if (NameStr[0] == 's' &&
3649 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3650 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3651 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3652 if (I.getNumOperands() == 2 && // Basic sanity checks.
3653 I.getOperand(1)->getType()->isFloatingPoint() &&
3654 I.getType() == I.getOperand(1)->getType()) {
3655 SDOperand Tmp = getValue(I.getOperand(1));
3656 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3659 } else if (NameStr[0] == 'c' &&
3660 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3661 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3662 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3663 if (I.getNumOperands() == 2 && // Basic sanity checks.
3664 I.getOperand(1)->getType()->isFloatingPoint() &&
3665 I.getType() == I.getOperand(1)->getType()) {
3666 SDOperand Tmp = getValue(I.getOperand(1));
3667 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3672 } else if (isa<InlineAsm>(I.getOperand(0))) {
3679 Callee = getValue(I.getOperand(0));
3681 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3683 LowerCallTo(&I, Callee, I.isTailCall());
3687 void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3688 if (isa<UndefValue>(I.getOperand(0))) {
3689 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3690 setValue(&I, Undef);
3694 // To add support for individual return values with aggregate types,
3695 // we'd need a way to take a getresult index and determine which
3696 // values of the Call SDNode are associated with it.
3697 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3698 "Individual return values must not be aggregates!");
3700 SDOperand Call = getValue(I.getOperand(0));
3701 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3705 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3706 /// this value and returns the result as a ValueVT value. This uses
3707 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3708 /// If the Flag pointer is NULL, no flag is used.
3709 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3711 SDOperand *Flag) const {
3712 // Assemble the legal parts into the final values.
3713 SmallVector<SDOperand, 4> Values(ValueVTs.size());
3714 SmallVector<SDOperand, 8> Parts;
3715 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3716 // Copy the legal parts from the registers.
3717 MVT ValueVT = ValueVTs[Value];
3718 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3719 MVT RegisterVT = RegVTs[Value];
3721 Parts.resize(NumRegs);
3722 for (unsigned i = 0; i != NumRegs; ++i) {
3725 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3727 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3728 *Flag = P.getValue(2);
3730 Chain = P.getValue(1);
3734 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3739 if (ValueVTs.size() == 1)
3742 return DAG.getNode(ISD::MERGE_VALUES,
3743 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3744 &Values[0], ValueVTs.size());
3747 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3748 /// specified value into the registers specified by this object. This uses
3749 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3750 /// If the Flag pointer is NULL, no flag is used.
3751 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3752 SDOperand &Chain, SDOperand *Flag) const {
3753 // Get the list of the values's legal parts.
3754 unsigned NumRegs = Regs.size();
3755 SmallVector<SDOperand, 8> Parts(NumRegs);
3756 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3757 MVT ValueVT = ValueVTs[Value];
3758 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3759 MVT RegisterVT = RegVTs[Value];
3761 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3762 &Parts[Part], NumParts, RegisterVT);
3766 // Copy the parts into the registers.
3767 SmallVector<SDOperand, 8> Chains(NumRegs);
3768 for (unsigned i = 0; i != NumRegs; ++i) {
3771 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3773 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3774 *Flag = Part.getValue(1);
3776 Chains[i] = Part.getValue(0);
3779 if (NumRegs == 1 || Flag)
3780 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3781 // flagged to it. That is the CopyToReg nodes and the user are considered
3782 // a single scheduling unit. If we create a TokenFactor and return it as
3783 // chain, then the TokenFactor is both a predecessor (operand) of the
3784 // user as well as a successor (the TF operands are flagged to the user).
3785 // c1, f1 = CopyToReg
3786 // c2, f2 = CopyToReg
3787 // c3 = TokenFactor c1, c2
3790 Chain = Chains[NumRegs-1];
3792 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3795 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3796 /// operand list. This adds the code marker and includes the number of
3797 /// values added into it.
3798 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3799 std::vector<SDOperand> &Ops) const {
3800 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3801 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3802 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3803 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3804 MVT RegisterVT = RegVTs[Value];
3805 for (unsigned i = 0; i != NumRegs; ++i)
3806 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3810 /// isAllocatableRegister - If the specified register is safe to allocate,
3811 /// i.e. it isn't a stack pointer or some other special register, return the
3812 /// register class for the register. Otherwise, return null.
3813 static const TargetRegisterClass *
3814 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3815 const TargetLowering &TLI,
3816 const TargetRegisterInfo *TRI) {
3817 MVT FoundVT = MVT::Other;
3818 const TargetRegisterClass *FoundRC = 0;
3819 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3820 E = TRI->regclass_end(); RCI != E; ++RCI) {
3821 MVT ThisVT = MVT::Other;
3823 const TargetRegisterClass *RC = *RCI;
3824 // If none of the the value types for this register class are valid, we
3825 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3826 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3828 if (TLI.isTypeLegal(*I)) {
3829 // If we have already found this register in a different register class,
3830 // choose the one with the largest VT specified. For example, on
3831 // PowerPC, we favor f64 register classes over f32.
3832 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
3839 if (ThisVT == MVT::Other) continue;
3841 // NOTE: This isn't ideal. In particular, this might allocate the
3842 // frame pointer in functions that need it (due to them not being taken
3843 // out of allocation, because a variable sized allocation hasn't been seen
3844 // yet). This is a slight code pessimization, but should still work.
3845 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3846 E = RC->allocation_order_end(MF); I != E; ++I)
3848 // We found a matching register class. Keep looking at others in case
3849 // we find one with larger registers that this physreg is also in.
3860 /// AsmOperandInfo - This contains information for each constraint that we are
3862 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3863 /// CallOperand - If this is the result output operand or a clobber
3864 /// this is null, otherwise it is the incoming operand to the CallInst.
3865 /// This gets modified as the asm is processed.
3866 SDOperand CallOperand;
3868 /// AssignedRegs - If this is a register or register class operand, this
3869 /// contains the set of register corresponding to the operand.
3870 RegsForValue AssignedRegs;
3872 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3873 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3876 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3877 /// busy in OutputRegs/InputRegs.
3878 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3879 std::set<unsigned> &OutputRegs,
3880 std::set<unsigned> &InputRegs,
3881 const TargetRegisterInfo &TRI) const {
3883 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3884 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3887 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3888 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3893 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3895 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3896 const TargetRegisterInfo &TRI) {
3897 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3899 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3900 for (; *Aliases; ++Aliases)
3901 Regs.insert(*Aliases);
3904 } // end anon namespace.
3907 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3908 /// specified operand. We prefer to assign virtual registers, to allow the
3909 /// register allocator handle the assignment process. However, if the asm uses
3910 /// features that we can't model on machineinstrs, we have SDISel do the
3911 /// allocation. This produces generally horrible, but correct, code.
3913 /// OpInfo describes the operand.
3914 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3915 /// or any explicitly clobbered registers.
3916 /// Input and OutputRegs are the set of already allocated physical registers.
3918 void SelectionDAGLowering::
3919 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3920 std::set<unsigned> &OutputRegs,
3921 std::set<unsigned> &InputRegs) {
3922 // Compute whether this value requires an input register, an output register,
3924 bool isOutReg = false;
3925 bool isInReg = false;
3926 switch (OpInfo.Type) {
3927 case InlineAsm::isOutput:
3930 // If this is an early-clobber output, or if there is an input
3931 // constraint that matches this, we need to reserve the input register
3932 // so no other inputs allocate to it.
3933 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3935 case InlineAsm::isInput:
3939 case InlineAsm::isClobber:
3946 MachineFunction &MF = DAG.getMachineFunction();
3947 SmallVector<unsigned, 4> Regs;
3949 // If this is a constraint for a single physreg, or a constraint for a
3950 // register class, find it.
3951 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3952 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3953 OpInfo.ConstraintVT);
3955 unsigned NumRegs = 1;
3956 if (OpInfo.ConstraintVT != MVT::Other)
3957 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3959 MVT ValueVT = OpInfo.ConstraintVT;
3962 // If this is a constraint for a specific physical register, like {r17},
3964 if (PhysReg.first) {
3965 if (OpInfo.ConstraintVT == MVT::Other)
3966 ValueVT = *PhysReg.second->vt_begin();
3968 // Get the actual register value type. This is important, because the user
3969 // may have asked for (e.g.) the AX register in i32 type. We need to
3970 // remember that AX is actually i16 to get the right extension.
3971 RegVT = *PhysReg.second->vt_begin();
3973 // This is a explicit reference to a physical register.
3974 Regs.push_back(PhysReg.first);
3976 // If this is an expanded reference, add the rest of the regs to Regs.
3978 TargetRegisterClass::iterator I = PhysReg.second->begin();
3979 for (; *I != PhysReg.first; ++I)
3980 assert(I != PhysReg.second->end() && "Didn't find reg!");
3982 // Already added the first reg.
3984 for (; NumRegs; --NumRegs, ++I) {
3985 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
3989 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3990 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3991 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3995 // Otherwise, if this was a reference to an LLVM register class, create vregs
3996 // for this reference.
3997 std::vector<unsigned> RegClassRegs;
3998 const TargetRegisterClass *RC = PhysReg.second;
4000 // If this is an early clobber or tied register, our regalloc doesn't know
4001 // how to maintain the constraint. If it isn't, go ahead and create vreg
4002 // and let the regalloc do the right thing.
4003 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4004 // If there is some other early clobber and this is an input register,
4005 // then we are forced to pre-allocate the input reg so it doesn't
4006 // conflict with the earlyclobber.
4007 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
4008 RegVT = *PhysReg.second->vt_begin();
4010 if (OpInfo.ConstraintVT == MVT::Other)
4013 // Create the appropriate number of virtual registers.
4014 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4015 for (; NumRegs; --NumRegs)
4016 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4018 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4022 // Otherwise, we can't allocate it. Let the code below figure out how to
4023 // maintain these constraints.
4024 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4027 // This is a reference to a register class that doesn't directly correspond
4028 // to an LLVM register class. Allocate NumRegs consecutive, available,
4029 // registers from the class.
4030 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4031 OpInfo.ConstraintVT);
4034 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4035 unsigned NumAllocated = 0;
4036 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4037 unsigned Reg = RegClassRegs[i];
4038 // See if this register is available.
4039 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4040 (isInReg && InputRegs.count(Reg))) { // Already used.
4041 // Make sure we find consecutive registers.
4046 // Check to see if this register is allocatable (i.e. don't give out the
4049 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4050 if (!RC) { // Couldn't allocate this register.
4051 // Reset NumAllocated to make sure we return consecutive registers.
4057 // Okay, this register is good, we can use it.
4060 // If we allocated enough consecutive registers, succeed.
4061 if (NumAllocated == NumRegs) {
4062 unsigned RegStart = (i-NumAllocated)+1;
4063 unsigned RegEnd = i+1;
4064 // Mark all of the allocated registers used.
4065 for (unsigned i = RegStart; i != RegEnd; ++i)
4066 Regs.push_back(RegClassRegs[i]);
4068 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4069 OpInfo.ConstraintVT);
4070 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4075 // Otherwise, we couldn't allocate enough registers for this.
4079 /// visitInlineAsm - Handle a call to an InlineAsm object.
4081 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4082 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4084 /// ConstraintOperands - Information about all of the constraints.
4085 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4087 SDOperand Chain = getRoot();
4090 std::set<unsigned> OutputRegs, InputRegs;
4092 // Do a prepass over the constraints, canonicalizing them, and building up the
4093 // ConstraintOperands list.
4094 std::vector<InlineAsm::ConstraintInfo>
4095 ConstraintInfos = IA->ParseConstraints();
4097 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4098 // constraint. If so, we can't let the register allocator allocate any input
4099 // registers, because it will not know to avoid the earlyclobbered output reg.
4100 bool SawEarlyClobber = false;
4102 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4103 unsigned ResNo = 0; // ResNo - The result number of the next output.
4104 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4105 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4106 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4108 MVT OpVT = MVT::Other;
4110 // Compute the value type for each operand.
4111 switch (OpInfo.Type) {
4112 case InlineAsm::isOutput:
4113 // Indirect outputs just consume an argument.
4114 if (OpInfo.isIndirect) {
4115 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4118 // The return value of the call is this value. As such, there is no
4119 // corresponding argument.
4120 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4121 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4122 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4124 assert(ResNo == 0 && "Asm only has one result!");
4125 OpVT = TLI.getValueType(CS.getType());
4129 case InlineAsm::isInput:
4130 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4132 case InlineAsm::isClobber:
4137 // If this is an input or an indirect output, process the call argument.
4138 // BasicBlocks are labels, currently appearing only in asm's.
4139 if (OpInfo.CallOperandVal) {
4140 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4141 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4143 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4144 const Type *OpTy = OpInfo.CallOperandVal->getType();
4145 // If this is an indirect operand, the operand is a pointer to the
4147 if (OpInfo.isIndirect)
4148 OpTy = cast<PointerType>(OpTy)->getElementType();
4150 // If OpTy is not a single value, it may be a struct/union that we
4151 // can tile with integers.
4152 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4153 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4161 OpTy = IntegerType::get(BitSize);
4166 OpVT = TLI.getValueType(OpTy, true);
4170 OpInfo.ConstraintVT = OpVT;
4172 // Compute the constraint code and ConstraintType to use.
4173 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
4175 // Keep track of whether we see an earlyclobber.
4176 SawEarlyClobber |= OpInfo.isEarlyClobber;
4178 // If we see a clobber of a register, it is an early clobber.
4179 if (!SawEarlyClobber &&
4180 OpInfo.Type == InlineAsm::isClobber &&
4181 OpInfo.ConstraintType == TargetLowering::C_Register) {
4182 // Note that we want to ignore things that we don't trick here, like
4183 // dirflag, fpsr, flags, etc.
4184 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4185 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4186 OpInfo.ConstraintVT);
4187 if (PhysReg.first || PhysReg.second) {
4188 // This is a register we know of.
4189 SawEarlyClobber = true;
4193 // If this is a memory input, and if the operand is not indirect, do what we
4194 // need to to provide an address for the memory input.
4195 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4196 !OpInfo.isIndirect) {
4197 assert(OpInfo.Type == InlineAsm::isInput &&
4198 "Can only indirectify direct input operands!");
4200 // Memory operands really want the address of the value. If we don't have
4201 // an indirect input, put it in the constpool if we can, otherwise spill
4202 // it to a stack slot.
4204 // If the operand is a float, integer, or vector constant, spill to a
4205 // constant pool entry to get its address.
4206 Value *OpVal = OpInfo.CallOperandVal;
4207 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4208 isa<ConstantVector>(OpVal)) {
4209 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4210 TLI.getPointerTy());
4212 // Otherwise, create a stack slot and emit a store to it before the
4214 const Type *Ty = OpVal->getType();
4215 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4216 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4217 MachineFunction &MF = DAG.getMachineFunction();
4218 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4219 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4220 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4221 OpInfo.CallOperand = StackSlot;
4224 // There is no longer a Value* corresponding to this operand.
4225 OpInfo.CallOperandVal = 0;
4226 // It is now an indirect operand.
4227 OpInfo.isIndirect = true;
4230 // If this constraint is for a specific register, allocate it before
4232 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4233 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4235 ConstraintInfos.clear();
4238 // Second pass - Loop over all of the operands, assigning virtual or physregs
4239 // to registerclass operands.
4240 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4241 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4243 // C_Register operands have already been allocated, Other/Memory don't need
4245 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4246 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4249 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4250 std::vector<SDOperand> AsmNodeOperands;
4251 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
4252 AsmNodeOperands.push_back(
4253 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4256 // Loop over all of the inputs, copying the operand values into the
4257 // appropriate registers and processing the output regs.
4258 RegsForValue RetValRegs;
4260 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4261 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4263 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4264 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4266 switch (OpInfo.Type) {
4267 case InlineAsm::isOutput: {
4268 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4269 OpInfo.ConstraintType != TargetLowering::C_Register) {
4270 // Memory output, or 'other' output (e.g. 'X' constraint).
4271 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4273 // Add information to the INLINEASM node to know about this output.
4274 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4275 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4276 TLI.getPointerTy()));
4277 AsmNodeOperands.push_back(OpInfo.CallOperand);
4281 // Otherwise, this is a register or register class output.
4283 // Copy the output from the appropriate register. Find a register that
4285 if (OpInfo.AssignedRegs.Regs.empty()) {
4286 cerr << "Couldn't allocate output reg for contraint '"
4287 << OpInfo.ConstraintCode << "'!\n";
4291 // If this is an indirect operand, store through the pointer after the
4293 if (OpInfo.isIndirect) {
4294 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4295 OpInfo.CallOperandVal));
4297 // This is the result value of the call.
4298 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4299 // Concatenate this output onto the outputs list.
4300 RetValRegs.append(OpInfo.AssignedRegs);
4303 // Add information to the INLINEASM node to know that this register is
4305 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4309 case InlineAsm::isInput: {
4310 SDOperand InOperandVal = OpInfo.CallOperand;
4312 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
4313 // If this is required to match an output register we have already set,
4314 // just use its register.
4315 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4317 // Scan until we find the definition we already emitted of this operand.
4318 // When we find it, create a RegsForValue operand.
4319 unsigned CurOp = 2; // The first operand.
4320 for (; OperandNo; --OperandNo) {
4321 // Advance to the next operand.
4323 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4324 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4325 (NumOps & 7) == 4 /*MEM*/) &&
4326 "Skipped past definitions?");
4327 CurOp += (NumOps>>3)+1;
4331 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4332 if ((NumOps & 7) == 2 /*REGDEF*/) {
4333 // Add NumOps>>3 registers to MatchedRegs.
4334 RegsForValue MatchedRegs;
4335 MatchedRegs.TLI = &TLI;
4336 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4337 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4338 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4340 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4341 MatchedRegs.Regs.push_back(Reg);
4344 // Use the produced MatchedRegs object to
4345 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4346 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4349 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4350 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4351 // Add information to the INLINEASM node to know about this input.
4352 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4353 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4354 TLI.getPointerTy()));
4355 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4360 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4361 assert(!OpInfo.isIndirect &&
4362 "Don't know how to handle indirect other inputs yet!");
4364 std::vector<SDOperand> Ops;
4365 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4368 cerr << "Invalid operand for inline asm constraint '"
4369 << OpInfo.ConstraintCode << "'!\n";
4373 // Add information to the INLINEASM node to know about this input.
4374 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4375 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4376 TLI.getPointerTy()));
4377 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4379 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4380 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4381 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4382 "Memory operands expect pointer values");
4384 // Add information to the INLINEASM node to know about this input.
4385 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4386 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4387 TLI.getPointerTy()));
4388 AsmNodeOperands.push_back(InOperandVal);
4392 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4393 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4394 "Unknown constraint type!");
4395 assert(!OpInfo.isIndirect &&
4396 "Don't know how to handle indirect register inputs yet!");
4398 // Copy the input into the appropriate registers.
4399 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4400 "Couldn't allocate input reg!");
4402 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4404 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4408 case InlineAsm::isClobber: {
4409 // Add the clobbered value to the operand list, so that the register
4410 // allocator is aware that the physreg got clobbered.
4411 if (!OpInfo.AssignedRegs.Regs.empty())
4412 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4419 // Finish up input operands.
4420 AsmNodeOperands[0] = Chain;
4421 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4423 Chain = DAG.getNode(ISD::INLINEASM,
4424 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4425 &AsmNodeOperands[0], AsmNodeOperands.size());
4426 Flag = Chain.getValue(1);
4428 // If this asm returns a register value, copy the result from that register
4429 // and set it as the value of the call.
4430 if (!RetValRegs.Regs.empty()) {
4431 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4433 // If any of the results of the inline asm is a vector, it may have the
4434 // wrong width/num elts. This can happen for register classes that can
4435 // contain multiple different value types. The preg or vreg allocated may
4436 // not have the same VT as was expected. Convert it to the right type with
4438 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4439 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4440 if (Val.Val->getValueType(i).isVector())
4441 Val = DAG.getNode(ISD::BIT_CONVERT,
4442 TLI.getValueType(ResSTy->getElementType(i)), Val);
4445 if (Val.getValueType().isVector())
4446 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4450 setValue(CS.getInstruction(), Val);
4453 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4455 // Process indirect outputs, first output all of the flagged copies out of
4457 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4458 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4459 Value *Ptr = IndirectStoresToEmit[i].second;
4460 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4461 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4464 // Emit the non-flagged stores from the physregs.
4465 SmallVector<SDOperand, 8> OutChains;
4466 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4467 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4468 getValue(StoresToEmit[i].second),
4469 StoresToEmit[i].second, 0));
4470 if (!OutChains.empty())
4471 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4472 &OutChains[0], OutChains.size());
4477 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4478 SDOperand Src = getValue(I.getOperand(0));
4480 MVT IntPtr = TLI.getPointerTy();
4482 if (IntPtr.bitsLT(Src.getValueType()))
4483 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4484 else if (IntPtr.bitsGT(Src.getValueType()))
4485 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4487 // Scale the source by the type size.
4488 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4489 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4490 Src, DAG.getIntPtrConstant(ElementSize));
4492 TargetLowering::ArgListTy Args;
4493 TargetLowering::ArgListEntry Entry;
4495 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4496 Args.push_back(Entry);
4498 std::pair<SDOperand,SDOperand> Result =
4499 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4500 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4501 setValue(&I, Result.first); // Pointers always fit in registers
4502 DAG.setRoot(Result.second);
4505 void SelectionDAGLowering::visitFree(FreeInst &I) {
4506 TargetLowering::ArgListTy Args;
4507 TargetLowering::ArgListEntry Entry;
4508 Entry.Node = getValue(I.getOperand(0));
4509 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4510 Args.push_back(Entry);
4511 MVT IntPtr = TLI.getPointerTy();
4512 std::pair<SDOperand,SDOperand> Result =
4513 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4514 CallingConv::C, true,
4515 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4516 DAG.setRoot(Result.second);
4519 // EmitInstrWithCustomInserter - This method should be implemented by targets
4520 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
4521 // instructions are special in various ways, which require special support to
4522 // insert. The specified MachineInstr is created but not inserted into any
4523 // basic blocks, and the scheduler passes ownership of it to this method.
4524 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4525 MachineBasicBlock *MBB) {
4526 cerr << "If a target marks an instruction with "
4527 << "'usesCustomDAGSchedInserter', it must implement "
4528 << "TargetLowering::EmitInstrWithCustomInserter!\n";
4533 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4534 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4535 getValue(I.getOperand(1)),
4536 DAG.getSrcValue(I.getOperand(1))));
4539 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4540 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4541 getValue(I.getOperand(0)),
4542 DAG.getSrcValue(I.getOperand(0)));
4544 DAG.setRoot(V.getValue(1));
4547 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4548 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4549 getValue(I.getOperand(1)),
4550 DAG.getSrcValue(I.getOperand(1))));
4553 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4554 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4555 getValue(I.getOperand(1)),
4556 getValue(I.getOperand(2)),
4557 DAG.getSrcValue(I.getOperand(1)),
4558 DAG.getSrcValue(I.getOperand(2))));
4561 /// TargetLowering::LowerArguments - This is the default LowerArguments
4562 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4563 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4564 /// integrated into SDISel.
4565 std::vector<SDOperand>
4566 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4567 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4568 std::vector<SDOperand> Ops;
4569 Ops.push_back(DAG.getRoot());
4570 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4571 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4573 // Add one result value for each formal argument.
4574 std::vector<MVT> RetVals;
4576 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4578 SmallVector<MVT, 4> ValueVTs;
4579 ComputeValueVTs(*this, I->getType(), ValueVTs);
4580 for (unsigned Value = 0, NumValues = ValueVTs.size();
4581 Value != NumValues; ++Value) {
4582 MVT VT = ValueVTs[Value];
4583 const Type *ArgTy = VT.getTypeForMVT();
4584 ISD::ArgFlagsTy Flags;
4585 unsigned OriginalAlignment =
4586 getTargetData()->getABITypeAlignment(ArgTy);
4588 if (F.paramHasAttr(j, ParamAttr::ZExt))
4590 if (F.paramHasAttr(j, ParamAttr::SExt))
4592 if (F.paramHasAttr(j, ParamAttr::InReg))
4594 if (F.paramHasAttr(j, ParamAttr::StructRet))
4596 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4598 const PointerType *Ty = cast<PointerType>(I->getType());
4599 const Type *ElementTy = Ty->getElementType();
4600 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4601 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4602 // For ByVal, alignment should be passed from FE. BE will guess if
4603 // this info is not there but there are cases it cannot get right.
4604 if (F.getParamAlignment(j))
4605 FrameAlign = F.getParamAlignment(j);
4606 Flags.setByValAlign(FrameAlign);
4607 Flags.setByValSize(FrameSize);
4609 if (F.paramHasAttr(j, ParamAttr::Nest))
4611 Flags.setOrigAlign(OriginalAlignment);
4613 MVT RegisterVT = getRegisterType(VT);
4614 unsigned NumRegs = getNumRegisters(VT);
4615 for (unsigned i = 0; i != NumRegs; ++i) {
4616 RetVals.push_back(RegisterVT);
4617 ISD::ArgFlagsTy MyFlags = Flags;
4618 if (NumRegs > 1 && i == 0)
4620 // if it isn't first piece, alignment must be 1
4622 MyFlags.setOrigAlign(1);
4623 Ops.push_back(DAG.getArgFlags(MyFlags));
4628 RetVals.push_back(MVT::Other);
4631 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4632 DAG.getVTList(&RetVals[0], RetVals.size()),
4633 &Ops[0], Ops.size()).Val;
4635 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4636 // allows exposing the loads that may be part of the argument access to the
4637 // first DAGCombiner pass.
4638 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4640 // The number of results should match up, except that the lowered one may have
4641 // an extra flag result.
4642 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4643 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4644 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4645 && "Lowering produced unexpected number of results!");
4646 Result = TmpRes.Val;
4648 unsigned NumArgRegs = Result->getNumValues() - 1;
4649 DAG.setRoot(SDOperand(Result, NumArgRegs));
4651 // Set up the return result vector.
4655 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4657 SmallVector<MVT, 4> ValueVTs;
4658 ComputeValueVTs(*this, I->getType(), ValueVTs);
4659 for (unsigned Value = 0, NumValues = ValueVTs.size();
4660 Value != NumValues; ++Value) {
4661 MVT VT = ValueVTs[Value];
4662 MVT PartVT = getRegisterType(VT);
4664 unsigned NumParts = getNumRegisters(VT);
4665 SmallVector<SDOperand, 4> Parts(NumParts);
4666 for (unsigned j = 0; j != NumParts; ++j)
4667 Parts[j] = SDOperand(Result, i++);
4669 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4670 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4671 AssertOp = ISD::AssertSext;
4672 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4673 AssertOp = ISD::AssertZext;
4675 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4679 assert(i == NumArgRegs && "Argument register count mismatch!");
4684 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4685 /// implementation, which just inserts an ISD::CALL node, which is later custom
4686 /// lowered by the target to something concrete. FIXME: When all targets are
4687 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4688 std::pair<SDOperand, SDOperand>
4689 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4690 bool RetSExt, bool RetZExt, bool isVarArg,
4691 unsigned CallingConv, bool isTailCall,
4693 ArgListTy &Args, SelectionDAG &DAG) {
4694 SmallVector<SDOperand, 32> Ops;
4695 Ops.push_back(Chain); // Op#0 - Chain
4696 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4697 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4698 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4699 Ops.push_back(Callee);
4701 // Handle all of the outgoing arguments.
4702 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4703 SmallVector<MVT, 4> ValueVTs;
4704 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4705 for (unsigned Value = 0, NumValues = ValueVTs.size();
4706 Value != NumValues; ++Value) {
4707 MVT VT = ValueVTs[Value];
4708 const Type *ArgTy = VT.getTypeForMVT();
4709 SDOperand Op = SDOperand(Args[i].Node.Val, Args[i].Node.ResNo + Value);
4710 ISD::ArgFlagsTy Flags;
4711 unsigned OriginalAlignment =
4712 getTargetData()->getABITypeAlignment(ArgTy);
4718 if (Args[i].isInReg)
4722 if (Args[i].isByVal) {
4724 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4725 const Type *ElementTy = Ty->getElementType();
4726 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4727 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4728 // For ByVal, alignment should come from FE. BE will guess if this
4729 // info is not there but there are cases it cannot get right.
4730 if (Args[i].Alignment)
4731 FrameAlign = Args[i].Alignment;
4732 Flags.setByValAlign(FrameAlign);
4733 Flags.setByValSize(FrameSize);
4737 Flags.setOrigAlign(OriginalAlignment);
4739 MVT PartVT = getRegisterType(VT);
4740 unsigned NumParts = getNumRegisters(VT);
4741 SmallVector<SDOperand, 4> Parts(NumParts);
4742 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4745 ExtendKind = ISD::SIGN_EXTEND;
4746 else if (Args[i].isZExt)
4747 ExtendKind = ISD::ZERO_EXTEND;
4749 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4751 for (unsigned i = 0; i != NumParts; ++i) {
4752 // if it isn't first piece, alignment must be 1
4753 ISD::ArgFlagsTy MyFlags = Flags;
4754 if (NumParts > 1 && i == 0)
4757 MyFlags.setOrigAlign(1);
4759 Ops.push_back(Parts[i]);
4760 Ops.push_back(DAG.getArgFlags(MyFlags));
4765 // Figure out the result value types. We start by making a list of
4766 // the potentially illegal return value types.
4767 SmallVector<MVT, 4> LoweredRetTys;
4768 SmallVector<MVT, 4> RetTys;
4769 ComputeValueVTs(*this, RetTy, RetTys);
4771 // Then we translate that to a list of legal types.
4772 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4774 MVT RegisterVT = getRegisterType(VT);
4775 unsigned NumRegs = getNumRegisters(VT);
4776 for (unsigned i = 0; i != NumRegs; ++i)
4777 LoweredRetTys.push_back(RegisterVT);
4780 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4782 // Create the CALL node.
4783 SDOperand Res = DAG.getNode(ISD::CALL,
4784 DAG.getVTList(&LoweredRetTys[0],
4785 LoweredRetTys.size()),
4786 &Ops[0], Ops.size());
4787 Chain = Res.getValue(LoweredRetTys.size() - 1);
4789 // Gather up the call result into a single value.
4790 if (RetTy != Type::VoidTy) {
4791 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4794 AssertOp = ISD::AssertSext;
4796 AssertOp = ISD::AssertZext;
4798 SmallVector<SDOperand, 4> ReturnValues;
4800 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4802 MVT RegisterVT = getRegisterType(VT);
4803 unsigned NumRegs = getNumRegisters(VT);
4804 unsigned RegNoEnd = NumRegs + RegNo;
4805 SmallVector<SDOperand, 4> Results;
4806 for (; RegNo != RegNoEnd; ++RegNo)
4807 Results.push_back(Res.getValue(RegNo));
4808 SDOperand ReturnValue =
4809 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4811 ReturnValues.push_back(ReturnValue);
4813 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4814 DAG.getNode(ISD::MERGE_VALUES,
4815 DAG.getVTList(&RetTys[0], RetTys.size()),
4816 &ReturnValues[0], ReturnValues.size());
4819 return std::make_pair(Res, Chain);
4822 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4823 assert(0 && "LowerOperation not implemented for this target!");
4828 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4829 SelectionDAG &DAG) {
4830 assert(0 && "CustomPromoteOperation not implemented for this target!");
4835 //===----------------------------------------------------------------------===//
4836 // SelectionDAGISel code
4837 //===----------------------------------------------------------------------===//
4839 unsigned SelectionDAGISel::MakeReg(MVT VT) {
4840 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4843 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4844 AU.addRequired<AliasAnalysis>();
4845 AU.addRequired<CollectorModuleMetadata>();
4846 AU.setPreservesAll();
4849 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4850 // Get alias analysis for load/store combining.
4851 AA = &getAnalysis<AliasAnalysis>();
4853 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4854 if (MF.getFunction()->hasCollector())
4855 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4858 RegInfo = &MF.getRegInfo();
4859 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4861 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4863 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4864 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4865 // Mark landing pad.
4866 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4868 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4869 SelectBasicBlock(I, MF, FuncInfo);
4871 // Add function live-ins to entry block live-in set.
4872 BasicBlock *EntryBB = &Fn.getEntryBlock();
4873 BB = FuncInfo.MBBMap[EntryBB];
4874 if (!RegInfo->livein_empty())
4875 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4876 E = RegInfo->livein_end(); I != E; ++I)
4877 BB->addLiveIn(I->first);
4880 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4881 "Not all catch info was assigned to a landing pad!");
4887 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4888 SDOperand Op = getValue(V);
4889 assert((Op.getOpcode() != ISD::CopyFromReg ||
4890 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4891 "Copy from a reg to the same reg!");
4892 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4894 RegsForValue RFV(TLI, Reg, V->getType());
4895 SDOperand Chain = DAG.getEntryNode();
4896 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4897 PendingExports.push_back(Chain);
4900 void SelectionDAGISel::
4901 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4902 // If this is the entry block, emit arguments.
4903 Function &F = *LLVMBB->getParent();
4904 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4905 SDOperand OldRoot = SDL.DAG.getRoot();
4906 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4909 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4911 SmallVector<MVT, 4> ValueVTs;
4912 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4913 unsigned NumValues = ValueVTs.size();
4914 if (!AI->use_empty()) {
4915 SmallVector<MVT, 4> LegalValueVTs(NumValues);
4916 for (unsigned VI = 0; VI != NumValues; ++VI)
4917 LegalValueVTs[VI] = Args[a + VI].getValueType();
4918 SDL.setValue(AI, SDL.DAG.getNode(ISD::MERGE_VALUES,
4919 SDL.DAG.getVTList(&LegalValueVTs[0],
4921 &Args[a], NumValues));
4922 // If this argument is live outside of the entry block, insert a copy from
4923 // whereever we got it to the vreg that other BB's will reference it as.
4924 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4925 if (VMI != FuncInfo.ValueMap.end()) {
4926 SDL.CopyValueToVirtualRegister(AI, VMI->second);
4932 // Finally, if the target has anything special to do, allow it to do so.
4933 // FIXME: this should insert code into the DAG!
4934 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4937 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4938 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4939 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4940 if (isSelector(I)) {
4941 // Apply the catch info to DestBB.
4942 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4944 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4945 FLI.CatchInfoFound.insert(I);
4950 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4951 /// whether object offset >= 0.
4953 IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4954 if (!isa<FrameIndexSDNode>(Op)) return false;
4956 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4957 int FrameIdx = FrameIdxNode->getIndex();
4958 return MFI->isFixedObjectIndex(FrameIdx) &&
4959 MFI->getObjectOffset(FrameIdx) >= 0;
4962 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4963 /// possibly be overwritten when lowering the outgoing arguments in a tail
4964 /// call. Currently the implementation of this call is very conservative and
4965 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4966 /// virtual registers would be overwritten by direct lowering.
4967 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4968 MachineFrameInfo * MFI) {
4969 RegisterSDNode * OpReg = NULL;
4970 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4971 (Op.getOpcode()== ISD::CopyFromReg &&
4972 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4973 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4974 (Op.getOpcode() == ISD::LOAD &&
4975 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4976 (Op.getOpcode() == ISD::MERGE_VALUES &&
4977 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4978 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4984 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
4985 /// DAG and fixes their tailcall attribute operand.
4986 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4987 TargetLowering& TLI) {
4988 SDNode * Ret = NULL;
4989 SDOperand Terminator = DAG.getRoot();
4992 if (Terminator.getOpcode() == ISD::RET) {
4993 Ret = Terminator.Val;
4996 // Fix tail call attribute of CALL nodes.
4997 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4998 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4999 if (BI->getOpcode() == ISD::CALL) {
5000 SDOperand OpRet(Ret, 0);
5001 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
5002 bool isMarkedTailCall =
5003 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5004 // If CALL node has tail call attribute set to true and the call is not
5005 // eligible (no RET or the target rejects) the attribute is fixed to
5006 // false. The TargetLowering::IsEligibleForTailCallOptimization function
5007 // must correctly identify tail call optimizable calls.
5008 if (!isMarkedTailCall) continue;
5010 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5011 // Not eligible. Mark CALL node as non tail call.
5012 SmallVector<SDOperand, 32> Ops;
5014 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5015 E = OpCall.Val->op_end(); I != E; I++, idx++) {
5019 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5021 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
5023 // Look for tail call clobbered arguments. Emit a series of
5024 // copyto/copyfrom virtual register nodes to protect them.
5025 SmallVector<SDOperand, 32> Ops;
5026 SDOperand Chain = OpCall.getOperand(0), InFlag;
5028 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5029 E = OpCall.Val->op_end(); I != E; I++, idx++) {
5031 if (idx > 4 && (idx % 2)) {
5032 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5033 getArgFlags().isByVal();
5034 MachineFunction &MF = DAG.getMachineFunction();
5035 MachineFrameInfo *MFI = MF.getFrameInfo();
5037 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
5038 MVT VT = Arg.getValueType();
5039 unsigned VReg = MF.getRegInfo().
5040 createVirtualRegister(TLI.getRegClassFor(VT));
5041 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5042 InFlag = Chain.getValue(1);
5043 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5044 Chain = Arg.getValue(1);
5045 InFlag = Arg.getValue(2);
5050 // Link in chain of CopyTo/CopyFromReg.
5052 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
5058 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
5059 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5060 FunctionLoweringInfo &FuncInfo) {
5061 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
5063 // Lower any arguments needed in this block if this is the entry block.
5064 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
5065 LowerArguments(LLVMBB, SDL);
5067 BB = FuncInfo.MBBMap[LLVMBB];
5068 SDL.setCurrentBasicBlock(BB);
5070 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
5072 if (MMI && BB->isLandingPad()) {
5073 // Add a label to mark the beginning of the landing pad. Deletion of the
5074 // landing pad can thus be detected via the MachineModuleInfo.
5075 unsigned LabelID = MMI->addLandingPad(BB);
5076 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
5077 DAG.getConstant(LabelID, MVT::i32),
5078 DAG.getConstant(1, MVT::i32)));
5080 // Mark exception register as live in.
5081 unsigned Reg = TLI.getExceptionAddressRegister();
5082 if (Reg) BB->addLiveIn(Reg);
5084 // Mark exception selector register as live in.
5085 Reg = TLI.getExceptionSelectorRegister();
5086 if (Reg) BB->addLiveIn(Reg);
5088 // FIXME: Hack around an exception handling flaw (PR1508): the personality
5089 // function and list of typeids logically belong to the invoke (or, if you
5090 // like, the basic block containing the invoke), and need to be associated
5091 // with it in the dwarf exception handling tables. Currently however the
5092 // information is provided by an intrinsic (eh.selector) that can be moved
5093 // to unexpected places by the optimizers: if the unwind edge is critical,
5094 // then breaking it can result in the intrinsics being in the successor of
5095 // the landing pad, not the landing pad itself. This results in exceptions
5096 // not being caught because no typeids are associated with the invoke.
5097 // This may not be the only way things can go wrong, but it is the only way
5098 // we try to work around for the moment.
5099 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5101 if (Br && Br->isUnconditional()) { // Critical edge?
5102 BasicBlock::iterator I, E;
5103 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
5108 // No catch info found - try to extract some from the successor.
5109 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
5113 // Lower all of the non-terminator instructions.
5114 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
5118 // Ensure that all instructions which are used outside of their defining
5119 // blocks are available as virtual registers. Invoke is handled elsewhere.
5120 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
5121 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
5122 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
5123 if (VMI != FuncInfo.ValueMap.end())
5124 SDL.CopyValueToVirtualRegister(I, VMI->second);
5127 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5128 // ensure constants are generated when needed. Remember the virtual registers
5129 // that need to be added to the Machine PHI nodes as input. We cannot just
5130 // directly add them, because expansion might result in multiple MBB's for one
5131 // BB. As such, the start of the BB might correspond to a different MBB than
5134 TerminatorInst *TI = LLVMBB->getTerminator();
5136 // Emit constants only once even if used by multiple PHI nodes.
5137 std::map<Constant*, unsigned> ConstantsOut;
5139 // Vector bool would be better, but vector<bool> is really slow.
5140 std::vector<unsigned char> SuccsHandled;
5141 if (TI->getNumSuccessors())
5142 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
5144 // Check successor nodes' PHI nodes that expect a constant to be available
5146 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5147 BasicBlock *SuccBB = TI->getSuccessor(succ);
5148 if (!isa<PHINode>(SuccBB->begin())) continue;
5149 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
5151 // If this terminator has multiple identical successors (common for
5152 // switches), only handle each succ once.
5153 unsigned SuccMBBNo = SuccMBB->getNumber();
5154 if (SuccsHandled[SuccMBBNo]) continue;
5155 SuccsHandled[SuccMBBNo] = true;
5157 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5160 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5161 // nodes and Machine PHI nodes, but the incoming operands have not been
5163 for (BasicBlock::iterator I = SuccBB->begin();
5164 (PN = dyn_cast<PHINode>(I)); ++I) {
5165 // Ignore dead phi's.
5166 if (PN->use_empty()) continue;
5169 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5171 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5172 unsigned &RegOut = ConstantsOut[C];
5174 RegOut = FuncInfo.CreateRegForValue(C);
5175 SDL.CopyValueToVirtualRegister(C, RegOut);
5179 Reg = FuncInfo.ValueMap[PHIOp];
5181 assert(isa<AllocaInst>(PHIOp) &&
5182 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5183 "Didn't codegen value into a register!??");
5184 Reg = FuncInfo.CreateRegForValue(PHIOp);
5185 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
5189 // Remember that this register needs to added to the machine PHI node as
5190 // the input for this MBB.
5191 MVT VT = TLI.getValueType(PN->getType());
5192 unsigned NumRegisters = TLI.getNumRegisters(VT);
5193 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5194 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5197 ConstantsOut.clear();
5199 // Lower the terminator after the copies are emitted.
5200 SDL.visit(*LLVMBB->getTerminator());
5202 // Copy over any CaseBlock records that may now exist due to SwitchInst
5203 // lowering, as well as any jump table information.
5204 SwitchCases.clear();
5205 SwitchCases = SDL.SwitchCases;
5207 JTCases = SDL.JTCases;
5208 BitTestCases.clear();
5209 BitTestCases = SDL.BitTestCases;
5211 // Make sure the root of the DAG is up-to-date.
5212 DAG.setRoot(SDL.getControlRoot());
5214 // Check whether calls in this block are real tail calls. Fix up CALL nodes
5215 // with correct tailcall attribute so that the target can rely on the tailcall
5216 // attribute indicating whether the call is really eligible for tail call
5218 CheckDAGForTailCallsAndFixThem(DAG, TLI);
5221 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
5222 DOUT << "Lowered selection DAG:\n";
5225 // Run the DAG combiner in pre-legalize mode.
5226 DAG.Combine(false, *AA);
5228 DOUT << "Optimized lowered selection DAG:\n";
5231 // Second step, hack on the DAG until it only uses operations and types that
5232 // the target supports.
5233 #if 0 // Enable this some day.
5234 DAG.LegalizeTypes();
5235 // Someday even later, enable a dag combine pass here.
5239 DOUT << "Legalized selection DAG:\n";
5242 // Run the DAG combiner in post-legalize mode.
5243 DAG.Combine(true, *AA);
5245 DOUT << "Optimized legalized selection DAG:\n";
5248 if (ViewISelDAGs) DAG.viewGraph();
5250 // Third, instruction select all of the operations to machine code, adding the
5251 // code to the MachineBasicBlock.
5252 InstructionSelectBasicBlock(DAG);
5254 DOUT << "Selected machine code:\n";
5258 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5259 FunctionLoweringInfo &FuncInfo) {
5260 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5262 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5265 // First step, lower LLVM code to some DAG. This DAG may use operations and
5266 // types that are not supported by the target.
5267 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5269 // Second step, emit the lowered DAG as machine code.
5270 CodeGenAndEmitDAG(DAG);
5273 DOUT << "Total amount of phi nodes to update: "
5274 << PHINodesToUpdate.size() << "\n";
5275 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5276 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5277 << ", " << PHINodesToUpdate[i].second << ")\n";);
5279 // Next, now that we know what the last MBB the LLVM BB expanded is, update
5280 // PHI nodes in successors.
5281 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
5282 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5283 MachineInstr *PHI = PHINodesToUpdate[i].first;
5284 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5285 "This is not a machine PHI node that we are updating!");
5286 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5288 PHI->addOperand(MachineOperand::CreateMBB(BB));
5293 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5294 // Lower header first, if it wasn't already lowered
5295 if (!BitTestCases[i].Emitted) {
5296 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5298 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5299 // Set the current basic block to the mbb we wish to insert the code into
5300 BB = BitTestCases[i].Parent;
5301 HSDL.setCurrentBasicBlock(BB);
5303 HSDL.visitBitTestHeader(BitTestCases[i]);
5304 HSDAG.setRoot(HSDL.getRoot());
5305 CodeGenAndEmitDAG(HSDAG);
5308 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5309 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5311 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
5312 // Set the current basic block to the mbb we wish to insert the code into
5313 BB = BitTestCases[i].Cases[j].ThisBB;
5314 BSDL.setCurrentBasicBlock(BB);
5317 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5318 BitTestCases[i].Reg,
5319 BitTestCases[i].Cases[j]);
5321 BSDL.visitBitTestCase(BitTestCases[i].Default,
5322 BitTestCases[i].Reg,
5323 BitTestCases[i].Cases[j]);
5326 BSDAG.setRoot(BSDL.getRoot());
5327 CodeGenAndEmitDAG(BSDAG);
5331 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5332 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5333 MachineBasicBlock *PHIBB = PHI->getParent();
5334 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5335 "This is not a machine PHI node that we are updating!");
5336 // This is "default" BB. We have two jumps to it. From "header" BB and
5337 // from last "case" BB.
5338 if (PHIBB == BitTestCases[i].Default) {
5339 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5341 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5342 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5344 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5347 // One of "cases" BB.
5348 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5349 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5350 if (cBB->succ_end() !=
5351 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
5352 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5354 PHI->addOperand(MachineOperand::CreateMBB(cBB));
5360 // If the JumpTable record is filled in, then we need to emit a jump table.
5361 // Updating the PHI nodes is tricky in this case, since we need to determine
5362 // whether the PHI is a successor of the range check MBB or the jump table MBB
5363 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5364 // Lower header first, if it wasn't already lowered
5365 if (!JTCases[i].first.Emitted) {
5366 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5368 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5369 // Set the current basic block to the mbb we wish to insert the code into
5370 BB = JTCases[i].first.HeaderBB;
5371 HSDL.setCurrentBasicBlock(BB);
5373 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5374 HSDAG.setRoot(HSDL.getRoot());
5375 CodeGenAndEmitDAG(HSDAG);
5378 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5380 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
5381 // Set the current basic block to the mbb we wish to insert the code into
5382 BB = JTCases[i].second.MBB;
5383 JSDL.setCurrentBasicBlock(BB);
5385 JSDL.visitJumpTable(JTCases[i].second);
5386 JSDAG.setRoot(JSDL.getRoot());
5387 CodeGenAndEmitDAG(JSDAG);
5390 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5391 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5392 MachineBasicBlock *PHIBB = PHI->getParent();
5393 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5394 "This is not a machine PHI node that we are updating!");
5395 // "default" BB. We can go there only from header BB.
5396 if (PHIBB == JTCases[i].second.Default) {
5397 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5399 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
5401 // JT BB. Just iterate over successors here
5402 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
5403 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5405 PHI->addOperand(MachineOperand::CreateMBB(BB));
5410 // If the switch block involved a branch to one of the actual successors, we
5411 // need to update PHI nodes in that block.
5412 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5413 MachineInstr *PHI = PHINodesToUpdate[i].first;
5414 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5415 "This is not a machine PHI node that we are updating!");
5416 if (BB->isSuccessor(PHI->getParent())) {
5417 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5419 PHI->addOperand(MachineOperand::CreateMBB(BB));
5423 // If we generated any switch lowering information, build and codegen any
5424 // additional DAGs necessary.
5425 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
5426 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5428 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
5430 // Set the current basic block to the mbb we wish to insert the code into
5431 BB = SwitchCases[i].ThisBB;
5432 SDL.setCurrentBasicBlock(BB);
5435 SDL.visitSwitchCase(SwitchCases[i]);
5436 SDAG.setRoot(SDL.getRoot());
5437 CodeGenAndEmitDAG(SDAG);
5439 // Handle any PHI nodes in successors of this chunk, as if we were coming
5440 // from the original BB before switch expansion. Note that PHI nodes can
5441 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5442 // handle them the right number of times.
5443 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
5444 for (MachineBasicBlock::iterator Phi = BB->begin();
5445 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5446 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5447 for (unsigned pn = 0; ; ++pn) {
5448 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5449 if (PHINodesToUpdate[pn].first == Phi) {
5450 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5452 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5458 // Don't process RHS if same block as LHS.
5459 if (BB == SwitchCases[i].FalseBB)
5460 SwitchCases[i].FalseBB = 0;
5462 // If we haven't handled the RHS, do so now. Otherwise, we're done.
5463 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5464 SwitchCases[i].FalseBB = 0;
5466 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5471 //===----------------------------------------------------------------------===//
5472 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5473 /// target node in the graph.
5474 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5475 if (ViewSchedDAGs) DAG.viewGraph();
5477 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5481 RegisterScheduler::setDefault(Ctor);
5484 ScheduleDAG *SL = Ctor(this, &DAG, BB);
5487 if (ViewSUnitDAGs) SL->viewGraph();
5493 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5494 return new HazardRecognizer();
5497 //===----------------------------------------------------------------------===//
5498 // Helper functions used by the generated instruction selector.
5499 //===----------------------------------------------------------------------===//
5500 // Calls to these methods are generated by tblgen.
5502 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
5503 /// the dag combiner simplified the 255, we still want to match. RHS is the
5504 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5505 /// specified in the .td file (e.g. 255).
5506 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
5507 int64_t DesiredMaskS) const {
5508 const APInt &ActualMask = RHS->getAPIntValue();
5509 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5511 // If the actual mask exactly matches, success!
5512 if (ActualMask == DesiredMask)
5515 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5516 if (ActualMask.intersects(~DesiredMask))
5519 // Otherwise, the DAG Combiner may have proven that the value coming in is
5520 // either already zero or is not demanded. Check for known zero input bits.
5521 APInt NeededMask = DesiredMask & ~ActualMask;
5522 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5525 // TODO: check to see if missing bits are just not demanded.
5527 // Otherwise, this pattern doesn't match.
5531 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
5532 /// the dag combiner simplified the 255, we still want to match. RHS is the
5533 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5534 /// specified in the .td file (e.g. 255).
5535 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
5536 int64_t DesiredMaskS) const {
5537 const APInt &ActualMask = RHS->getAPIntValue();
5538 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5540 // If the actual mask exactly matches, success!
5541 if (ActualMask == DesiredMask)
5544 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5545 if (ActualMask.intersects(~DesiredMask))
5548 // Otherwise, the DAG Combiner may have proven that the value coming in is
5549 // either already zero or is not demanded. Check for known zero input bits.
5550 APInt NeededMask = DesiredMask & ~ActualMask;
5552 APInt KnownZero, KnownOne;
5553 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5555 // If all the missing bits in the or are already known to be set, match!
5556 if ((NeededMask & KnownOne) == NeededMask)
5559 // TODO: check to see if missing bits are just not demanded.
5561 // Otherwise, this pattern doesn't match.
5566 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5567 /// by tblgen. Others should not call it.
5568 void SelectionDAGISel::
5569 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5570 std::vector<SDOperand> InOps;
5571 std::swap(InOps, Ops);
5573 Ops.push_back(InOps[0]); // input chain.
5574 Ops.push_back(InOps[1]); // input asm string.
5576 unsigned i = 2, e = InOps.size();
5577 if (InOps[e-1].getValueType() == MVT::Flag)
5578 --e; // Don't process a flag operand if it is here.
5581 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5582 if ((Flags & 7) != 4 /*MEM*/) {
5583 // Just skip over this operand, copying the operands verbatim.
5584 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5585 i += (Flags >> 3) + 1;
5587 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5588 // Otherwise, this is a memory operand. Ask the target to select it.
5589 std::vector<SDOperand> SelOps;
5590 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5591 cerr << "Could not match memory address. Inline asm failure!\n";
5595 // Add this to the output node.
5596 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5597 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5599 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5604 // Add the flag input back if present.
5605 if (e != InOps.size())
5606 Ops.push_back(InOps.back());
5609 char SelectionDAGISel::ID = 0;