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/CodeGen/SelectionDAGISel.h"
16 #include "SimpleBBISel.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/Analysis/AliasAnalysis.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/FastISel.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/GCMetadata.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/ScheduleDAG.h"
39 #include "llvm/CodeGen/SchedulerRegistry.h"
40 #include "llvm/CodeGen/SelectionDAG.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetFrameInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/Timer.h"
56 EnableValueProp("enable-value-prop", cl::Hidden);
58 EnableLegalizeTypes("enable-legalize-types", cl::Hidden);
60 EnableFastISel("fast-isel", cl::Hidden,
61 cl::desc("Enable the experimental \"fast\" instruction selector"));
66 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
67 cl::desc("Pop up a window to show dags before the first "
70 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
71 cl::desc("Pop up a window to show dags before legalize types"));
73 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
74 cl::desc("Pop up a window to show dags before legalize"));
76 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
77 cl::desc("Pop up a window to show dags before the second "
80 ViewISelDAGs("view-isel-dags", cl::Hidden,
81 cl::desc("Pop up a window to show isel dags as they are selected"));
83 ViewSchedDAGs("view-sched-dags", cl::Hidden,
84 cl::desc("Pop up a window to show sched dags as they are processed"));
86 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
87 cl::desc("Pop up a window to show SUnit dags after they are processed"));
89 static const bool ViewDAGCombine1 = false,
90 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
91 ViewDAGCombine2 = false,
92 ViewISelDAGs = false, ViewSchedDAGs = false,
93 ViewSUnitDAGs = false;
96 //===---------------------------------------------------------------------===//
98 /// RegisterScheduler class - Track the registration of instruction schedulers.
100 //===---------------------------------------------------------------------===//
101 MachinePassRegistry RegisterScheduler::Registry;
103 //===---------------------------------------------------------------------===//
105 /// ISHeuristic command line option for instruction schedulers.
107 //===---------------------------------------------------------------------===//
108 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
109 RegisterPassParser<RegisterScheduler> >
110 ISHeuristic("pre-RA-sched",
111 cl::init(&createDefaultScheduler),
112 cl::desc("Instruction schedulers available (before register"
115 static RegisterScheduler
116 defaultListDAGScheduler("default", " Best scheduler for the target",
117 createDefaultScheduler);
119 namespace { struct SDISelAsmOperandInfo; }
121 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
122 /// insertvalue or extractvalue indices that identify a member, return
123 /// the linearized index of the start of the member.
125 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
126 const unsigned *Indices,
127 const unsigned *IndicesEnd,
128 unsigned CurIndex = 0) {
129 // Base case: We're done.
130 if (Indices && Indices == IndicesEnd)
133 // Given a struct type, recursively traverse the elements.
134 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
135 for (StructType::element_iterator EB = STy->element_begin(),
137 EE = STy->element_end();
139 if (Indices && *Indices == unsigned(EI - EB))
140 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
141 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
144 // Given an array type, recursively traverse the elements.
145 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
146 const Type *EltTy = ATy->getElementType();
147 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
148 if (Indices && *Indices == i)
149 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
150 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
153 // We haven't found the type we're looking for, so keep searching.
157 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
158 /// MVTs that represent all the individual underlying
159 /// non-aggregate types that comprise it.
161 /// If Offsets is non-null, it points to a vector to be filled in
162 /// with the in-memory offsets of each of the individual values.
164 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
165 SmallVectorImpl<MVT> &ValueVTs,
166 SmallVectorImpl<uint64_t> *Offsets = 0,
167 uint64_t StartingOffset = 0) {
168 // Given a struct type, recursively traverse the elements.
169 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
170 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
171 for (StructType::element_iterator EB = STy->element_begin(),
173 EE = STy->element_end();
175 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
176 StartingOffset + SL->getElementOffset(EI - EB));
179 // Given an array type, recursively traverse the elements.
180 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
181 const Type *EltTy = ATy->getElementType();
182 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
183 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
184 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
185 StartingOffset + i * EltSize);
188 // Base case: we can get an MVT for this LLVM IR type.
189 ValueVTs.push_back(TLI.getValueType(Ty));
191 Offsets->push_back(StartingOffset);
195 /// RegsForValue - This struct represents the registers (physical or virtual)
196 /// that a particular set of values is assigned, and the type information about
197 /// the value. The most common situation is to represent one value at a time,
198 /// but struct or array values are handled element-wise as multiple values.
199 /// The splitting of aggregates is performed recursively, so that we never
200 /// have aggregate-typed registers. The values at this point do not necessarily
201 /// have legal types, so each value may require one or more registers of some
204 struct VISIBILITY_HIDDEN RegsForValue {
205 /// TLI - The TargetLowering object.
207 const TargetLowering *TLI;
209 /// ValueVTs - The value types of the values, which may not be legal, and
210 /// may need be promoted or synthesized from one or more registers.
212 SmallVector<MVT, 4> ValueVTs;
214 /// RegVTs - The value types of the registers. This is the same size as
215 /// ValueVTs and it records, for each value, what the type of the assigned
216 /// register or registers are. (Individual values are never synthesized
217 /// from more than one type of register.)
219 /// With virtual registers, the contents of RegVTs is redundant with TLI's
220 /// getRegisterType member function, however when with physical registers
221 /// it is necessary to have a separate record of the types.
223 SmallVector<MVT, 4> RegVTs;
225 /// Regs - This list holds the registers assigned to the values.
226 /// Each legal or promoted value requires one register, and each
227 /// expanded value requires multiple registers.
229 SmallVector<unsigned, 4> Regs;
231 RegsForValue() : TLI(0) {}
233 RegsForValue(const TargetLowering &tli,
234 const SmallVector<unsigned, 4> ®s,
235 MVT regvt, MVT valuevt)
236 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
237 RegsForValue(const TargetLowering &tli,
238 const SmallVector<unsigned, 4> ®s,
239 const SmallVector<MVT, 4> ®vts,
240 const SmallVector<MVT, 4> &valuevts)
241 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
242 RegsForValue(const TargetLowering &tli,
243 unsigned Reg, const Type *Ty) : TLI(&tli) {
244 ComputeValueVTs(tli, Ty, ValueVTs);
246 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
247 MVT ValueVT = ValueVTs[Value];
248 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
249 MVT RegisterVT = TLI->getRegisterType(ValueVT);
250 for (unsigned i = 0; i != NumRegs; ++i)
251 Regs.push_back(Reg + i);
252 RegVTs.push_back(RegisterVT);
257 /// append - Add the specified values to this one.
258 void append(const RegsForValue &RHS) {
260 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
261 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
262 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
266 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
267 /// this value and returns the result as a ValueVTs value. This uses
268 /// Chain/Flag as the input and updates them for the output Chain/Flag.
269 /// If the Flag pointer is NULL, no flag is used.
270 SDValue getCopyFromRegs(SelectionDAG &DAG,
271 SDValue &Chain, SDValue *Flag) const;
273 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
274 /// specified value into the registers specified by this object. This uses
275 /// Chain/Flag as the input and updates them for the output Chain/Flag.
276 /// If the Flag pointer is NULL, no flag is used.
277 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
278 SDValue &Chain, SDValue *Flag) const;
280 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
281 /// operand list. This adds the code marker and includes the number of
282 /// values added into it.
283 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
284 std::vector<SDValue> &Ops) const;
289 //===--------------------------------------------------------------------===//
290 /// createDefaultScheduler - This creates an instruction scheduler appropriate
292 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
294 MachineBasicBlock *BB,
296 TargetLowering &TLI = IS->getTargetLowering();
298 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
299 return createTDListDAGScheduler(IS, DAG, BB, Fast);
301 assert(TLI.getSchedulingPreference() ==
302 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
303 return createBURRListDAGScheduler(IS, DAG, BB, Fast);
308 //===--------------------------------------------------------------------===//
309 /// FunctionLoweringInfo - This contains information that is global to a
310 /// function that is used when lowering a region of the function.
311 class FunctionLoweringInfo {
316 MachineRegisterInfo &RegInfo;
318 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
320 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
321 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
323 /// ValueMap - Since we emit code for the function a basic block at a time,
324 /// we must remember which virtual registers hold the values for
325 /// cross-basic-block values.
326 DenseMap<const Value*, unsigned> ValueMap;
328 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
329 /// the entry block. This allows the allocas to be efficiently referenced
330 /// anywhere in the function.
331 std::map<const AllocaInst*, int> StaticAllocaMap;
334 SmallSet<Instruction*, 8> CatchInfoLost;
335 SmallSet<Instruction*, 8> CatchInfoFound;
338 unsigned MakeReg(MVT VT) {
339 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
342 /// isExportedInst - Return true if the specified value is an instruction
343 /// exported from its block.
344 bool isExportedInst(const Value *V) {
345 return ValueMap.count(V);
348 unsigned CreateRegForValue(const Value *V);
350 unsigned InitializeRegForValue(const Value *V) {
351 unsigned &R = ValueMap[V];
352 assert(R == 0 && "Already initialized this value register!");
353 return R = CreateRegForValue(V);
357 unsigned NumSignBits;
358 APInt KnownOne, KnownZero;
359 LiveOutInfo() : NumSignBits(0) {}
362 /// LiveOutRegInfo - Information about live out vregs, indexed by their
363 /// register number offset by 'FirstVirtualRegister'.
364 std::vector<LiveOutInfo> LiveOutRegInfo;
368 /// isSelector - Return true if this instruction is a call to the
369 /// eh.selector intrinsic.
370 static bool isSelector(Instruction *I) {
371 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
372 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
373 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
377 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
378 /// PHI nodes or outside of the basic block that defines it, or used by a
379 /// switch or atomic instruction, which may expand to multiple basic blocks.
380 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
381 if (isa<PHINode>(I)) return true;
382 BasicBlock *BB = I->getParent();
383 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
384 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
385 // FIXME: Remove switchinst special case.
386 isa<SwitchInst>(*UI))
391 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
392 /// entry block, return true. This includes arguments used by switches, since
393 /// the switch may expand into multiple basic blocks.
394 static bool isOnlyUsedInEntryBlock(Argument *A) {
395 BasicBlock *Entry = A->getParent()->begin();
396 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
397 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
398 return false; // Use not in entry block.
402 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
403 Function &fn, MachineFunction &mf)
404 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
406 // Create a vreg for each argument register that is not dead and is used
407 // outside of the entry block for the function.
408 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
410 if (!isOnlyUsedInEntryBlock(AI))
411 InitializeRegForValue(AI);
413 // Initialize the mapping of values to registers. This is only set up for
414 // instruction values that are used outside of the block that defines
416 Function::iterator BB = Fn.begin(), EB = Fn.end();
417 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
418 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
419 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
420 const Type *Ty = AI->getAllocatedType();
421 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
423 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
426 TySize *= CUI->getZExtValue(); // Get total allocated size.
427 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
428 StaticAllocaMap[AI] =
429 MF.getFrameInfo()->CreateStackObject(TySize, Align);
432 for (; BB != EB; ++BB)
433 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
434 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
435 if (!isa<AllocaInst>(I) ||
436 !StaticAllocaMap.count(cast<AllocaInst>(I)))
437 InitializeRegForValue(I);
439 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
440 // also creates the initial PHI MachineInstrs, though none of the input
441 // operands are populated.
442 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
443 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
447 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
450 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
451 if (PN->use_empty()) continue;
453 unsigned PHIReg = ValueMap[PN];
454 assert(PHIReg && "PHI node does not have an assigned virtual register!");
456 SmallVector<MVT, 4> ValueVTs;
457 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
458 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
459 MVT VT = ValueVTs[vti];
460 unsigned NumRegisters = TLI.getNumRegisters(VT);
461 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
462 for (unsigned i = 0; i != NumRegisters; ++i)
463 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
464 PHIReg += NumRegisters;
470 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
471 /// the correctly promoted or expanded types. Assign these registers
472 /// consecutive vreg numbers and return the first assigned number.
474 /// In the case that the given value has struct or array type, this function
475 /// will assign registers for each member or element.
477 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
478 SmallVector<MVT, 4> ValueVTs;
479 ComputeValueVTs(TLI, V->getType(), ValueVTs);
481 unsigned FirstReg = 0;
482 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
483 MVT ValueVT = ValueVTs[Value];
484 MVT RegisterVT = TLI.getRegisterType(ValueVT);
486 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
487 for (unsigned i = 0; i != NumRegs; ++i) {
488 unsigned R = MakeReg(RegisterVT);
489 if (!FirstReg) FirstReg = R;
495 //===----------------------------------------------------------------------===//
496 /// SelectionDAGLowering - This is the common target-independent lowering
497 /// implementation that is parameterized by a TargetLowering object.
498 /// Also, targets can overload any lowering method.
501 class SelectionDAGLowering {
502 MachineBasicBlock *CurMBB;
504 DenseMap<const Value*, SDValue> NodeMap;
506 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
507 /// them up and then emit token factor nodes when possible. This allows us to
508 /// get simple disambiguation between loads without worrying about alias
510 SmallVector<SDValue, 8> PendingLoads;
512 /// PendingExports - CopyToReg nodes that copy values to virtual registers
513 /// for export to other blocks need to be emitted before any terminator
514 /// instruction, but they have no other ordering requirements. We bunch them
515 /// up and the emit a single tokenfactor for them just before terminator
517 std::vector<SDValue> PendingExports;
519 /// Case - A struct to record the Value for a switch case, and the
520 /// case's target basic block.
524 MachineBasicBlock* BB;
526 Case() : Low(0), High(0), BB(0) { }
527 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
528 Low(low), High(high), BB(bb) { }
529 uint64_t size() const {
530 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
531 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
532 return (rHigh - rLow + 1ULL);
538 MachineBasicBlock* BB;
541 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
542 Mask(mask), BB(bb), Bits(bits) { }
545 typedef std::vector<Case> CaseVector;
546 typedef std::vector<CaseBits> CaseBitsVector;
547 typedef CaseVector::iterator CaseItr;
548 typedef std::pair<CaseItr, CaseItr> CaseRange;
550 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
551 /// of conditional branches.
553 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
554 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
556 /// CaseBB - The MBB in which to emit the compare and branch
557 MachineBasicBlock *CaseBB;
558 /// LT, GE - If nonzero, we know the current case value must be less-than or
559 /// greater-than-or-equal-to these Constants.
562 /// Range - A pair of iterators representing the range of case values to be
563 /// processed at this point in the binary search tree.
567 typedef std::vector<CaseRec> CaseRecVector;
569 /// The comparison function for sorting the switch case values in the vector.
570 /// WARNING: Case ranges should be disjoint!
572 bool operator () (const Case& C1, const Case& C2) {
573 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
574 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
575 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
576 return CI1->getValue().slt(CI2->getValue());
581 bool operator () (const CaseBits& C1, const CaseBits& C2) {
582 return C1.Bits > C2.Bits;
586 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
589 // TLI - This is information that describes the available target features we
590 // need for lowering. This indicates when operations are unavailable,
591 // implemented with a libcall, etc.
594 const TargetData *TD;
597 /// SwitchCases - Vector of CaseBlock structures used to communicate
598 /// SwitchInst code generation information.
599 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
600 /// JTCases - Vector of JumpTable structures used to communicate
601 /// SwitchInst code generation information.
602 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
603 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
605 /// FuncInfo - Information about the function as a whole.
607 FunctionLoweringInfo &FuncInfo;
609 /// GFI - Garbage collection metadata for the function.
612 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
614 FunctionLoweringInfo &funcinfo,
616 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
617 FuncInfo(funcinfo), GFI(gfi) {
620 /// getRoot - Return the current virtual root of the Selection DAG,
621 /// flushing any PendingLoad items. This must be done before emitting
622 /// a store or any other node that may need to be ordered after any
623 /// prior load instructions.
626 if (PendingLoads.empty())
627 return DAG.getRoot();
629 if (PendingLoads.size() == 1) {
630 SDValue Root = PendingLoads[0];
632 PendingLoads.clear();
636 // Otherwise, we have to make a token factor node.
637 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
638 &PendingLoads[0], PendingLoads.size());
639 PendingLoads.clear();
644 /// getControlRoot - Similar to getRoot, but instead of flushing all the
645 /// PendingLoad items, flush all the PendingExports items. It is necessary
646 /// to do this before emitting a terminator instruction.
648 SDValue getControlRoot() {
649 SDValue Root = DAG.getRoot();
651 if (PendingExports.empty())
654 // Turn all of the CopyToReg chains into one factored node.
655 if (Root.getOpcode() != ISD::EntryToken) {
656 unsigned i = 0, e = PendingExports.size();
657 for (; i != e; ++i) {
658 assert(PendingExports[i].Val->getNumOperands() > 1);
659 if (PendingExports[i].Val->getOperand(0) == Root)
660 break; // Don't add the root if we already indirectly depend on it.
664 PendingExports.push_back(Root);
667 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
669 PendingExports.size());
670 PendingExports.clear();
675 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
677 void visit(Instruction &I) { visit(I.getOpcode(), I); }
679 void visit(unsigned Opcode, User &I) {
680 // Note: this doesn't use InstVisitor, because it has to work with
681 // ConstantExpr's in addition to instructions.
683 default: assert(0 && "Unknown instruction type encountered!");
685 // Build the switch statement using the Instruction.def file.
686 #define HANDLE_INST(NUM, OPCODE, CLASS) \
687 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
688 #include "llvm/Instruction.def"
692 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
694 SDValue getValue(const Value *V);
696 void setValue(const Value *V, SDValue NewN) {
697 SDValue &N = NodeMap[V];
698 assert(N.Val == 0 && "Already set a value for this node!");
702 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
703 std::set<unsigned> &OutputRegs,
704 std::set<unsigned> &InputRegs);
706 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
707 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
709 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
710 void ExportFromCurrentBlock(Value *V);
711 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
712 MachineBasicBlock *LandingPad = NULL);
714 // Terminator instructions.
715 void visitRet(ReturnInst &I);
716 void visitBr(BranchInst &I);
717 void visitSwitch(SwitchInst &I);
718 void visitUnreachable(UnreachableInst &I) { /* noop */ }
720 // Helpers for visitSwitch
721 bool handleSmallSwitchRange(CaseRec& CR,
722 CaseRecVector& WorkList,
724 MachineBasicBlock* Default);
725 bool handleJTSwitchCase(CaseRec& CR,
726 CaseRecVector& WorkList,
728 MachineBasicBlock* Default);
729 bool handleBTSplitSwitchCase(CaseRec& CR,
730 CaseRecVector& WorkList,
732 MachineBasicBlock* Default);
733 bool handleBitTestsSwitchCase(CaseRec& CR,
734 CaseRecVector& WorkList,
736 MachineBasicBlock* Default);
737 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
738 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
739 void visitBitTestCase(MachineBasicBlock* NextMBB,
741 SelectionDAGISel::BitTestCase &B);
742 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
743 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
744 SelectionDAGISel::JumpTableHeader &JTH);
746 // These all get lowered before this pass.
747 void visitInvoke(InvokeInst &I);
748 void visitUnwind(UnwindInst &I);
750 void visitBinary(User &I, unsigned OpCode);
751 void visitShift(User &I, unsigned Opcode);
752 void visitAdd(User &I) {
753 if (I.getType()->isFPOrFPVector())
754 visitBinary(I, ISD::FADD);
756 visitBinary(I, ISD::ADD);
758 void visitSub(User &I);
759 void visitMul(User &I) {
760 if (I.getType()->isFPOrFPVector())
761 visitBinary(I, ISD::FMUL);
763 visitBinary(I, ISD::MUL);
765 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
766 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
767 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
768 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
769 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
770 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
771 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
772 void visitOr (User &I) { visitBinary(I, ISD::OR); }
773 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
774 void visitShl (User &I) { visitShift(I, ISD::SHL); }
775 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
776 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
777 void visitICmp(User &I);
778 void visitFCmp(User &I);
779 void visitVICmp(User &I);
780 void visitVFCmp(User &I);
781 // Visit the conversion instructions
782 void visitTrunc(User &I);
783 void visitZExt(User &I);
784 void visitSExt(User &I);
785 void visitFPTrunc(User &I);
786 void visitFPExt(User &I);
787 void visitFPToUI(User &I);
788 void visitFPToSI(User &I);
789 void visitUIToFP(User &I);
790 void visitSIToFP(User &I);
791 void visitPtrToInt(User &I);
792 void visitIntToPtr(User &I);
793 void visitBitCast(User &I);
795 void visitExtractElement(User &I);
796 void visitInsertElement(User &I);
797 void visitShuffleVector(User &I);
799 void visitExtractValue(ExtractValueInst &I);
800 void visitInsertValue(InsertValueInst &I);
802 void visitGetElementPtr(User &I);
803 void visitSelect(User &I);
805 void visitMalloc(MallocInst &I);
806 void visitFree(FreeInst &I);
807 void visitAlloca(AllocaInst &I);
808 void visitLoad(LoadInst &I);
809 void visitStore(StoreInst &I);
810 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
811 void visitCall(CallInst &I);
812 void visitInlineAsm(CallSite CS);
813 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
814 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
816 void visitVAStart(CallInst &I);
817 void visitVAArg(VAArgInst &I);
818 void visitVAEnd(CallInst &I);
819 void visitVACopy(CallInst &I);
821 void visitUserOp1(Instruction &I) {
822 assert(0 && "UserOp1 should not exist at instruction selection time!");
825 void visitUserOp2(Instruction &I) {
826 assert(0 && "UserOp2 should not exist at instruction selection time!");
831 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
834 } // end namespace llvm
837 /// getCopyFromParts - Create a value that contains the specified legal parts
838 /// combined into the value they represent. If the parts combine to a type
839 /// larger then ValueVT then AssertOp can be used to specify whether the extra
840 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
841 /// (ISD::AssertSext).
842 static SDValue getCopyFromParts(SelectionDAG &DAG,
843 const SDValue *Parts,
847 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
848 assert(NumParts > 0 && "No parts to assemble!");
849 TargetLowering &TLI = DAG.getTargetLoweringInfo();
850 SDValue Val = Parts[0];
853 // Assemble the value from multiple parts.
854 if (!ValueVT.isVector()) {
855 unsigned PartBits = PartVT.getSizeInBits();
856 unsigned ValueBits = ValueVT.getSizeInBits();
858 // Assemble the power of 2 part.
859 unsigned RoundParts = NumParts & (NumParts - 1) ?
860 1 << Log2_32(NumParts) : NumParts;
861 unsigned RoundBits = PartBits * RoundParts;
862 MVT RoundVT = RoundBits == ValueBits ?
863 ValueVT : MVT::getIntegerVT(RoundBits);
866 if (RoundParts > 2) {
867 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
868 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
869 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
875 if (TLI.isBigEndian())
877 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
879 if (RoundParts < NumParts) {
880 // Assemble the trailing non-power-of-2 part.
881 unsigned OddParts = NumParts - RoundParts;
882 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
883 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
885 // Combine the round and odd parts.
887 if (TLI.isBigEndian())
889 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
890 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
891 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
892 DAG.getConstant(Lo.getValueType().getSizeInBits(),
893 TLI.getShiftAmountTy()));
894 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
895 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
898 // Handle a multi-element vector.
899 MVT IntermediateVT, RegisterVT;
900 unsigned NumIntermediates;
902 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
904 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
905 NumParts = NumRegs; // Silence a compiler warning.
906 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
907 assert(RegisterVT == Parts[0].getValueType() &&
908 "Part type doesn't match part!");
910 // Assemble the parts into intermediate operands.
911 SmallVector<SDValue, 8> Ops(NumIntermediates);
912 if (NumIntermediates == NumParts) {
913 // If the register was not expanded, truncate or copy the value,
915 for (unsigned i = 0; i != NumParts; ++i)
916 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
917 PartVT, IntermediateVT);
918 } else if (NumParts > 0) {
919 // If the intermediate type was expanded, build the intermediate operands
921 assert(NumParts % NumIntermediates == 0 &&
922 "Must expand into a divisible number of parts!");
923 unsigned Factor = NumParts / NumIntermediates;
924 for (unsigned i = 0; i != NumIntermediates; ++i)
925 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
926 PartVT, IntermediateVT);
929 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
931 Val = DAG.getNode(IntermediateVT.isVector() ?
932 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
933 ValueVT, &Ops[0], NumIntermediates);
937 // There is now one part, held in Val. Correct it to match ValueVT.
938 PartVT = Val.getValueType();
940 if (PartVT == ValueVT)
943 if (PartVT.isVector()) {
944 assert(ValueVT.isVector() && "Unknown vector conversion!");
945 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
948 if (ValueVT.isVector()) {
949 assert(ValueVT.getVectorElementType() == PartVT &&
950 ValueVT.getVectorNumElements() == 1 &&
951 "Only trivial scalar-to-vector conversions should get here!");
952 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
955 if (PartVT.isInteger() &&
956 ValueVT.isInteger()) {
957 if (ValueVT.bitsLT(PartVT)) {
958 // For a truncate, see if we have any information to
959 // indicate whether the truncated bits will always be
960 // zero or sign-extension.
961 if (AssertOp != ISD::DELETED_NODE)
962 Val = DAG.getNode(AssertOp, PartVT, Val,
963 DAG.getValueType(ValueVT));
964 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
966 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
970 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
971 if (ValueVT.bitsLT(Val.getValueType()))
972 // FP_ROUND's are always exact here.
973 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
974 DAG.getIntPtrConstant(1));
975 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
978 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
979 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
981 assert(0 && "Unknown mismatch!");
985 /// getCopyToParts - Create a series of nodes that contain the specified value
986 /// split into legal parts. If the parts contain more bits than Val, then, for
987 /// integers, ExtendKind can be used to specify how to generate the extra bits.
988 static void getCopyToParts(SelectionDAG &DAG,
993 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
994 TargetLowering &TLI = DAG.getTargetLoweringInfo();
995 MVT PtrVT = TLI.getPointerTy();
996 MVT ValueVT = Val.getValueType();
997 unsigned PartBits = PartVT.getSizeInBits();
998 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
1003 if (!ValueVT.isVector()) {
1004 if (PartVT == ValueVT) {
1005 assert(NumParts == 1 && "No-op copy with multiple parts!");
1010 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
1011 // If the parts cover more bits than the value has, promote the value.
1012 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
1013 assert(NumParts == 1 && "Do not know what to promote to!");
1014 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
1015 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
1016 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
1017 Val = DAG.getNode(ExtendKind, ValueVT, Val);
1019 assert(0 && "Unknown mismatch!");
1021 } else if (PartBits == ValueVT.getSizeInBits()) {
1022 // Different types of the same size.
1023 assert(NumParts == 1 && PartVT != ValueVT);
1024 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1025 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
1026 // If the parts cover less bits than value has, truncate the value.
1027 if (PartVT.isInteger() && ValueVT.isInteger()) {
1028 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
1029 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1031 assert(0 && "Unknown mismatch!");
1035 // The value may have changed - recompute ValueVT.
1036 ValueVT = Val.getValueType();
1037 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
1038 "Failed to tile the value with PartVT!");
1040 if (NumParts == 1) {
1041 assert(PartVT == ValueVT && "Type conversion failed!");
1046 // Expand the value into multiple parts.
1047 if (NumParts & (NumParts - 1)) {
1048 // The number of parts is not a power of 2. Split off and copy the tail.
1049 assert(PartVT.isInteger() && ValueVT.isInteger() &&
1050 "Do not know what to expand to!");
1051 unsigned RoundParts = 1 << Log2_32(NumParts);
1052 unsigned RoundBits = RoundParts * PartBits;
1053 unsigned OddParts = NumParts - RoundParts;
1054 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
1055 DAG.getConstant(RoundBits,
1056 TLI.getShiftAmountTy()));
1057 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1058 if (TLI.isBigEndian())
1059 // The odd parts were reversed by getCopyToParts - unreverse them.
1060 std::reverse(Parts + RoundParts, Parts + NumParts);
1061 NumParts = RoundParts;
1062 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
1063 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1066 // The number of parts is a power of 2. Repeatedly bisect the value using
1068 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
1069 MVT::getIntegerVT(ValueVT.getSizeInBits()),
1071 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1072 for (unsigned i = 0; i < NumParts; i += StepSize) {
1073 unsigned ThisBits = StepSize * PartBits / 2;
1074 MVT ThisVT = MVT::getIntegerVT (ThisBits);
1075 SDValue &Part0 = Parts[i];
1076 SDValue &Part1 = Parts[i+StepSize/2];
1078 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1079 DAG.getConstant(1, PtrVT));
1080 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1081 DAG.getConstant(0, PtrVT));
1083 if (ThisBits == PartBits && ThisVT != PartVT) {
1084 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1085 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1090 if (TLI.isBigEndian())
1091 std::reverse(Parts, Parts + NumParts);
1097 if (NumParts == 1) {
1098 if (PartVT != ValueVT) {
1099 if (PartVT.isVector()) {
1100 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1102 assert(ValueVT.getVectorElementType() == PartVT &&
1103 ValueVT.getVectorNumElements() == 1 &&
1104 "Only trivial vector-to-scalar conversions should get here!");
1105 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1106 DAG.getConstant(0, PtrVT));
1114 // Handle a multi-element vector.
1115 MVT IntermediateVT, RegisterVT;
1116 unsigned NumIntermediates;
1118 DAG.getTargetLoweringInfo()
1119 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1121 unsigned NumElements = ValueVT.getVectorNumElements();
1123 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1124 NumParts = NumRegs; // Silence a compiler warning.
1125 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1127 // Split the vector into intermediate operands.
1128 SmallVector<SDValue, 8> Ops(NumIntermediates);
1129 for (unsigned i = 0; i != NumIntermediates; ++i)
1130 if (IntermediateVT.isVector())
1131 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1132 IntermediateVT, Val,
1133 DAG.getConstant(i * (NumElements / NumIntermediates),
1136 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1137 IntermediateVT, Val,
1138 DAG.getConstant(i, PtrVT));
1140 // Split the intermediate operands into legal parts.
1141 if (NumParts == NumIntermediates) {
1142 // If the register was not expanded, promote or copy the value,
1144 for (unsigned i = 0; i != NumParts; ++i)
1145 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1146 } else if (NumParts > 0) {
1147 // If the intermediate type was expanded, split each the value into
1149 assert(NumParts % NumIntermediates == 0 &&
1150 "Must expand into a divisible number of parts!");
1151 unsigned Factor = NumParts / NumIntermediates;
1152 for (unsigned i = 0; i != NumIntermediates; ++i)
1153 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1158 SDValue SelectionDAGLowering::getValue(const Value *V) {
1159 SDValue &N = NodeMap[V];
1160 if (N.Val) return N;
1162 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1163 MVT VT = TLI.getValueType(V->getType(), true);
1165 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1166 return N = DAG.getConstant(CI->getValue(), VT);
1168 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1169 return N = DAG.getGlobalAddress(GV, VT);
1171 if (isa<ConstantPointerNull>(C))
1172 return N = DAG.getConstant(0, TLI.getPointerTy());
1174 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1175 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1177 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1178 !V->getType()->isAggregateType())
1179 return N = DAG.getNode(ISD::UNDEF, VT);
1181 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1182 visit(CE->getOpcode(), *CE);
1183 SDValue N1 = NodeMap[V];
1184 assert(N1.Val && "visit didn't populate the ValueMap!");
1188 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1189 SmallVector<SDValue, 4> Constants;
1190 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1192 SDNode *Val = getValue(*OI).Val;
1193 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1194 Constants.push_back(SDValue(Val, i));
1196 return DAG.getMergeValues(&Constants[0], Constants.size());
1199 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
1200 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1201 "Unknown struct or array constant!");
1203 SmallVector<MVT, 4> ValueVTs;
1204 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1205 unsigned NumElts = ValueVTs.size();
1207 return SDValue(); // empty struct
1208 SmallVector<SDValue, 4> Constants(NumElts);
1209 for (unsigned i = 0; i != NumElts; ++i) {
1210 MVT EltVT = ValueVTs[i];
1211 if (isa<UndefValue>(C))
1212 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1213 else if (EltVT.isFloatingPoint())
1214 Constants[i] = DAG.getConstantFP(0, EltVT);
1216 Constants[i] = DAG.getConstant(0, EltVT);
1218 return DAG.getMergeValues(&Constants[0], NumElts);
1221 const VectorType *VecTy = cast<VectorType>(V->getType());
1222 unsigned NumElements = VecTy->getNumElements();
1224 // Now that we know the number and type of the elements, get that number of
1225 // elements into the Ops array based on what kind of constant it is.
1226 SmallVector<SDValue, 16> Ops;
1227 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1228 for (unsigned i = 0; i != NumElements; ++i)
1229 Ops.push_back(getValue(CP->getOperand(i)));
1231 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1232 "Unknown vector constant!");
1233 MVT EltVT = TLI.getValueType(VecTy->getElementType());
1236 if (isa<UndefValue>(C))
1237 Op = DAG.getNode(ISD::UNDEF, EltVT);
1238 else if (EltVT.isFloatingPoint())
1239 Op = DAG.getConstantFP(0, EltVT);
1241 Op = DAG.getConstant(0, EltVT);
1242 Ops.assign(NumElements, Op);
1245 // Create a BUILD_VECTOR node.
1246 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1249 // If this is a static alloca, generate it as the frameindex instead of
1251 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1252 std::map<const AllocaInst*, int>::iterator SI =
1253 FuncInfo.StaticAllocaMap.find(AI);
1254 if (SI != FuncInfo.StaticAllocaMap.end())
1255 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1258 unsigned InReg = FuncInfo.ValueMap[V];
1259 assert(InReg && "Value not in map!");
1261 RegsForValue RFV(TLI, InReg, V->getType());
1262 SDValue Chain = DAG.getEntryNode();
1263 return RFV.getCopyFromRegs(DAG, Chain, NULL);
1267 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1268 if (I.getNumOperands() == 0) {
1269 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1273 SmallVector<SDValue, 8> NewValues;
1274 NewValues.push_back(getControlRoot());
1275 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1276 SDValue RetOp = getValue(I.getOperand(i));
1278 SmallVector<MVT, 4> ValueVTs;
1279 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1280 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
1281 MVT VT = ValueVTs[j];
1283 // FIXME: C calling convention requires the return type to be promoted to
1284 // at least 32-bit. But this is not necessary for non-C calling conventions.
1285 if (VT.isInteger()) {
1286 MVT MinVT = TLI.getRegisterType(MVT::i32);
1287 if (VT.bitsLT(MinVT))
1291 unsigned NumParts = TLI.getNumRegisters(VT);
1292 MVT PartVT = TLI.getRegisterType(VT);
1293 SmallVector<SDValue, 4> Parts(NumParts);
1294 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1296 const Function *F = I.getParent()->getParent();
1297 if (F->paramHasAttr(0, ParamAttr::SExt))
1298 ExtendKind = ISD::SIGN_EXTEND;
1299 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1300 ExtendKind = ISD::ZERO_EXTEND;
1302 getCopyToParts(DAG, SDValue(RetOp.Val, RetOp.ResNo + j),
1303 &Parts[0], NumParts, PartVT, ExtendKind);
1305 for (unsigned i = 0; i < NumParts; ++i) {
1306 NewValues.push_back(Parts[i]);
1307 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1311 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1312 &NewValues[0], NewValues.size()));
1315 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1316 /// the current basic block, add it to ValueMap now so that we'll get a
1318 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1319 // No need to export constants.
1320 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1322 // Already exported?
1323 if (FuncInfo.isExportedInst(V)) return;
1325 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1326 CopyValueToVirtualRegister(V, Reg);
1329 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1330 const BasicBlock *FromBB) {
1331 // The operands of the setcc have to be in this block. We don't know
1332 // how to export them from some other block.
1333 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1334 // Can export from current BB.
1335 if (VI->getParent() == FromBB)
1338 // Is already exported, noop.
1339 return FuncInfo.isExportedInst(V);
1342 // If this is an argument, we can export it if the BB is the entry block or
1343 // if it is already exported.
1344 if (isa<Argument>(V)) {
1345 if (FromBB == &FromBB->getParent()->getEntryBlock())
1348 // Otherwise, can only export this if it is already exported.
1349 return FuncInfo.isExportedInst(V);
1352 // Otherwise, constants can always be exported.
1356 static bool InBlock(const Value *V, const BasicBlock *BB) {
1357 if (const Instruction *I = dyn_cast<Instruction>(V))
1358 return I->getParent() == BB;
1362 /// FindMergedConditions - If Cond is an expression like
1363 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1364 MachineBasicBlock *TBB,
1365 MachineBasicBlock *FBB,
1366 MachineBasicBlock *CurBB,
1368 // If this node is not part of the or/and tree, emit it as a branch.
1369 Instruction *BOp = dyn_cast<Instruction>(Cond);
1371 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1372 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1373 BOp->getParent() != CurBB->getBasicBlock() ||
1374 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1375 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1376 const BasicBlock *BB = CurBB->getBasicBlock();
1378 // If the leaf of the tree is a comparison, merge the condition into
1380 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1381 // The operands of the cmp have to be in this block. We don't know
1382 // how to export them from some other block. If this is the first block
1383 // of the sequence, no exporting is needed.
1385 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1386 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1387 BOp = cast<Instruction>(Cond);
1388 ISD::CondCode Condition;
1389 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1390 switch (IC->getPredicate()) {
1391 default: assert(0 && "Unknown icmp predicate opcode!");
1392 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1393 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1394 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1395 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1396 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1397 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1398 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1399 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1400 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1401 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1403 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1404 ISD::CondCode FPC, FOC;
1405 switch (FC->getPredicate()) {
1406 default: assert(0 && "Unknown fcmp predicate opcode!");
1407 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1408 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1409 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1410 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1411 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1412 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1413 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1414 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1415 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1416 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1417 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1418 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1419 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1420 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1421 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1422 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1424 if (FiniteOnlyFPMath())
1429 Condition = ISD::SETEQ; // silence warning.
1430 assert(0 && "Unknown compare instruction");
1433 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1434 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1435 SwitchCases.push_back(CB);
1439 // Create a CaseBlock record representing this branch.
1440 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1441 NULL, TBB, FBB, CurBB);
1442 SwitchCases.push_back(CB);
1447 // Create TmpBB after CurBB.
1448 MachineFunction::iterator BBI = CurBB;
1449 MachineFunction &MF = DAG.getMachineFunction();
1450 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1451 CurBB->getParent()->insert(++BBI, TmpBB);
1453 if (Opc == Instruction::Or) {
1454 // Codegen X | Y as:
1462 // Emit the LHS condition.
1463 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1465 // Emit the RHS condition into TmpBB.
1466 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1468 assert(Opc == Instruction::And && "Unknown merge op!");
1469 // Codegen X & Y as:
1476 // This requires creation of TmpBB after CurBB.
1478 // Emit the LHS condition.
1479 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1481 // Emit the RHS condition into TmpBB.
1482 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1486 /// If the set of cases should be emitted as a series of branches, return true.
1487 /// If we should emit this as a bunch of and/or'd together conditions, return
1490 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1491 if (Cases.size() != 2) return true;
1493 // If this is two comparisons of the same values or'd or and'd together, they
1494 // will get folded into a single comparison, so don't emit two blocks.
1495 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1496 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1497 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1498 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1505 void SelectionDAGLowering::visitBr(BranchInst &I) {
1506 // Update machine-CFG edges.
1507 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1509 // Figure out which block is immediately after the current one.
1510 MachineBasicBlock *NextBlock = 0;
1511 MachineFunction::iterator BBI = CurMBB;
1512 if (++BBI != CurMBB->getParent()->end())
1515 if (I.isUnconditional()) {
1516 // Update machine-CFG edges.
1517 CurMBB->addSuccessor(Succ0MBB);
1519 // If this is not a fall-through branch, emit the branch.
1520 if (Succ0MBB != NextBlock)
1521 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1522 DAG.getBasicBlock(Succ0MBB)));
1526 // If this condition is one of the special cases we handle, do special stuff
1528 Value *CondVal = I.getCondition();
1529 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1531 // If this is a series of conditions that are or'd or and'd together, emit
1532 // this as a sequence of branches instead of setcc's with and/or operations.
1533 // For example, instead of something like:
1546 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1547 if (BOp->hasOneUse() &&
1548 (BOp->getOpcode() == Instruction::And ||
1549 BOp->getOpcode() == Instruction::Or)) {
1550 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1551 // If the compares in later blocks need to use values not currently
1552 // exported from this block, export them now. This block should always
1553 // be the first entry.
1554 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1556 // Allow some cases to be rejected.
1557 if (ShouldEmitAsBranches(SwitchCases)) {
1558 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1559 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1560 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1563 // Emit the branch for this block.
1564 visitSwitchCase(SwitchCases[0]);
1565 SwitchCases.erase(SwitchCases.begin());
1569 // Okay, we decided not to do this, remove any inserted MBB's and clear
1571 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1572 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1574 SwitchCases.clear();
1578 // Create a CaseBlock record representing this branch.
1579 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1580 NULL, Succ0MBB, Succ1MBB, CurMBB);
1581 // Use visitSwitchCase to actually insert the fast branch sequence for this
1583 visitSwitchCase(CB);
1586 /// visitSwitchCase - Emits the necessary code to represent a single node in
1587 /// the binary search tree resulting from lowering a switch instruction.
1588 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1590 SDValue CondLHS = getValue(CB.CmpLHS);
1592 // Build the setcc now.
1593 if (CB.CmpMHS == NULL) {
1594 // Fold "(X == true)" to X and "(X == false)" to !X to
1595 // handle common cases produced by branch lowering.
1596 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1598 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1599 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1600 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1602 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1604 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1606 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1607 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1609 SDValue CmpOp = getValue(CB.CmpMHS);
1610 MVT VT = CmpOp.getValueType();
1612 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1613 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1615 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1616 Cond = DAG.getSetCC(MVT::i1, SUB,
1617 DAG.getConstant(High-Low, VT), ISD::SETULE);
1621 // Update successor info
1622 CurMBB->addSuccessor(CB.TrueBB);
1623 CurMBB->addSuccessor(CB.FalseBB);
1625 // Set NextBlock to be the MBB immediately after the current one, if any.
1626 // This is used to avoid emitting unnecessary branches to the next block.
1627 MachineBasicBlock *NextBlock = 0;
1628 MachineFunction::iterator BBI = CurMBB;
1629 if (++BBI != CurMBB->getParent()->end())
1632 // If the lhs block is the next block, invert the condition so that we can
1633 // fall through to the lhs instead of the rhs block.
1634 if (CB.TrueBB == NextBlock) {
1635 std::swap(CB.TrueBB, CB.FalseBB);
1636 SDValue True = DAG.getConstant(1, Cond.getValueType());
1637 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1639 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1640 DAG.getBasicBlock(CB.TrueBB));
1642 // If the branch was constant folded, fix up the CFG.
1643 if (BrCond.getOpcode() == ISD::BR) {
1644 CurMBB->removeSuccessor(CB.FalseBB);
1645 DAG.setRoot(BrCond);
1647 // Otherwise, go ahead and insert the false branch.
1648 if (BrCond == getControlRoot())
1649 CurMBB->removeSuccessor(CB.TrueBB);
1651 if (CB.FalseBB == NextBlock)
1652 DAG.setRoot(BrCond);
1654 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1655 DAG.getBasicBlock(CB.FalseBB)));
1659 /// visitJumpTable - Emit JumpTable node in the current MBB
1660 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1661 // Emit the code for the jump table
1662 assert(JT.Reg != -1U && "Should lower JT Header first!");
1663 MVT PTy = TLI.getPointerTy();
1664 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1665 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1666 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1671 /// visitJumpTableHeader - This function emits necessary code to produce index
1672 /// in the JumpTable from switch case.
1673 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1674 SelectionDAGISel::JumpTableHeader &JTH) {
1675 // Subtract the lowest switch case value from the value being switched on
1676 // and conditional branch to default mbb if the result is greater than the
1677 // difference between smallest and largest cases.
1678 SDValue SwitchOp = getValue(JTH.SValue);
1679 MVT VT = SwitchOp.getValueType();
1680 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1681 DAG.getConstant(JTH.First, VT));
1683 // The SDNode we just created, which holds the value being switched on
1684 // minus the the smallest case value, needs to be copied to a virtual
1685 // register so it can be used as an index into the jump table in a
1686 // subsequent basic block. This value may be smaller or larger than the
1687 // target's pointer type, and therefore require extension or truncating.
1688 if (VT.bitsGT(TLI.getPointerTy()))
1689 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1691 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1693 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1694 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1695 JT.Reg = JumpTableReg;
1697 // Emit the range check for the jump table, and branch to the default
1698 // block for the switch statement if the value being switched on exceeds
1699 // the largest case in the switch.
1700 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1701 DAG.getConstant(JTH.Last-JTH.First,VT),
1704 // Set NextBlock to be the MBB immediately after the current one, if any.
1705 // This is used to avoid emitting unnecessary branches to the next block.
1706 MachineBasicBlock *NextBlock = 0;
1707 MachineFunction::iterator BBI = CurMBB;
1708 if (++BBI != CurMBB->getParent()->end())
1711 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1712 DAG.getBasicBlock(JT.Default));
1714 if (JT.MBB == NextBlock)
1715 DAG.setRoot(BrCond);
1717 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1718 DAG.getBasicBlock(JT.MBB)));
1723 /// visitBitTestHeader - This function emits necessary code to produce value
1724 /// suitable for "bit tests"
1725 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1726 // Subtract the minimum value
1727 SDValue SwitchOp = getValue(B.SValue);
1728 MVT VT = SwitchOp.getValueType();
1729 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1730 DAG.getConstant(B.First, VT));
1733 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1734 DAG.getConstant(B.Range, VT),
1738 if (VT.bitsGT(TLI.getShiftAmountTy()))
1739 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1741 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1743 // Make desired shift
1744 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1745 DAG.getConstant(1, TLI.getPointerTy()),
1748 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1749 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1752 // Set NextBlock to be the MBB immediately after the current one, if any.
1753 // This is used to avoid emitting unnecessary branches to the next block.
1754 MachineBasicBlock *NextBlock = 0;
1755 MachineFunction::iterator BBI = CurMBB;
1756 if (++BBI != CurMBB->getParent()->end())
1759 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1761 CurMBB->addSuccessor(B.Default);
1762 CurMBB->addSuccessor(MBB);
1764 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1765 DAG.getBasicBlock(B.Default));
1767 if (MBB == NextBlock)
1768 DAG.setRoot(BrRange);
1770 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1771 DAG.getBasicBlock(MBB)));
1776 /// visitBitTestCase - this function produces one "bit test"
1777 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1779 SelectionDAGISel::BitTestCase &B) {
1780 // Emit bit tests and jumps
1781 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1782 TLI.getPointerTy());
1784 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1785 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1786 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1787 DAG.getConstant(0, TLI.getPointerTy()),
1790 CurMBB->addSuccessor(B.TargetBB);
1791 CurMBB->addSuccessor(NextMBB);
1793 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1794 AndCmp, DAG.getBasicBlock(B.TargetBB));
1796 // Set NextBlock to be the MBB immediately after the current one, if any.
1797 // This is used to avoid emitting unnecessary branches to the next block.
1798 MachineBasicBlock *NextBlock = 0;
1799 MachineFunction::iterator BBI = CurMBB;
1800 if (++BBI != CurMBB->getParent()->end())
1803 if (NextMBB == NextBlock)
1806 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1807 DAG.getBasicBlock(NextMBB)));
1812 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1813 // Retrieve successors.
1814 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1815 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1817 if (isa<InlineAsm>(I.getCalledValue()))
1820 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1822 // If the value of the invoke is used outside of its defining block, make it
1823 // available as a virtual register.
1824 if (!I.use_empty()) {
1825 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1826 if (VMI != FuncInfo.ValueMap.end())
1827 CopyValueToVirtualRegister(&I, VMI->second);
1830 // Update successor info
1831 CurMBB->addSuccessor(Return);
1832 CurMBB->addSuccessor(LandingPad);
1834 // Drop into normal successor.
1835 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1836 DAG.getBasicBlock(Return)));
1839 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1842 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1843 /// small case ranges).
1844 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1845 CaseRecVector& WorkList,
1847 MachineBasicBlock* Default) {
1848 Case& BackCase = *(CR.Range.second-1);
1850 // Size is the number of Cases represented by this range.
1851 unsigned Size = CR.Range.second - CR.Range.first;
1855 // Get the MachineFunction which holds the current MBB. This is used when
1856 // inserting any additional MBBs necessary to represent the switch.
1857 MachineFunction *CurMF = CurMBB->getParent();
1859 // Figure out which block is immediately after the current one.
1860 MachineBasicBlock *NextBlock = 0;
1861 MachineFunction::iterator BBI = CR.CaseBB;
1863 if (++BBI != CurMBB->getParent()->end())
1866 // TODO: If any two of the cases has the same destination, and if one value
1867 // is the same as the other, but has one bit unset that the other has set,
1868 // use bit manipulation to do two compares at once. For example:
1869 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1871 // Rearrange the case blocks so that the last one falls through if possible.
1872 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1873 // The last case block won't fall through into 'NextBlock' if we emit the
1874 // branches in this order. See if rearranging a case value would help.
1875 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1876 if (I->BB == NextBlock) {
1877 std::swap(*I, BackCase);
1883 // Create a CaseBlock record representing a conditional branch to
1884 // the Case's target mbb if the value being switched on SV is equal
1886 MachineBasicBlock *CurBlock = CR.CaseBB;
1887 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1888 MachineBasicBlock *FallThrough;
1890 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1891 CurMF->insert(BBI, FallThrough);
1893 // If the last case doesn't match, go to the default block.
1894 FallThrough = Default;
1897 Value *RHS, *LHS, *MHS;
1899 if (I->High == I->Low) {
1900 // This is just small small case range :) containing exactly 1 case
1902 LHS = SV; RHS = I->High; MHS = NULL;
1905 LHS = I->Low; MHS = SV; RHS = I->High;
1907 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1908 I->BB, FallThrough, CurBlock);
1910 // If emitting the first comparison, just call visitSwitchCase to emit the
1911 // code into the current block. Otherwise, push the CaseBlock onto the
1912 // vector to be later processed by SDISel, and insert the node's MBB
1913 // before the next MBB.
1914 if (CurBlock == CurMBB)
1915 visitSwitchCase(CB);
1917 SwitchCases.push_back(CB);
1919 CurBlock = FallThrough;
1925 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1926 return !DisableJumpTables &&
1927 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1928 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1931 /// handleJTSwitchCase - Emit jumptable for current switch case range
1932 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1933 CaseRecVector& WorkList,
1935 MachineBasicBlock* Default) {
1936 Case& FrontCase = *CR.Range.first;
1937 Case& BackCase = *(CR.Range.second-1);
1939 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1940 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1943 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1947 if (!areJTsAllowed(TLI) || TSize <= 3)
1950 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1954 DOUT << "Lowering jump table\n"
1955 << "First entry: " << First << ". Last entry: " << Last << "\n"
1956 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1958 // Get the MachineFunction which holds the current MBB. This is used when
1959 // inserting any additional MBBs necessary to represent the switch.
1960 MachineFunction *CurMF = CurMBB->getParent();
1962 // Figure out which block is immediately after the current one.
1963 MachineBasicBlock *NextBlock = 0;
1964 MachineFunction::iterator BBI = CR.CaseBB;
1966 if (++BBI != CurMBB->getParent()->end())
1969 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1971 // Create a new basic block to hold the code for loading the address
1972 // of the jump table, and jumping to it. Update successor information;
1973 // we will either branch to the default case for the switch, or the jump
1975 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1976 CurMF->insert(BBI, JumpTableBB);
1977 CR.CaseBB->addSuccessor(Default);
1978 CR.CaseBB->addSuccessor(JumpTableBB);
1980 // Build a vector of destination BBs, corresponding to each target
1981 // of the jump table. If the value of the jump table slot corresponds to
1982 // a case statement, push the case's BB onto the vector, otherwise, push
1984 std::vector<MachineBasicBlock*> DestBBs;
1985 int64_t TEI = First;
1986 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1987 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1988 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1990 if ((Low <= TEI) && (TEI <= High)) {
1991 DestBBs.push_back(I->BB);
1995 DestBBs.push_back(Default);
1999 // Update successor info. Add one edge to each unique successor.
2000 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2001 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2002 E = DestBBs.end(); I != E; ++I) {
2003 if (!SuccsHandled[(*I)->getNumber()]) {
2004 SuccsHandled[(*I)->getNumber()] = true;
2005 JumpTableBB->addSuccessor(*I);
2009 // Create a jump table index for this jump table, or return an existing
2011 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
2013 // Set the jump table information so that we can codegen it as a second
2014 // MachineBasicBlock
2015 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
2016 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
2017 (CR.CaseBB == CurMBB));
2018 if (CR.CaseBB == CurMBB)
2019 visitJumpTableHeader(JT, JTH);
2021 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
2026 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2028 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
2029 CaseRecVector& WorkList,
2031 MachineBasicBlock* Default) {
2032 // Get the MachineFunction which holds the current MBB. This is used when
2033 // inserting any additional MBBs necessary to represent the switch.
2034 MachineFunction *CurMF = CurMBB->getParent();
2036 // Figure out which block is immediately after the current one.
2037 MachineBasicBlock *NextBlock = 0;
2038 MachineFunction::iterator BBI = CR.CaseBB;
2040 if (++BBI != CurMBB->getParent()->end())
2043 Case& FrontCase = *CR.Range.first;
2044 Case& BackCase = *(CR.Range.second-1);
2045 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2047 // Size is the number of Cases represented by this range.
2048 unsigned Size = CR.Range.second - CR.Range.first;
2050 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2051 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
2053 CaseItr Pivot = CR.Range.first + Size/2;
2055 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2056 // (heuristically) allow us to emit JumpTable's later.
2058 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2062 uint64_t LSize = FrontCase.size();
2063 uint64_t RSize = TSize-LSize;
2064 DOUT << "Selecting best pivot: \n"
2065 << "First: " << First << ", Last: " << Last <<"\n"
2066 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
2067 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2069 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2070 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
2071 assert((RBegin-LEnd>=1) && "Invalid case distance");
2072 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2073 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
2074 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
2075 // Should always split in some non-trivial place
2077 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2078 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2079 << "Metric: " << Metric << "\n";
2080 if (FMetric < Metric) {
2083 DOUT << "Current metric set to: " << FMetric << "\n";
2089 if (areJTsAllowed(TLI)) {
2090 // If our case is dense we *really* should handle it earlier!
2091 assert((FMetric > 0) && "Should handle dense range earlier!");
2093 Pivot = CR.Range.first + Size/2;
2096 CaseRange LHSR(CR.Range.first, Pivot);
2097 CaseRange RHSR(Pivot, CR.Range.second);
2098 Constant *C = Pivot->Low;
2099 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2101 // We know that we branch to the LHS if the Value being switched on is
2102 // less than the Pivot value, C. We use this to optimize our binary
2103 // tree a bit, by recognizing that if SV is greater than or equal to the
2104 // LHS's Case Value, and that Case Value is exactly one less than the
2105 // Pivot's Value, then we can branch directly to the LHS's Target,
2106 // rather than creating a leaf node for it.
2107 if ((LHSR.second - LHSR.first) == 1 &&
2108 LHSR.first->High == CR.GE &&
2109 cast<ConstantInt>(C)->getSExtValue() ==
2110 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2111 TrueBB = LHSR.first->BB;
2113 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2114 CurMF->insert(BBI, TrueBB);
2115 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2118 // Similar to the optimization above, if the Value being switched on is
2119 // known to be less than the Constant CR.LT, and the current Case Value
2120 // is CR.LT - 1, then we can branch directly to the target block for
2121 // the current Case Value, rather than emitting a RHS leaf node for it.
2122 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2123 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2124 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2125 FalseBB = RHSR.first->BB;
2127 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2128 CurMF->insert(BBI, FalseBB);
2129 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2132 // Create a CaseBlock record representing a conditional branch to
2133 // the LHS node if the value being switched on SV is less than C.
2134 // Otherwise, branch to LHS.
2135 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
2136 TrueBB, FalseBB, CR.CaseBB);
2138 if (CR.CaseBB == CurMBB)
2139 visitSwitchCase(CB);
2141 SwitchCases.push_back(CB);
2146 /// handleBitTestsSwitchCase - if current case range has few destination and
2147 /// range span less, than machine word bitwidth, encode case range into series
2148 /// of masks and emit bit tests with these masks.
2149 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2150 CaseRecVector& WorkList,
2152 MachineBasicBlock* Default){
2153 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
2155 Case& FrontCase = *CR.Range.first;
2156 Case& BackCase = *(CR.Range.second-1);
2158 // Get the MachineFunction which holds the current MBB. This is used when
2159 // inserting any additional MBBs necessary to represent the switch.
2160 MachineFunction *CurMF = CurMBB->getParent();
2162 unsigned numCmps = 0;
2163 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2165 // Single case counts one, case range - two.
2166 if (I->Low == I->High)
2172 // Count unique destinations
2173 SmallSet<MachineBasicBlock*, 4> Dests;
2174 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2175 Dests.insert(I->BB);
2176 if (Dests.size() > 3)
2177 // Don't bother the code below, if there are too much unique destinations
2180 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2181 << "Total number of comparisons: " << numCmps << "\n";
2183 // Compute span of values.
2184 Constant* minValue = FrontCase.Low;
2185 Constant* maxValue = BackCase.High;
2186 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2187 cast<ConstantInt>(minValue)->getSExtValue();
2188 DOUT << "Compare range: " << range << "\n"
2189 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2190 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2192 if (range>=IntPtrBits ||
2193 (!(Dests.size() == 1 && numCmps >= 3) &&
2194 !(Dests.size() == 2 && numCmps >= 5) &&
2195 !(Dests.size() >= 3 && numCmps >= 6)))
2198 DOUT << "Emitting bit tests\n";
2199 int64_t lowBound = 0;
2201 // Optimize the case where all the case values fit in a
2202 // word without having to subtract minValue. In this case,
2203 // we can optimize away the subtraction.
2204 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2205 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
2206 range = cast<ConstantInt>(maxValue)->getSExtValue();
2208 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2211 CaseBitsVector CasesBits;
2212 unsigned i, count = 0;
2214 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2215 MachineBasicBlock* Dest = I->BB;
2216 for (i = 0; i < count; ++i)
2217 if (Dest == CasesBits[i].BB)
2221 assert((count < 3) && "Too much destinations to test!");
2222 CasesBits.push_back(CaseBits(0, Dest, 0));
2226 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2227 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2229 for (uint64_t j = lo; j <= hi; j++) {
2230 CasesBits[i].Mask |= 1ULL << j;
2231 CasesBits[i].Bits++;
2235 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2237 SelectionDAGISel::BitTestInfo BTC;
2239 // Figure out which block is immediately after the current one.
2240 MachineFunction::iterator BBI = CR.CaseBB;
2243 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2246 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2247 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2248 << ", BB: " << CasesBits[i].BB << "\n";
2250 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2251 CurMF->insert(BBI, CaseBB);
2252 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2257 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2258 -1U, (CR.CaseBB == CurMBB),
2259 CR.CaseBB, Default, BTC);
2261 if (CR.CaseBB == CurMBB)
2262 visitBitTestHeader(BTB);
2264 BitTestCases.push_back(BTB);
2270 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2271 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2272 const SwitchInst& SI) {
2273 unsigned numCmps = 0;
2275 // Start with "simple" cases
2276 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2277 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2278 Cases.push_back(Case(SI.getSuccessorValue(i),
2279 SI.getSuccessorValue(i),
2282 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2284 // Merge case into clusters
2285 if (Cases.size()>=2)
2286 // Must recompute end() each iteration because it may be
2287 // invalidated by erase if we hold on to it
2288 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2289 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2290 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2291 MachineBasicBlock* nextBB = J->BB;
2292 MachineBasicBlock* currentBB = I->BB;
2294 // If the two neighboring cases go to the same destination, merge them
2295 // into a single case.
2296 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2304 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2305 if (I->Low != I->High)
2306 // A range counts double, since it requires two compares.
2313 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2314 // Figure out which block is immediately after the current one.
2315 MachineBasicBlock *NextBlock = 0;
2316 MachineFunction::iterator BBI = CurMBB;
2318 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2320 // If there is only the default destination, branch to it if it is not the
2321 // next basic block. Otherwise, just fall through.
2322 if (SI.getNumOperands() == 2) {
2323 // Update machine-CFG edges.
2325 // If this is not a fall-through branch, emit the branch.
2326 CurMBB->addSuccessor(Default);
2327 if (Default != NextBlock)
2328 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2329 DAG.getBasicBlock(Default)));
2334 // If there are any non-default case statements, create a vector of Cases
2335 // representing each one, and sort the vector so that we can efficiently
2336 // create a binary search tree from them.
2338 unsigned numCmps = Clusterify(Cases, SI);
2339 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2340 << ". Total compares: " << numCmps << "\n";
2342 // Get the Value to be switched on and default basic blocks, which will be
2343 // inserted into CaseBlock records, representing basic blocks in the binary
2345 Value *SV = SI.getOperand(0);
2347 // Push the initial CaseRec onto the worklist
2348 CaseRecVector WorkList;
2349 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2351 while (!WorkList.empty()) {
2352 // Grab a record representing a case range to process off the worklist
2353 CaseRec CR = WorkList.back();
2354 WorkList.pop_back();
2356 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2359 // If the range has few cases (two or less) emit a series of specific
2361 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2364 // If the switch has more than 5 blocks, and at least 40% dense, and the
2365 // target supports indirect branches, then emit a jump table rather than
2366 // lowering the switch to a binary tree of conditional branches.
2367 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2370 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2371 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2372 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2377 void SelectionDAGLowering::visitSub(User &I) {
2378 // -0.0 - X --> fneg
2379 const Type *Ty = I.getType();
2380 if (isa<VectorType>(Ty)) {
2381 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2382 const VectorType *DestTy = cast<VectorType>(I.getType());
2383 const Type *ElTy = DestTy->getElementType();
2384 if (ElTy->isFloatingPoint()) {
2385 unsigned VL = DestTy->getNumElements();
2386 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2387 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2389 SDValue Op2 = getValue(I.getOperand(1));
2390 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2396 if (Ty->isFloatingPoint()) {
2397 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2398 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2399 SDValue Op2 = getValue(I.getOperand(1));
2400 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2405 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2408 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2409 SDValue Op1 = getValue(I.getOperand(0));
2410 SDValue Op2 = getValue(I.getOperand(1));
2412 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2415 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2416 SDValue Op1 = getValue(I.getOperand(0));
2417 SDValue Op2 = getValue(I.getOperand(1));
2418 if (!isa<VectorType>(I.getType())) {
2419 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2420 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2421 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2422 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2425 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2428 void SelectionDAGLowering::visitICmp(User &I) {
2429 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2430 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2431 predicate = IC->getPredicate();
2432 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2433 predicate = ICmpInst::Predicate(IC->getPredicate());
2434 SDValue Op1 = getValue(I.getOperand(0));
2435 SDValue Op2 = getValue(I.getOperand(1));
2436 ISD::CondCode Opcode;
2437 switch (predicate) {
2438 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2439 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2440 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2441 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2442 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2443 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2444 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2445 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2446 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2447 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2449 assert(!"Invalid ICmp predicate value");
2450 Opcode = ISD::SETEQ;
2453 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2456 void SelectionDAGLowering::visitFCmp(User &I) {
2457 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2458 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2459 predicate = FC->getPredicate();
2460 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2461 predicate = FCmpInst::Predicate(FC->getPredicate());
2462 SDValue Op1 = getValue(I.getOperand(0));
2463 SDValue Op2 = getValue(I.getOperand(1));
2464 ISD::CondCode Condition, FOC, FPC;
2465 switch (predicate) {
2466 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2467 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2468 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2469 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2470 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2471 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2472 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2473 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2474 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2475 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2476 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2477 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2478 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2479 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2480 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2481 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2483 assert(!"Invalid FCmp predicate value");
2484 FOC = FPC = ISD::SETFALSE;
2487 if (FiniteOnlyFPMath())
2491 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2494 void SelectionDAGLowering::visitVICmp(User &I) {
2495 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2496 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2497 predicate = IC->getPredicate();
2498 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2499 predicate = ICmpInst::Predicate(IC->getPredicate());
2500 SDValue Op1 = getValue(I.getOperand(0));
2501 SDValue Op2 = getValue(I.getOperand(1));
2502 ISD::CondCode Opcode;
2503 switch (predicate) {
2504 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2505 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2506 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2507 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2508 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2509 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2510 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2511 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2512 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2513 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2515 assert(!"Invalid ICmp predicate value");
2516 Opcode = ISD::SETEQ;
2519 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2522 void SelectionDAGLowering::visitVFCmp(User &I) {
2523 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2524 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2525 predicate = FC->getPredicate();
2526 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2527 predicate = FCmpInst::Predicate(FC->getPredicate());
2528 SDValue Op1 = getValue(I.getOperand(0));
2529 SDValue Op2 = getValue(I.getOperand(1));
2530 ISD::CondCode Condition, FOC, FPC;
2531 switch (predicate) {
2532 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2533 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2534 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2535 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2536 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2537 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2538 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2539 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2540 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2541 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2542 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2543 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2544 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2545 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2546 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2547 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2549 assert(!"Invalid VFCmp predicate value");
2550 FOC = FPC = ISD::SETFALSE;
2553 if (FiniteOnlyFPMath())
2558 MVT DestVT = TLI.getValueType(I.getType());
2560 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2563 void SelectionDAGLowering::visitSelect(User &I) {
2564 SDValue Cond = getValue(I.getOperand(0));
2565 SDValue TrueVal = getValue(I.getOperand(1));
2566 SDValue FalseVal = getValue(I.getOperand(2));
2567 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2568 TrueVal, FalseVal));
2572 void SelectionDAGLowering::visitTrunc(User &I) {
2573 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2574 SDValue N = getValue(I.getOperand(0));
2575 MVT DestVT = TLI.getValueType(I.getType());
2576 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2579 void SelectionDAGLowering::visitZExt(User &I) {
2580 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2581 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2582 SDValue N = getValue(I.getOperand(0));
2583 MVT DestVT = TLI.getValueType(I.getType());
2584 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2587 void SelectionDAGLowering::visitSExt(User &I) {
2588 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2589 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2590 SDValue N = getValue(I.getOperand(0));
2591 MVT DestVT = TLI.getValueType(I.getType());
2592 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2595 void SelectionDAGLowering::visitFPTrunc(User &I) {
2596 // FPTrunc is never a no-op cast, no need to check
2597 SDValue N = getValue(I.getOperand(0));
2598 MVT DestVT = TLI.getValueType(I.getType());
2599 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2602 void SelectionDAGLowering::visitFPExt(User &I){
2603 // FPTrunc is never a no-op cast, no need to check
2604 SDValue N = getValue(I.getOperand(0));
2605 MVT DestVT = TLI.getValueType(I.getType());
2606 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2609 void SelectionDAGLowering::visitFPToUI(User &I) {
2610 // FPToUI is never a no-op cast, no need to check
2611 SDValue N = getValue(I.getOperand(0));
2612 MVT DestVT = TLI.getValueType(I.getType());
2613 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2616 void SelectionDAGLowering::visitFPToSI(User &I) {
2617 // FPToSI is never a no-op cast, no need to check
2618 SDValue N = getValue(I.getOperand(0));
2619 MVT DestVT = TLI.getValueType(I.getType());
2620 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2623 void SelectionDAGLowering::visitUIToFP(User &I) {
2624 // UIToFP is never a no-op cast, no need to check
2625 SDValue N = getValue(I.getOperand(0));
2626 MVT DestVT = TLI.getValueType(I.getType());
2627 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2630 void SelectionDAGLowering::visitSIToFP(User &I){
2631 // UIToFP is never a no-op cast, no need to check
2632 SDValue N = getValue(I.getOperand(0));
2633 MVT DestVT = TLI.getValueType(I.getType());
2634 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2637 void SelectionDAGLowering::visitPtrToInt(User &I) {
2638 // What to do depends on the size of the integer and the size of the pointer.
2639 // We can either truncate, zero extend, or no-op, accordingly.
2640 SDValue N = getValue(I.getOperand(0));
2641 MVT SrcVT = N.getValueType();
2642 MVT DestVT = TLI.getValueType(I.getType());
2644 if (DestVT.bitsLT(SrcVT))
2645 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2647 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2648 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2649 setValue(&I, Result);
2652 void SelectionDAGLowering::visitIntToPtr(User &I) {
2653 // What to do depends on the size of the integer and the size of the pointer.
2654 // We can either truncate, zero extend, or no-op, accordingly.
2655 SDValue N = getValue(I.getOperand(0));
2656 MVT SrcVT = N.getValueType();
2657 MVT DestVT = TLI.getValueType(I.getType());
2658 if (DestVT.bitsLT(SrcVT))
2659 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2661 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2662 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2665 void SelectionDAGLowering::visitBitCast(User &I) {
2666 SDValue N = getValue(I.getOperand(0));
2667 MVT DestVT = TLI.getValueType(I.getType());
2669 // BitCast assures us that source and destination are the same size so this
2670 // is either a BIT_CONVERT or a no-op.
2671 if (DestVT != N.getValueType())
2672 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2674 setValue(&I, N); // noop cast.
2677 void SelectionDAGLowering::visitInsertElement(User &I) {
2678 SDValue InVec = getValue(I.getOperand(0));
2679 SDValue InVal = getValue(I.getOperand(1));
2680 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2681 getValue(I.getOperand(2)));
2683 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2684 TLI.getValueType(I.getType()),
2685 InVec, InVal, InIdx));
2688 void SelectionDAGLowering::visitExtractElement(User &I) {
2689 SDValue InVec = getValue(I.getOperand(0));
2690 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2691 getValue(I.getOperand(1)));
2692 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2693 TLI.getValueType(I.getType()), InVec, InIdx));
2696 void SelectionDAGLowering::visitShuffleVector(User &I) {
2697 SDValue V1 = getValue(I.getOperand(0));
2698 SDValue V2 = getValue(I.getOperand(1));
2699 SDValue Mask = getValue(I.getOperand(2));
2701 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2702 TLI.getValueType(I.getType()),
2706 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2707 const Value *Op0 = I.getOperand(0);
2708 const Value *Op1 = I.getOperand(1);
2709 const Type *AggTy = I.getType();
2710 const Type *ValTy = Op1->getType();
2711 bool IntoUndef = isa<UndefValue>(Op0);
2712 bool FromUndef = isa<UndefValue>(Op1);
2714 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2715 I.idx_begin(), I.idx_end());
2717 SmallVector<MVT, 4> AggValueVTs;
2718 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2719 SmallVector<MVT, 4> ValValueVTs;
2720 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2722 unsigned NumAggValues = AggValueVTs.size();
2723 unsigned NumValValues = ValValueVTs.size();
2724 SmallVector<SDValue, 4> Values(NumAggValues);
2726 SDValue Agg = getValue(Op0);
2727 SDValue Val = getValue(Op1);
2729 // Copy the beginning value(s) from the original aggregate.
2730 for (; i != LinearIndex; ++i)
2731 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2732 SDValue(Agg.Val, Agg.ResNo + i);
2733 // Copy values from the inserted value(s).
2734 for (; i != LinearIndex + NumValValues; ++i)
2735 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2736 SDValue(Val.Val, Val.ResNo + i - LinearIndex);
2737 // Copy remaining value(s) from the original aggregate.
2738 for (; i != NumAggValues; ++i)
2739 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2740 SDValue(Agg.Val, Agg.ResNo + i);
2742 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2743 &Values[0], NumAggValues));
2746 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2747 const Value *Op0 = I.getOperand(0);
2748 const Type *AggTy = Op0->getType();
2749 const Type *ValTy = I.getType();
2750 bool OutOfUndef = isa<UndefValue>(Op0);
2752 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2753 I.idx_begin(), I.idx_end());
2755 SmallVector<MVT, 4> ValValueVTs;
2756 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2758 unsigned NumValValues = ValValueVTs.size();
2759 SmallVector<SDValue, 4> Values(NumValValues);
2761 SDValue Agg = getValue(Op0);
2762 // Copy out the selected value(s).
2763 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2764 Values[i - LinearIndex] =
2765 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(Agg.ResNo + i)) :
2766 SDValue(Agg.Val, Agg.ResNo + i);
2768 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2769 &Values[0], NumValValues));
2773 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2774 SDValue N = getValue(I.getOperand(0));
2775 const Type *Ty = I.getOperand(0)->getType();
2777 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2780 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2781 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2784 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2785 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2786 DAG.getIntPtrConstant(Offset));
2788 Ty = StTy->getElementType(Field);
2790 Ty = cast<SequentialType>(Ty)->getElementType();
2792 // If this is a constant subscript, handle it quickly.
2793 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2794 if (CI->getZExtValue() == 0) continue;
2796 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2797 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2798 DAG.getIntPtrConstant(Offs));
2802 // N = N + Idx * ElementSize;
2803 uint64_t ElementSize = TD->getABITypeSize(Ty);
2804 SDValue IdxN = getValue(Idx);
2806 // If the index is smaller or larger than intptr_t, truncate or extend
2808 if (IdxN.getValueType().bitsLT(N.getValueType())) {
2809 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2810 } else if (IdxN.getValueType().bitsGT(N.getValueType()))
2811 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2813 // If this is a multiply by a power of two, turn it into a shl
2814 // immediately. This is a very common case.
2815 if (isPowerOf2_64(ElementSize)) {
2816 unsigned Amt = Log2_64(ElementSize);
2817 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2818 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2819 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2823 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2824 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2825 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2831 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2832 // If this is a fixed sized alloca in the entry block of the function,
2833 // allocate it statically on the stack.
2834 if (FuncInfo.StaticAllocaMap.count(&I))
2835 return; // getValue will auto-populate this.
2837 const Type *Ty = I.getAllocatedType();
2838 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2840 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2843 SDValue AllocSize = getValue(I.getArraySize());
2844 MVT IntPtr = TLI.getPointerTy();
2845 if (IntPtr.bitsLT(AllocSize.getValueType()))
2846 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2847 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2848 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2850 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2851 DAG.getIntPtrConstant(TySize));
2853 // Handle alignment. If the requested alignment is less than or equal to
2854 // the stack alignment, ignore it. If the size is greater than or equal to
2855 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2856 unsigned StackAlign =
2857 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2858 if (Align <= StackAlign)
2861 // Round the size of the allocation up to the stack alignment size
2862 // by add SA-1 to the size.
2863 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2864 DAG.getIntPtrConstant(StackAlign-1));
2865 // Mask out the low bits for alignment purposes.
2866 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2867 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2869 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2870 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2872 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2874 DAG.setRoot(DSA.getValue(1));
2876 // Inform the Frame Information that we have just allocated a variable-sized
2878 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2881 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2882 const Value *SV = I.getOperand(0);
2883 SDValue Ptr = getValue(SV);
2885 const Type *Ty = I.getType();
2886 bool isVolatile = I.isVolatile();
2887 unsigned Alignment = I.getAlignment();
2889 SmallVector<MVT, 4> ValueVTs;
2890 SmallVector<uint64_t, 4> Offsets;
2891 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2892 unsigned NumValues = ValueVTs.size();
2897 bool ConstantMemory = false;
2899 // Serialize volatile loads with other side effects.
2901 else if (AA.pointsToConstantMemory(SV)) {
2902 // Do not serialize (non-volatile) loads of constant memory with anything.
2903 Root = DAG.getEntryNode();
2904 ConstantMemory = true;
2906 // Do not serialize non-volatile loads against each other.
2907 Root = DAG.getRoot();
2910 SmallVector<SDValue, 4> Values(NumValues);
2911 SmallVector<SDValue, 4> Chains(NumValues);
2912 MVT PtrVT = Ptr.getValueType();
2913 for (unsigned i = 0; i != NumValues; ++i) {
2914 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2915 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2916 DAG.getConstant(Offsets[i], PtrVT)),
2918 isVolatile, Alignment);
2920 Chains[i] = L.getValue(1);
2923 if (!ConstantMemory) {
2924 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2925 &Chains[0], NumValues);
2929 PendingLoads.push_back(Chain);
2932 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2933 &Values[0], NumValues));
2937 void SelectionDAGLowering::visitStore(StoreInst &I) {
2938 Value *SrcV = I.getOperand(0);
2939 Value *PtrV = I.getOperand(1);
2941 SmallVector<MVT, 4> ValueVTs;
2942 SmallVector<uint64_t, 4> Offsets;
2943 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2944 unsigned NumValues = ValueVTs.size();
2948 // Get the lowered operands. Note that we do this after
2949 // checking if NumResults is zero, because with zero results
2950 // the operands won't have values in the map.
2951 SDValue Src = getValue(SrcV);
2952 SDValue Ptr = getValue(PtrV);
2954 SDValue Root = getRoot();
2955 SmallVector<SDValue, 4> Chains(NumValues);
2956 MVT PtrVT = Ptr.getValueType();
2957 bool isVolatile = I.isVolatile();
2958 unsigned Alignment = I.getAlignment();
2959 for (unsigned i = 0; i != NumValues; ++i)
2960 Chains[i] = DAG.getStore(Root, SDValue(Src.Val, Src.ResNo + i),
2961 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2962 DAG.getConstant(Offsets[i], PtrVT)),
2964 isVolatile, Alignment);
2966 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2969 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2971 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2972 unsigned Intrinsic) {
2973 bool HasChain = !I.doesNotAccessMemory();
2974 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2976 // Build the operand list.
2977 SmallVector<SDValue, 8> Ops;
2978 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2980 // We don't need to serialize loads against other loads.
2981 Ops.push_back(DAG.getRoot());
2983 Ops.push_back(getRoot());
2987 // Add the intrinsic ID as an integer operand.
2988 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2990 // Add all operands of the call to the operand list.
2991 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2992 SDValue Op = getValue(I.getOperand(i));
2993 assert(TLI.isTypeLegal(Op.getValueType()) &&
2994 "Intrinsic uses a non-legal type?");
2998 std::vector<MVT> VTs;
2999 if (I.getType() != Type::VoidTy) {
3000 MVT VT = TLI.getValueType(I.getType());
3001 if (VT.isVector()) {
3002 const VectorType *DestTy = cast<VectorType>(I.getType());
3003 MVT EltVT = TLI.getValueType(DestTy->getElementType());
3005 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
3006 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
3009 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
3013 VTs.push_back(MVT::Other);
3015 const MVT *VTList = DAG.getNodeValueTypes(VTs);
3020 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
3021 &Ops[0], Ops.size());
3022 else if (I.getType() != Type::VoidTy)
3023 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
3024 &Ops[0], Ops.size());
3026 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
3027 &Ops[0], Ops.size());
3030 SDValue Chain = Result.getValue(Result.Val->getNumValues()-1);
3032 PendingLoads.push_back(Chain);
3036 if (I.getType() != Type::VoidTy) {
3037 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3038 MVT VT = TLI.getValueType(PTy);
3039 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
3041 setValue(&I, Result);
3045 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3046 static GlobalVariable *ExtractTypeInfo (Value *V) {
3047 V = V->stripPointerCasts();
3048 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3049 assert ((GV || isa<ConstantPointerNull>(V)) &&
3050 "TypeInfo must be a global variable or NULL");
3054 /// addCatchInfo - Extract the personality and type infos from an eh.selector
3055 /// call, and add them to the specified machine basic block.
3056 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3057 MachineBasicBlock *MBB) {
3058 // Inform the MachineModuleInfo of the personality for this landing pad.
3059 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3060 assert(CE->getOpcode() == Instruction::BitCast &&
3061 isa<Function>(CE->getOperand(0)) &&
3062 "Personality should be a function");
3063 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3065 // Gather all the type infos for this landing pad and pass them along to
3066 // MachineModuleInfo.
3067 std::vector<GlobalVariable *> TyInfo;
3068 unsigned N = I.getNumOperands();
3070 for (unsigned i = N - 1; i > 2; --i) {
3071 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3072 unsigned FilterLength = CI->getZExtValue();
3073 unsigned FirstCatch = i + FilterLength + !FilterLength;
3074 assert (FirstCatch <= N && "Invalid filter length");
3076 if (FirstCatch < N) {
3077 TyInfo.reserve(N - FirstCatch);
3078 for (unsigned j = FirstCatch; j < N; ++j)
3079 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3080 MMI->addCatchTypeInfo(MBB, TyInfo);
3084 if (!FilterLength) {
3086 MMI->addCleanup(MBB);
3089 TyInfo.reserve(FilterLength - 1);
3090 for (unsigned j = i + 1; j < FirstCatch; ++j)
3091 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3092 MMI->addFilterTypeInfo(MBB, TyInfo);
3101 TyInfo.reserve(N - 3);
3102 for (unsigned j = 3; j < N; ++j)
3103 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3104 MMI->addCatchTypeInfo(MBB, TyInfo);
3109 /// Inlined utility function to implement binary input atomic intrinsics for
3110 // visitIntrinsicCall: I is a call instruction
3111 // Op is the associated NodeType for I
3113 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3114 SDValue Root = getRoot();
3115 SDValue L = DAG.getAtomic(Op, Root,
3116 getValue(I.getOperand(1)),
3117 getValue(I.getOperand(2)),
3120 DAG.setRoot(L.getValue(1));
3124 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3125 /// we want to emit this as a call to a named external function, return the name
3126 /// otherwise lower it and return null.
3128 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3129 switch (Intrinsic) {
3131 // By default, turn this into a target intrinsic node.
3132 visitTargetIntrinsic(I, Intrinsic);
3134 case Intrinsic::vastart: visitVAStart(I); return 0;
3135 case Intrinsic::vaend: visitVAEnd(I); return 0;
3136 case Intrinsic::vacopy: visitVACopy(I); return 0;
3137 case Intrinsic::returnaddress:
3138 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3139 getValue(I.getOperand(1))));
3141 case Intrinsic::frameaddress:
3142 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3143 getValue(I.getOperand(1))));
3145 case Intrinsic::setjmp:
3146 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3148 case Intrinsic::longjmp:
3149 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3151 case Intrinsic::memcpy_i32:
3152 case Intrinsic::memcpy_i64: {
3153 SDValue Op1 = getValue(I.getOperand(1));
3154 SDValue Op2 = getValue(I.getOperand(2));
3155 SDValue Op3 = getValue(I.getOperand(3));
3156 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3157 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3158 I.getOperand(1), 0, I.getOperand(2), 0));
3161 case Intrinsic::memset_i32:
3162 case Intrinsic::memset_i64: {
3163 SDValue Op1 = getValue(I.getOperand(1));
3164 SDValue Op2 = getValue(I.getOperand(2));
3165 SDValue Op3 = getValue(I.getOperand(3));
3166 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3167 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3168 I.getOperand(1), 0));
3171 case Intrinsic::memmove_i32:
3172 case Intrinsic::memmove_i64: {
3173 SDValue Op1 = getValue(I.getOperand(1));
3174 SDValue Op2 = getValue(I.getOperand(2));
3175 SDValue Op3 = getValue(I.getOperand(3));
3176 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3178 // If the source and destination are known to not be aliases, we can
3179 // lower memmove as memcpy.
3180 uint64_t Size = -1ULL;
3181 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3182 Size = C->getValue();
3183 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3184 AliasAnalysis::NoAlias) {
3185 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3186 I.getOperand(1), 0, I.getOperand(2), 0));
3190 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3191 I.getOperand(1), 0, I.getOperand(2), 0));
3194 case Intrinsic::dbg_stoppoint: {
3195 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3196 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3197 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3198 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3199 assert(DD && "Not a debug information descriptor");
3200 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3203 cast<CompileUnitDesc>(DD)));
3208 case Intrinsic::dbg_region_start: {
3209 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3210 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3211 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3212 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3213 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3218 case Intrinsic::dbg_region_end: {
3219 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3220 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3221 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3222 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3223 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3228 case Intrinsic::dbg_func_start: {
3229 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3231 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3232 Value *SP = FSI.getSubprogram();
3233 if (SP && MMI->Verify(SP)) {
3234 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3235 // what (most?) gdb expects.
3236 DebugInfoDesc *DD = MMI->getDescFor(SP);
3237 assert(DD && "Not a debug information descriptor");
3238 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3239 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3240 unsigned SrcFile = MMI->RecordSource(CompileUnit);
3241 // Record the source line but does create a label. It will be emitted
3242 // at asm emission time.
3243 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3248 case Intrinsic::dbg_declare: {
3249 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3250 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3251 Value *Variable = DI.getVariable();
3252 if (MMI && Variable && MMI->Verify(Variable))
3253 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3254 getValue(DI.getAddress()), getValue(Variable)));
3258 case Intrinsic::eh_exception: {
3259 if (!CurMBB->isLandingPad()) {
3260 // FIXME: Mark exception register as live in. Hack for PR1508.
3261 unsigned Reg = TLI.getExceptionAddressRegister();
3262 if (Reg) CurMBB->addLiveIn(Reg);
3264 // Insert the EXCEPTIONADDR instruction.
3265 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3267 Ops[0] = DAG.getRoot();
3268 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3270 DAG.setRoot(Op.getValue(1));
3274 case Intrinsic::eh_selector_i32:
3275 case Intrinsic::eh_selector_i64: {
3276 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3277 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3278 MVT::i32 : MVT::i64);
3281 if (CurMBB->isLandingPad())
3282 addCatchInfo(I, MMI, CurMBB);
3285 FuncInfo.CatchInfoLost.insert(&I);
3287 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3288 unsigned Reg = TLI.getExceptionSelectorRegister();
3289 if (Reg) CurMBB->addLiveIn(Reg);
3292 // Insert the EHSELECTION instruction.
3293 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3295 Ops[0] = getValue(I.getOperand(1));
3297 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3299 DAG.setRoot(Op.getValue(1));
3301 setValue(&I, DAG.getConstant(0, VT));
3307 case Intrinsic::eh_typeid_for_i32:
3308 case Intrinsic::eh_typeid_for_i64: {
3309 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3310 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3311 MVT::i32 : MVT::i64);
3314 // Find the type id for the given typeinfo.
3315 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3317 unsigned TypeID = MMI->getTypeIDFor(GV);
3318 setValue(&I, DAG.getConstant(TypeID, VT));
3320 // Return something different to eh_selector.
3321 setValue(&I, DAG.getConstant(1, VT));
3327 case Intrinsic::eh_return: {
3328 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3331 MMI->setCallsEHReturn(true);
3332 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3335 getValue(I.getOperand(1)),
3336 getValue(I.getOperand(2))));
3338 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3344 case Intrinsic::eh_unwind_init: {
3345 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3346 MMI->setCallsUnwindInit(true);
3352 case Intrinsic::eh_dwarf_cfa: {
3353 MVT VT = getValue(I.getOperand(1)).getValueType();
3355 if (VT.bitsGT(TLI.getPointerTy()))
3356 CfaArg = DAG.getNode(ISD::TRUNCATE,
3357 TLI.getPointerTy(), getValue(I.getOperand(1)));
3359 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3360 TLI.getPointerTy(), getValue(I.getOperand(1)));
3362 SDValue Offset = DAG.getNode(ISD::ADD,
3364 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3365 TLI.getPointerTy()),
3367 setValue(&I, DAG.getNode(ISD::ADD,
3369 DAG.getNode(ISD::FRAMEADDR,
3372 TLI.getPointerTy())),
3377 case Intrinsic::sqrt:
3378 setValue(&I, DAG.getNode(ISD::FSQRT,
3379 getValue(I.getOperand(1)).getValueType(),
3380 getValue(I.getOperand(1))));
3382 case Intrinsic::powi:
3383 setValue(&I, DAG.getNode(ISD::FPOWI,
3384 getValue(I.getOperand(1)).getValueType(),
3385 getValue(I.getOperand(1)),
3386 getValue(I.getOperand(2))));
3388 case Intrinsic::sin:
3389 setValue(&I, DAG.getNode(ISD::FSIN,
3390 getValue(I.getOperand(1)).getValueType(),
3391 getValue(I.getOperand(1))));
3393 case Intrinsic::cos:
3394 setValue(&I, DAG.getNode(ISD::FCOS,
3395 getValue(I.getOperand(1)).getValueType(),
3396 getValue(I.getOperand(1))));
3398 case Intrinsic::pow:
3399 setValue(&I, DAG.getNode(ISD::FPOW,
3400 getValue(I.getOperand(1)).getValueType(),
3401 getValue(I.getOperand(1)),
3402 getValue(I.getOperand(2))));
3404 case Intrinsic::pcmarker: {
3405 SDValue Tmp = getValue(I.getOperand(1));
3406 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3409 case Intrinsic::readcyclecounter: {
3410 SDValue Op = getRoot();
3411 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3412 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3415 DAG.setRoot(Tmp.getValue(1));
3418 case Intrinsic::part_select: {
3419 // Currently not implemented: just abort
3420 assert(0 && "part_select intrinsic not implemented");
3423 case Intrinsic::part_set: {
3424 // Currently not implemented: just abort
3425 assert(0 && "part_set intrinsic not implemented");
3428 case Intrinsic::bswap:
3429 setValue(&I, DAG.getNode(ISD::BSWAP,
3430 getValue(I.getOperand(1)).getValueType(),
3431 getValue(I.getOperand(1))));
3433 case Intrinsic::cttz: {
3434 SDValue Arg = getValue(I.getOperand(1));
3435 MVT Ty = Arg.getValueType();
3436 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3437 setValue(&I, result);
3440 case Intrinsic::ctlz: {
3441 SDValue Arg = getValue(I.getOperand(1));
3442 MVT Ty = Arg.getValueType();
3443 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3444 setValue(&I, result);
3447 case Intrinsic::ctpop: {
3448 SDValue Arg = getValue(I.getOperand(1));
3449 MVT Ty = Arg.getValueType();
3450 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3451 setValue(&I, result);
3454 case Intrinsic::stacksave: {
3455 SDValue Op = getRoot();
3456 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3457 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3459 DAG.setRoot(Tmp.getValue(1));
3462 case Intrinsic::stackrestore: {
3463 SDValue Tmp = getValue(I.getOperand(1));
3464 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3467 case Intrinsic::var_annotation:
3468 // Discard annotate attributes
3471 case Intrinsic::init_trampoline: {
3472 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3476 Ops[1] = getValue(I.getOperand(1));
3477 Ops[2] = getValue(I.getOperand(2));
3478 Ops[3] = getValue(I.getOperand(3));
3479 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3480 Ops[5] = DAG.getSrcValue(F);
3482 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3483 DAG.getNodeValueTypes(TLI.getPointerTy(),
3488 DAG.setRoot(Tmp.getValue(1));
3492 case Intrinsic::gcroot:
3494 Value *Alloca = I.getOperand(1);
3495 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3497 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3498 GFI->addStackRoot(FI->getIndex(), TypeMap);
3502 case Intrinsic::gcread:
3503 case Intrinsic::gcwrite:
3504 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3507 case Intrinsic::flt_rounds: {
3508 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3512 case Intrinsic::trap: {
3513 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3516 case Intrinsic::prefetch: {
3519 Ops[1] = getValue(I.getOperand(1));
3520 Ops[2] = getValue(I.getOperand(2));
3521 Ops[3] = getValue(I.getOperand(3));
3522 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3526 case Intrinsic::memory_barrier: {
3529 for (int x = 1; x < 6; ++x)
3530 Ops[x] = getValue(I.getOperand(x));
3532 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3535 case Intrinsic::atomic_cmp_swap: {
3536 SDValue Root = getRoot();
3537 SDValue L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, Root,
3538 getValue(I.getOperand(1)),
3539 getValue(I.getOperand(2)),
3540 getValue(I.getOperand(3)),
3543 DAG.setRoot(L.getValue(1));
3546 case Intrinsic::atomic_load_add:
3547 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
3548 case Intrinsic::atomic_load_sub:
3549 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
3550 case Intrinsic::atomic_load_and:
3551 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3552 case Intrinsic::atomic_load_or:
3553 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3554 case Intrinsic::atomic_load_xor:
3555 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3556 case Intrinsic::atomic_load_nand:
3557 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
3558 case Intrinsic::atomic_load_min:
3559 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3560 case Intrinsic::atomic_load_max:
3561 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3562 case Intrinsic::atomic_load_umin:
3563 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3564 case Intrinsic::atomic_load_umax:
3565 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3566 case Intrinsic::atomic_swap:
3567 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
3572 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
3574 MachineBasicBlock *LandingPad) {
3575 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3576 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3577 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3578 unsigned BeginLabel = 0, EndLabel = 0;
3580 TargetLowering::ArgListTy Args;
3581 TargetLowering::ArgListEntry Entry;
3582 Args.reserve(CS.arg_size());
3583 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3585 SDValue ArgNode = getValue(*i);
3586 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3588 unsigned attrInd = i - CS.arg_begin() + 1;
3589 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3590 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3591 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3592 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3593 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3594 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3595 Entry.Alignment = CS.getParamAlignment(attrInd);
3596 Args.push_back(Entry);
3599 if (LandingPad && MMI) {
3600 // Insert a label before the invoke call to mark the try range. This can be
3601 // used to detect deletion of the invoke via the MachineModuleInfo.
3602 BeginLabel = MMI->NextLabelID();
3603 // Both PendingLoads and PendingExports must be flushed here;
3604 // this call might not return.
3606 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
3609 std::pair<SDValue,SDValue> Result =
3610 TLI.LowerCallTo(getRoot(), CS.getType(),
3611 CS.paramHasAttr(0, ParamAttr::SExt),
3612 CS.paramHasAttr(0, ParamAttr::ZExt),
3613 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3615 if (CS.getType() != Type::VoidTy)
3616 setValue(CS.getInstruction(), Result.first);
3617 DAG.setRoot(Result.second);
3619 if (LandingPad && MMI) {
3620 // Insert a label at the end of the invoke call to mark the try range. This
3621 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3622 EndLabel = MMI->NextLabelID();
3623 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
3625 // Inform MachineModuleInfo of range.
3626 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3631 void SelectionDAGLowering::visitCall(CallInst &I) {
3632 const char *RenameFn = 0;
3633 if (Function *F = I.getCalledFunction()) {
3634 if (F->isDeclaration()) {
3635 if (unsigned IID = F->getIntrinsicID()) {
3636 RenameFn = visitIntrinsicCall(I, IID);
3642 // Check for well-known libc/libm calls. If the function is internal, it
3643 // can't be a library call.
3644 unsigned NameLen = F->getNameLen();
3645 if (!F->hasInternalLinkage() && NameLen) {
3646 const char *NameStr = F->getNameStart();
3647 if (NameStr[0] == 'c' &&
3648 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3649 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3650 if (I.getNumOperands() == 3 && // Basic sanity checks.
3651 I.getOperand(1)->getType()->isFloatingPoint() &&
3652 I.getType() == I.getOperand(1)->getType() &&
3653 I.getType() == I.getOperand(2)->getType()) {
3654 SDValue LHS = getValue(I.getOperand(1));
3655 SDValue RHS = getValue(I.getOperand(2));
3656 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3660 } else if (NameStr[0] == 'f' &&
3661 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3662 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3663 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3664 if (I.getNumOperands() == 2 && // Basic sanity checks.
3665 I.getOperand(1)->getType()->isFloatingPoint() &&
3666 I.getType() == I.getOperand(1)->getType()) {
3667 SDValue Tmp = getValue(I.getOperand(1));
3668 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3671 } else if (NameStr[0] == 's' &&
3672 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3673 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3674 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3675 if (I.getNumOperands() == 2 && // Basic sanity checks.
3676 I.getOperand(1)->getType()->isFloatingPoint() &&
3677 I.getType() == I.getOperand(1)->getType()) {
3678 SDValue Tmp = getValue(I.getOperand(1));
3679 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3682 } else if (NameStr[0] == 'c' &&
3683 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3684 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3685 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3686 if (I.getNumOperands() == 2 && // Basic sanity checks.
3687 I.getOperand(1)->getType()->isFloatingPoint() &&
3688 I.getType() == I.getOperand(1)->getType()) {
3689 SDValue Tmp = getValue(I.getOperand(1));
3690 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3695 } else if (isa<InlineAsm>(I.getOperand(0))) {
3702 Callee = getValue(I.getOperand(0));
3704 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3706 LowerCallTo(&I, Callee, I.isTailCall());
3710 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3711 /// this value and returns the result as a ValueVT value. This uses
3712 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3713 /// If the Flag pointer is NULL, no flag is used.
3714 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3716 SDValue *Flag) const {
3717 // Assemble the legal parts into the final values.
3718 SmallVector<SDValue, 4> Values(ValueVTs.size());
3719 SmallVector<SDValue, 8> Parts;
3720 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3721 // Copy the legal parts from the registers.
3722 MVT ValueVT = ValueVTs[Value];
3723 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3724 MVT RegisterVT = RegVTs[Value];
3726 Parts.resize(NumRegs);
3727 for (unsigned i = 0; i != NumRegs; ++i) {
3730 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3732 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3733 *Flag = P.getValue(2);
3735 Chain = P.getValue(1);
3737 // If the source register was virtual and if we know something about it,
3738 // add an assert node.
3739 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
3740 RegisterVT.isInteger() && !RegisterVT.isVector()) {
3741 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
3742 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
3743 if (FLI.LiveOutRegInfo.size() > SlotNo) {
3744 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
3746 unsigned RegSize = RegisterVT.getSizeInBits();
3747 unsigned NumSignBits = LOI.NumSignBits;
3748 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
3750 // FIXME: We capture more information than the dag can represent. For
3751 // now, just use the tightest assertzext/assertsext possible.
3753 MVT FromVT(MVT::Other);
3754 if (NumSignBits == RegSize)
3755 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
3756 else if (NumZeroBits >= RegSize-1)
3757 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
3758 else if (NumSignBits > RegSize-8)
3759 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
3760 else if (NumZeroBits >= RegSize-9)
3761 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
3762 else if (NumSignBits > RegSize-16)
3763 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
3764 else if (NumZeroBits >= RegSize-17)
3765 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
3766 else if (NumSignBits > RegSize-32)
3767 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
3768 else if (NumZeroBits >= RegSize-33)
3769 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
3771 if (FromVT != MVT::Other) {
3772 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
3773 RegisterVT, P, DAG.getValueType(FromVT));
3782 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3787 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3788 &Values[0], ValueVTs.size());
3791 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3792 /// specified value into the registers specified by this object. This uses
3793 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3794 /// If the Flag pointer is NULL, no flag is used.
3795 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
3796 SDValue &Chain, SDValue *Flag) const {
3797 // Get the list of the values's legal parts.
3798 unsigned NumRegs = Regs.size();
3799 SmallVector<SDValue, 8> Parts(NumRegs);
3800 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3801 MVT ValueVT = ValueVTs[Value];
3802 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3803 MVT RegisterVT = RegVTs[Value];
3805 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3806 &Parts[Part], NumParts, RegisterVT);
3810 // Copy the parts into the registers.
3811 SmallVector<SDValue, 8> Chains(NumRegs);
3812 for (unsigned i = 0; i != NumRegs; ++i) {
3815 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3817 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3818 *Flag = Part.getValue(1);
3820 Chains[i] = Part.getValue(0);
3823 if (NumRegs == 1 || Flag)
3824 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3825 // flagged to it. That is the CopyToReg nodes and the user are considered
3826 // a single scheduling unit. If we create a TokenFactor and return it as
3827 // chain, then the TokenFactor is both a predecessor (operand) of the
3828 // user as well as a successor (the TF operands are flagged to the user).
3829 // c1, f1 = CopyToReg
3830 // c2, f2 = CopyToReg
3831 // c3 = TokenFactor c1, c2
3834 Chain = Chains[NumRegs-1];
3836 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3839 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3840 /// operand list. This adds the code marker and includes the number of
3841 /// values added into it.
3842 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3843 std::vector<SDValue> &Ops) const {
3844 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3845 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3846 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3847 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3848 MVT RegisterVT = RegVTs[Value];
3849 for (unsigned i = 0; i != NumRegs; ++i)
3850 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3854 /// isAllocatableRegister - If the specified register is safe to allocate,
3855 /// i.e. it isn't a stack pointer or some other special register, return the
3856 /// register class for the register. Otherwise, return null.
3857 static const TargetRegisterClass *
3858 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3859 const TargetLowering &TLI,
3860 const TargetRegisterInfo *TRI) {
3861 MVT FoundVT = MVT::Other;
3862 const TargetRegisterClass *FoundRC = 0;
3863 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3864 E = TRI->regclass_end(); RCI != E; ++RCI) {
3865 MVT ThisVT = MVT::Other;
3867 const TargetRegisterClass *RC = *RCI;
3868 // If none of the the value types for this register class are valid, we
3869 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3870 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3872 if (TLI.isTypeLegal(*I)) {
3873 // If we have already found this register in a different register class,
3874 // choose the one with the largest VT specified. For example, on
3875 // PowerPC, we favor f64 register classes over f32.
3876 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
3883 if (ThisVT == MVT::Other) continue;
3885 // NOTE: This isn't ideal. In particular, this might allocate the
3886 // frame pointer in functions that need it (due to them not being taken
3887 // out of allocation, because a variable sized allocation hasn't been seen
3888 // yet). This is a slight code pessimization, but should still work.
3889 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3890 E = RC->allocation_order_end(MF); I != E; ++I)
3892 // We found a matching register class. Keep looking at others in case
3893 // we find one with larger registers that this physreg is also in.
3904 /// AsmOperandInfo - This contains information for each constraint that we are
3906 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3907 /// CallOperand - If this is the result output operand or a clobber
3908 /// this is null, otherwise it is the incoming operand to the CallInst.
3909 /// This gets modified as the asm is processed.
3910 SDValue CallOperand;
3912 /// AssignedRegs - If this is a register or register class operand, this
3913 /// contains the set of register corresponding to the operand.
3914 RegsForValue AssignedRegs;
3916 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3917 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3920 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3921 /// busy in OutputRegs/InputRegs.
3922 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3923 std::set<unsigned> &OutputRegs,
3924 std::set<unsigned> &InputRegs,
3925 const TargetRegisterInfo &TRI) const {
3927 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3928 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3931 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3932 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3937 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3939 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3940 const TargetRegisterInfo &TRI) {
3941 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3943 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3944 for (; *Aliases; ++Aliases)
3945 Regs.insert(*Aliases);
3948 } // end anon namespace.
3951 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3952 /// specified operand. We prefer to assign virtual registers, to allow the
3953 /// register allocator handle the assignment process. However, if the asm uses
3954 /// features that we can't model on machineinstrs, we have SDISel do the
3955 /// allocation. This produces generally horrible, but correct, code.
3957 /// OpInfo describes the operand.
3958 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3959 /// or any explicitly clobbered registers.
3960 /// Input and OutputRegs are the set of already allocated physical registers.
3962 void SelectionDAGLowering::
3963 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3964 std::set<unsigned> &OutputRegs,
3965 std::set<unsigned> &InputRegs) {
3966 // Compute whether this value requires an input register, an output register,
3968 bool isOutReg = false;
3969 bool isInReg = false;
3970 switch (OpInfo.Type) {
3971 case InlineAsm::isOutput:
3974 // If this is an early-clobber output, or if there is an input
3975 // constraint that matches this, we need to reserve the input register
3976 // so no other inputs allocate to it.
3977 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3979 case InlineAsm::isInput:
3983 case InlineAsm::isClobber:
3990 MachineFunction &MF = DAG.getMachineFunction();
3991 SmallVector<unsigned, 4> Regs;
3993 // If this is a constraint for a single physreg, or a constraint for a
3994 // register class, find it.
3995 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3996 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3997 OpInfo.ConstraintVT);
3999 unsigned NumRegs = 1;
4000 if (OpInfo.ConstraintVT != MVT::Other)
4001 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4003 MVT ValueVT = OpInfo.ConstraintVT;
4006 // If this is a constraint for a specific physical register, like {r17},
4008 if (PhysReg.first) {
4009 if (OpInfo.ConstraintVT == MVT::Other)
4010 ValueVT = *PhysReg.second->vt_begin();
4012 // Get the actual register value type. This is important, because the user
4013 // may have asked for (e.g.) the AX register in i32 type. We need to
4014 // remember that AX is actually i16 to get the right extension.
4015 RegVT = *PhysReg.second->vt_begin();
4017 // This is a explicit reference to a physical register.
4018 Regs.push_back(PhysReg.first);
4020 // If this is an expanded reference, add the rest of the regs to Regs.
4022 TargetRegisterClass::iterator I = PhysReg.second->begin();
4023 for (; *I != PhysReg.first; ++I)
4024 assert(I != PhysReg.second->end() && "Didn't find reg!");
4026 // Already added the first reg.
4028 for (; NumRegs; --NumRegs, ++I) {
4029 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4033 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4034 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4035 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4039 // Otherwise, if this was a reference to an LLVM register class, create vregs
4040 // for this reference.
4041 std::vector<unsigned> RegClassRegs;
4042 const TargetRegisterClass *RC = PhysReg.second;
4044 // If this is an early clobber or tied register, our regalloc doesn't know
4045 // how to maintain the constraint. If it isn't, go ahead and create vreg
4046 // and let the regalloc do the right thing.
4047 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4048 // If there is some other early clobber and this is an input register,
4049 // then we are forced to pre-allocate the input reg so it doesn't
4050 // conflict with the earlyclobber.
4051 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
4052 RegVT = *PhysReg.second->vt_begin();
4054 if (OpInfo.ConstraintVT == MVT::Other)
4057 // Create the appropriate number of virtual registers.
4058 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4059 for (; NumRegs; --NumRegs)
4060 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4062 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4066 // Otherwise, we can't allocate it. Let the code below figure out how to
4067 // maintain these constraints.
4068 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4071 // This is a reference to a register class that doesn't directly correspond
4072 // to an LLVM register class. Allocate NumRegs consecutive, available,
4073 // registers from the class.
4074 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4075 OpInfo.ConstraintVT);
4078 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4079 unsigned NumAllocated = 0;
4080 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4081 unsigned Reg = RegClassRegs[i];
4082 // See if this register is available.
4083 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4084 (isInReg && InputRegs.count(Reg))) { // Already used.
4085 // Make sure we find consecutive registers.
4090 // Check to see if this register is allocatable (i.e. don't give out the
4093 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4094 if (!RC) { // Couldn't allocate this register.
4095 // Reset NumAllocated to make sure we return consecutive registers.
4101 // Okay, this register is good, we can use it.
4104 // If we allocated enough consecutive registers, succeed.
4105 if (NumAllocated == NumRegs) {
4106 unsigned RegStart = (i-NumAllocated)+1;
4107 unsigned RegEnd = i+1;
4108 // Mark all of the allocated registers used.
4109 for (unsigned i = RegStart; i != RegEnd; ++i)
4110 Regs.push_back(RegClassRegs[i]);
4112 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4113 OpInfo.ConstraintVT);
4114 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4119 // Otherwise, we couldn't allocate enough registers for this.
4123 /// visitInlineAsm - Handle a call to an InlineAsm object.
4125 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4126 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4128 /// ConstraintOperands - Information about all of the constraints.
4129 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4131 SDValue Chain = getRoot();
4134 std::set<unsigned> OutputRegs, InputRegs;
4136 // Do a prepass over the constraints, canonicalizing them, and building up the
4137 // ConstraintOperands list.
4138 std::vector<InlineAsm::ConstraintInfo>
4139 ConstraintInfos = IA->ParseConstraints();
4141 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4142 // constraint. If so, we can't let the register allocator allocate any input
4143 // registers, because it will not know to avoid the earlyclobbered output reg.
4144 bool SawEarlyClobber = false;
4146 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4147 unsigned ResNo = 0; // ResNo - The result number of the next output.
4148 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4149 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4150 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4152 MVT OpVT = MVT::Other;
4154 // Compute the value type for each operand.
4155 switch (OpInfo.Type) {
4156 case InlineAsm::isOutput:
4157 // Indirect outputs just consume an argument.
4158 if (OpInfo.isIndirect) {
4159 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4162 // The return value of the call is this value. As such, there is no
4163 // corresponding argument.
4164 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4165 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4166 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4168 assert(ResNo == 0 && "Asm only has one result!");
4169 OpVT = TLI.getValueType(CS.getType());
4173 case InlineAsm::isInput:
4174 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4176 case InlineAsm::isClobber:
4181 // If this is an input or an indirect output, process the call argument.
4182 // BasicBlocks are labels, currently appearing only in asm's.
4183 if (OpInfo.CallOperandVal) {
4184 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4185 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4187 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4188 const Type *OpTy = OpInfo.CallOperandVal->getType();
4189 // If this is an indirect operand, the operand is a pointer to the
4191 if (OpInfo.isIndirect)
4192 OpTy = cast<PointerType>(OpTy)->getElementType();
4194 // If OpTy is not a single value, it may be a struct/union that we
4195 // can tile with integers.
4196 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4197 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4205 OpTy = IntegerType::get(BitSize);
4210 OpVT = TLI.getValueType(OpTy, true);
4214 OpInfo.ConstraintVT = OpVT;
4216 // Compute the constraint code and ConstraintType to use.
4217 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
4219 // Keep track of whether we see an earlyclobber.
4220 SawEarlyClobber |= OpInfo.isEarlyClobber;
4222 // If we see a clobber of a register, it is an early clobber.
4223 if (!SawEarlyClobber &&
4224 OpInfo.Type == InlineAsm::isClobber &&
4225 OpInfo.ConstraintType == TargetLowering::C_Register) {
4226 // Note that we want to ignore things that we don't trick here, like
4227 // dirflag, fpsr, flags, etc.
4228 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4229 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4230 OpInfo.ConstraintVT);
4231 if (PhysReg.first || PhysReg.second) {
4232 // This is a register we know of.
4233 SawEarlyClobber = true;
4237 // If this is a memory input, and if the operand is not indirect, do what we
4238 // need to to provide an address for the memory input.
4239 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4240 !OpInfo.isIndirect) {
4241 assert(OpInfo.Type == InlineAsm::isInput &&
4242 "Can only indirectify direct input operands!");
4244 // Memory operands really want the address of the value. If we don't have
4245 // an indirect input, put it in the constpool if we can, otherwise spill
4246 // it to a stack slot.
4248 // If the operand is a float, integer, or vector constant, spill to a
4249 // constant pool entry to get its address.
4250 Value *OpVal = OpInfo.CallOperandVal;
4251 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4252 isa<ConstantVector>(OpVal)) {
4253 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4254 TLI.getPointerTy());
4256 // Otherwise, create a stack slot and emit a store to it before the
4258 const Type *Ty = OpVal->getType();
4259 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4260 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4261 MachineFunction &MF = DAG.getMachineFunction();
4262 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4263 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4264 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4265 OpInfo.CallOperand = StackSlot;
4268 // There is no longer a Value* corresponding to this operand.
4269 OpInfo.CallOperandVal = 0;
4270 // It is now an indirect operand.
4271 OpInfo.isIndirect = true;
4274 // If this constraint is for a specific register, allocate it before
4276 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4277 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4279 ConstraintInfos.clear();
4282 // Second pass - Loop over all of the operands, assigning virtual or physregs
4283 // to registerclass operands.
4284 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4285 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4287 // C_Register operands have already been allocated, Other/Memory don't need
4289 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4290 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4293 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4294 std::vector<SDValue> AsmNodeOperands;
4295 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4296 AsmNodeOperands.push_back(
4297 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4300 // Loop over all of the inputs, copying the operand values into the
4301 // appropriate registers and processing the output regs.
4302 RegsForValue RetValRegs;
4304 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4305 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4307 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4308 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4310 switch (OpInfo.Type) {
4311 case InlineAsm::isOutput: {
4312 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4313 OpInfo.ConstraintType != TargetLowering::C_Register) {
4314 // Memory output, or 'other' output (e.g. 'X' constraint).
4315 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4317 // Add information to the INLINEASM node to know about this output.
4318 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4319 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4320 TLI.getPointerTy()));
4321 AsmNodeOperands.push_back(OpInfo.CallOperand);
4325 // Otherwise, this is a register or register class output.
4327 // Copy the output from the appropriate register. Find a register that
4329 if (OpInfo.AssignedRegs.Regs.empty()) {
4330 cerr << "Couldn't allocate output reg for constraint '"
4331 << OpInfo.ConstraintCode << "'!\n";
4335 // If this is an indirect operand, store through the pointer after the
4337 if (OpInfo.isIndirect) {
4338 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4339 OpInfo.CallOperandVal));
4341 // This is the result value of the call.
4342 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4343 // Concatenate this output onto the outputs list.
4344 RetValRegs.append(OpInfo.AssignedRegs);
4347 // Add information to the INLINEASM node to know that this register is
4349 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4353 case InlineAsm::isInput: {
4354 SDValue InOperandVal = OpInfo.CallOperand;
4356 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
4357 // If this is required to match an output register we have already set,
4358 // just use its register.
4359 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4361 // Scan until we find the definition we already emitted of this operand.
4362 // When we find it, create a RegsForValue operand.
4363 unsigned CurOp = 2; // The first operand.
4364 for (; OperandNo; --OperandNo) {
4365 // Advance to the next operand.
4367 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4368 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4369 (NumOps & 7) == 4 /*MEM*/) &&
4370 "Skipped past definitions?");
4371 CurOp += (NumOps>>3)+1;
4375 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4376 if ((NumOps & 7) == 2 /*REGDEF*/) {
4377 // Add NumOps>>3 registers to MatchedRegs.
4378 RegsForValue MatchedRegs;
4379 MatchedRegs.TLI = &TLI;
4380 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4381 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4382 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4384 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4385 MatchedRegs.Regs.push_back(Reg);
4388 // Use the produced MatchedRegs object to
4389 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4390 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4393 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4394 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4395 // Add information to the INLINEASM node to know about this input.
4396 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4397 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4398 TLI.getPointerTy()));
4399 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4404 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4405 assert(!OpInfo.isIndirect &&
4406 "Don't know how to handle indirect other inputs yet!");
4408 std::vector<SDValue> Ops;
4409 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4412 cerr << "Invalid operand for inline asm constraint '"
4413 << OpInfo.ConstraintCode << "'!\n";
4417 // Add information to the INLINEASM node to know about this input.
4418 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4419 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4420 TLI.getPointerTy()));
4421 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4423 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4424 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4425 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4426 "Memory operands expect pointer values");
4428 // Add information to the INLINEASM node to know about this input.
4429 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4430 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4431 TLI.getPointerTy()));
4432 AsmNodeOperands.push_back(InOperandVal);
4436 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4437 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4438 "Unknown constraint type!");
4439 assert(!OpInfo.isIndirect &&
4440 "Don't know how to handle indirect register inputs yet!");
4442 // Copy the input into the appropriate registers.
4443 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4444 "Couldn't allocate input reg!");
4446 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4448 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4452 case InlineAsm::isClobber: {
4453 // Add the clobbered value to the operand list, so that the register
4454 // allocator is aware that the physreg got clobbered.
4455 if (!OpInfo.AssignedRegs.Regs.empty())
4456 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4463 // Finish up input operands.
4464 AsmNodeOperands[0] = Chain;
4465 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4467 Chain = DAG.getNode(ISD::INLINEASM,
4468 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4469 &AsmNodeOperands[0], AsmNodeOperands.size());
4470 Flag = Chain.getValue(1);
4472 // If this asm returns a register value, copy the result from that register
4473 // and set it as the value of the call.
4474 if (!RetValRegs.Regs.empty()) {
4475 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4477 // If any of the results of the inline asm is a vector, it may have the
4478 // wrong width/num elts. This can happen for register classes that can
4479 // contain multiple different value types. The preg or vreg allocated may
4480 // not have the same VT as was expected. Convert it to the right type with
4482 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4483 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4484 if (Val.Val->getValueType(i).isVector())
4485 Val = DAG.getNode(ISD::BIT_CONVERT,
4486 TLI.getValueType(ResSTy->getElementType(i)), Val);
4489 if (Val.getValueType().isVector())
4490 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4494 setValue(CS.getInstruction(), Val);
4497 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
4499 // Process indirect outputs, first output all of the flagged copies out of
4501 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4502 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4503 Value *Ptr = IndirectStoresToEmit[i].second;
4504 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4505 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4508 // Emit the non-flagged stores from the physregs.
4509 SmallVector<SDValue, 8> OutChains;
4510 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4511 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4512 getValue(StoresToEmit[i].second),
4513 StoresToEmit[i].second, 0));
4514 if (!OutChains.empty())
4515 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4516 &OutChains[0], OutChains.size());
4521 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4522 SDValue Src = getValue(I.getOperand(0));
4524 MVT IntPtr = TLI.getPointerTy();
4526 if (IntPtr.bitsLT(Src.getValueType()))
4527 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4528 else if (IntPtr.bitsGT(Src.getValueType()))
4529 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4531 // Scale the source by the type size.
4532 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4533 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4534 Src, DAG.getIntPtrConstant(ElementSize));
4536 TargetLowering::ArgListTy Args;
4537 TargetLowering::ArgListEntry Entry;
4539 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4540 Args.push_back(Entry);
4542 std::pair<SDValue,SDValue> Result =
4543 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4544 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4545 setValue(&I, Result.first); // Pointers always fit in registers
4546 DAG.setRoot(Result.second);
4549 void SelectionDAGLowering::visitFree(FreeInst &I) {
4550 TargetLowering::ArgListTy Args;
4551 TargetLowering::ArgListEntry Entry;
4552 Entry.Node = getValue(I.getOperand(0));
4553 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4554 Args.push_back(Entry);
4555 MVT IntPtr = TLI.getPointerTy();
4556 std::pair<SDValue,SDValue> Result =
4557 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4558 CallingConv::C, true,
4559 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4560 DAG.setRoot(Result.second);
4563 // EmitInstrWithCustomInserter - This method should be implemented by targets
4564 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
4565 // instructions are special in various ways, which require special support to
4566 // insert. The specified MachineInstr is created but not inserted into any
4567 // basic blocks, and the scheduler passes ownership of it to this method.
4568 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4569 MachineBasicBlock *MBB) {
4570 cerr << "If a target marks an instruction with "
4571 << "'usesCustomDAGSchedInserter', it must implement "
4572 << "TargetLowering::EmitInstrWithCustomInserter!\n";
4577 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4578 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4579 getValue(I.getOperand(1)),
4580 DAG.getSrcValue(I.getOperand(1))));
4583 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4584 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4585 getValue(I.getOperand(0)),
4586 DAG.getSrcValue(I.getOperand(0)));
4588 DAG.setRoot(V.getValue(1));
4591 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4592 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4593 getValue(I.getOperand(1)),
4594 DAG.getSrcValue(I.getOperand(1))));
4597 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4598 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4599 getValue(I.getOperand(1)),
4600 getValue(I.getOperand(2)),
4601 DAG.getSrcValue(I.getOperand(1)),
4602 DAG.getSrcValue(I.getOperand(2))));
4605 /// TargetLowering::LowerArguments - This is the default LowerArguments
4606 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4607 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4608 /// integrated into SDISel.
4609 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
4610 SmallVectorImpl<SDValue> &ArgValues) {
4611 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4612 SmallVector<SDValue, 3+16> Ops;
4613 Ops.push_back(DAG.getRoot());
4614 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4615 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4617 // Add one result value for each formal argument.
4618 SmallVector<MVT, 16> RetVals;
4620 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4622 SmallVector<MVT, 4> ValueVTs;
4623 ComputeValueVTs(*this, I->getType(), ValueVTs);
4624 for (unsigned Value = 0, NumValues = ValueVTs.size();
4625 Value != NumValues; ++Value) {
4626 MVT VT = ValueVTs[Value];
4627 const Type *ArgTy = VT.getTypeForMVT();
4628 ISD::ArgFlagsTy Flags;
4629 unsigned OriginalAlignment =
4630 getTargetData()->getABITypeAlignment(ArgTy);
4632 if (F.paramHasAttr(j, ParamAttr::ZExt))
4634 if (F.paramHasAttr(j, ParamAttr::SExt))
4636 if (F.paramHasAttr(j, ParamAttr::InReg))
4638 if (F.paramHasAttr(j, ParamAttr::StructRet))
4640 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4642 const PointerType *Ty = cast<PointerType>(I->getType());
4643 const Type *ElementTy = Ty->getElementType();
4644 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4645 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4646 // For ByVal, alignment should be passed from FE. BE will guess if
4647 // this info is not there but there are cases it cannot get right.
4648 if (F.getParamAlignment(j))
4649 FrameAlign = F.getParamAlignment(j);
4650 Flags.setByValAlign(FrameAlign);
4651 Flags.setByValSize(FrameSize);
4653 if (F.paramHasAttr(j, ParamAttr::Nest))
4655 Flags.setOrigAlign(OriginalAlignment);
4657 MVT RegisterVT = getRegisterType(VT);
4658 unsigned NumRegs = getNumRegisters(VT);
4659 for (unsigned i = 0; i != NumRegs; ++i) {
4660 RetVals.push_back(RegisterVT);
4661 ISD::ArgFlagsTy MyFlags = Flags;
4662 if (NumRegs > 1 && i == 0)
4664 // if it isn't first piece, alignment must be 1
4666 MyFlags.setOrigAlign(1);
4667 Ops.push_back(DAG.getArgFlags(MyFlags));
4672 RetVals.push_back(MVT::Other);
4675 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4676 DAG.getVTList(&RetVals[0], RetVals.size()),
4677 &Ops[0], Ops.size()).Val;
4679 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4680 // allows exposing the loads that may be part of the argument access to the
4681 // first DAGCombiner pass.
4682 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
4684 // The number of results should match up, except that the lowered one may have
4685 // an extra flag result.
4686 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4687 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4688 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4689 && "Lowering produced unexpected number of results!");
4691 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
4692 if (Result != TmpRes.Val && Result->use_empty()) {
4693 HandleSDNode Dummy(DAG.getRoot());
4694 DAG.RemoveDeadNode(Result);
4697 Result = TmpRes.Val;
4699 unsigned NumArgRegs = Result->getNumValues() - 1;
4700 DAG.setRoot(SDValue(Result, NumArgRegs));
4702 // Set up the return result vector.
4705 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4707 SmallVector<MVT, 4> ValueVTs;
4708 ComputeValueVTs(*this, I->getType(), ValueVTs);
4709 for (unsigned Value = 0, NumValues = ValueVTs.size();
4710 Value != NumValues; ++Value) {
4711 MVT VT = ValueVTs[Value];
4712 MVT PartVT = getRegisterType(VT);
4714 unsigned NumParts = getNumRegisters(VT);
4715 SmallVector<SDValue, 4> Parts(NumParts);
4716 for (unsigned j = 0; j != NumParts; ++j)
4717 Parts[j] = SDValue(Result, i++);
4719 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4720 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4721 AssertOp = ISD::AssertSext;
4722 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4723 AssertOp = ISD::AssertZext;
4725 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4729 assert(i == NumArgRegs && "Argument register count mismatch!");
4733 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4734 /// implementation, which just inserts an ISD::CALL node, which is later custom
4735 /// lowered by the target to something concrete. FIXME: When all targets are
4736 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4737 std::pair<SDValue, SDValue>
4738 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
4739 bool RetSExt, bool RetZExt, bool isVarArg,
4740 unsigned CallingConv, bool isTailCall,
4742 ArgListTy &Args, SelectionDAG &DAG) {
4743 SmallVector<SDValue, 32> Ops;
4744 Ops.push_back(Chain); // Op#0 - Chain
4745 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4746 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4747 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4748 Ops.push_back(Callee);
4750 // Handle all of the outgoing arguments.
4751 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4752 SmallVector<MVT, 4> ValueVTs;
4753 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4754 for (unsigned Value = 0, NumValues = ValueVTs.size();
4755 Value != NumValues; ++Value) {
4756 MVT VT = ValueVTs[Value];
4757 const Type *ArgTy = VT.getTypeForMVT();
4758 SDValue Op = SDValue(Args[i].Node.Val, Args[i].Node.ResNo + Value);
4759 ISD::ArgFlagsTy Flags;
4760 unsigned OriginalAlignment =
4761 getTargetData()->getABITypeAlignment(ArgTy);
4767 if (Args[i].isInReg)
4771 if (Args[i].isByVal) {
4773 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4774 const Type *ElementTy = Ty->getElementType();
4775 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4776 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4777 // For ByVal, alignment should come from FE. BE will guess if this
4778 // info is not there but there are cases it cannot get right.
4779 if (Args[i].Alignment)
4780 FrameAlign = Args[i].Alignment;
4781 Flags.setByValAlign(FrameAlign);
4782 Flags.setByValSize(FrameSize);
4786 Flags.setOrigAlign(OriginalAlignment);
4788 MVT PartVT = getRegisterType(VT);
4789 unsigned NumParts = getNumRegisters(VT);
4790 SmallVector<SDValue, 4> Parts(NumParts);
4791 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4794 ExtendKind = ISD::SIGN_EXTEND;
4795 else if (Args[i].isZExt)
4796 ExtendKind = ISD::ZERO_EXTEND;
4798 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4800 for (unsigned i = 0; i != NumParts; ++i) {
4801 // if it isn't first piece, alignment must be 1
4802 ISD::ArgFlagsTy MyFlags = Flags;
4803 if (NumParts > 1 && i == 0)
4806 MyFlags.setOrigAlign(1);
4808 Ops.push_back(Parts[i]);
4809 Ops.push_back(DAG.getArgFlags(MyFlags));
4814 // Figure out the result value types. We start by making a list of
4815 // the potentially illegal return value types.
4816 SmallVector<MVT, 4> LoweredRetTys;
4817 SmallVector<MVT, 4> RetTys;
4818 ComputeValueVTs(*this, RetTy, RetTys);
4820 // Then we translate that to a list of legal types.
4821 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4823 MVT RegisterVT = getRegisterType(VT);
4824 unsigned NumRegs = getNumRegisters(VT);
4825 for (unsigned i = 0; i != NumRegs; ++i)
4826 LoweredRetTys.push_back(RegisterVT);
4829 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4831 // Create the CALL node.
4832 SDValue Res = DAG.getNode(ISD::CALL,
4833 DAG.getVTList(&LoweredRetTys[0],
4834 LoweredRetTys.size()),
4835 &Ops[0], Ops.size());
4836 Chain = Res.getValue(LoweredRetTys.size() - 1);
4838 // Gather up the call result into a single value.
4839 if (RetTy != Type::VoidTy) {
4840 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4843 AssertOp = ISD::AssertSext;
4845 AssertOp = ISD::AssertZext;
4847 SmallVector<SDValue, 4> ReturnValues;
4849 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4851 MVT RegisterVT = getRegisterType(VT);
4852 unsigned NumRegs = getNumRegisters(VT);
4853 unsigned RegNoEnd = NumRegs + RegNo;
4854 SmallVector<SDValue, 4> Results;
4855 for (; RegNo != RegNoEnd; ++RegNo)
4856 Results.push_back(Res.getValue(RegNo));
4857 SDValue ReturnValue =
4858 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4860 ReturnValues.push_back(ReturnValue);
4862 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
4863 &ReturnValues[0], ReturnValues.size());
4866 return std::make_pair(Res, Chain);
4869 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
4870 assert(0 && "LowerOperation not implemented for this target!");
4876 //===----------------------------------------------------------------------===//
4877 // SelectionDAGISel code
4878 //===----------------------------------------------------------------------===//
4880 unsigned SelectionDAGISel::MakeReg(MVT VT) {
4881 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4884 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4885 AU.addRequired<AliasAnalysis>();
4886 AU.addRequired<GCModuleInfo>();
4887 AU.setPreservesAll();
4890 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4891 // Get alias analysis for load/store combining.
4892 AA = &getAnalysis<AliasAnalysis>();
4894 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4895 if (MF.getFunction()->hasGC())
4896 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
4899 RegInfo = &MF.getRegInfo();
4900 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4902 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4904 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4905 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4906 // Mark landing pad.
4907 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4909 SelectAllBasicBlocks(Fn, MF, FuncInfo);
4911 // Add function live-ins to entry block live-in set.
4912 BasicBlock *EntryBB = &Fn.getEntryBlock();
4913 BB = FuncInfo.MBBMap[EntryBB];
4914 if (!RegInfo->livein_empty())
4915 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4916 E = RegInfo->livein_end(); I != E; ++I)
4917 BB->addLiveIn(I->first);
4920 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4921 "Not all catch info was assigned to a landing pad!");
4927 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4928 SDValue Op = getValue(V);
4929 assert((Op.getOpcode() != ISD::CopyFromReg ||
4930 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4931 "Copy from a reg to the same reg!");
4932 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4934 RegsForValue RFV(TLI, Reg, V->getType());
4935 SDValue Chain = DAG.getEntryNode();
4936 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4937 PendingExports.push_back(Chain);
4940 void SelectionDAGISel::
4941 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4942 // If this is the entry block, emit arguments.
4943 Function &F = *LLVMBB->getParent();
4944 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4945 SDValue OldRoot = SDL.DAG.getRoot();
4946 SmallVector<SDValue, 16> Args;
4947 TLI.LowerArguments(F, SDL.DAG, Args);
4950 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4952 SmallVector<MVT, 4> ValueVTs;
4953 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4954 unsigned NumValues = ValueVTs.size();
4955 if (!AI->use_empty()) {
4956 SDL.setValue(AI, SDL.DAG.getMergeValues(&Args[a], NumValues));
4957 // If this argument is live outside of the entry block, insert a copy from
4958 // whereever we got it to the vreg that other BB's will reference it as.
4959 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4960 if (VMI != FuncInfo.ValueMap.end()) {
4961 SDL.CopyValueToVirtualRegister(AI, VMI->second);
4967 // Finally, if the target has anything special to do, allow it to do so.
4968 // FIXME: this should insert code into the DAG!
4969 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4972 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4973 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4974 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4975 if (isSelector(I)) {
4976 // Apply the catch info to DestBB.
4977 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4979 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4980 FLI.CatchInfoFound.insert(I);
4985 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4986 /// whether object offset >= 0.
4988 IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDValue Op) {
4989 if (!isa<FrameIndexSDNode>(Op)) return false;
4991 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4992 int FrameIdx = FrameIdxNode->getIndex();
4993 return MFI->isFixedObjectIndex(FrameIdx) &&
4994 MFI->getObjectOffset(FrameIdx) >= 0;
4997 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4998 /// possibly be overwritten when lowering the outgoing arguments in a tail
4999 /// call. Currently the implementation of this call is very conservative and
5000 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
5001 /// virtual registers would be overwritten by direct lowering.
5002 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
5003 MachineFrameInfo * MFI) {
5004 RegisterSDNode * OpReg = NULL;
5005 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
5006 (Op.getOpcode()== ISD::CopyFromReg &&
5007 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
5008 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
5009 (Op.getOpcode() == ISD::LOAD &&
5010 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
5011 (Op.getOpcode() == ISD::MERGE_VALUES &&
5012 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
5013 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
5019 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
5020 /// DAG and fixes their tailcall attribute operand.
5021 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
5022 TargetLowering& TLI) {
5023 SDNode * Ret = NULL;
5024 SDValue Terminator = DAG.getRoot();
5027 if (Terminator.getOpcode() == ISD::RET) {
5028 Ret = Terminator.Val;
5031 // Fix tail call attribute of CALL nodes.
5032 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
5033 BI = DAG.allnodes_end(); BI != BE; ) {
5035 if (BI->getOpcode() == ISD::CALL) {
5036 SDValue OpRet(Ret, 0);
5037 SDValue OpCall(BI, 0);
5038 bool isMarkedTailCall =
5039 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5040 // If CALL node has tail call attribute set to true and the call is not
5041 // eligible (no RET or the target rejects) the attribute is fixed to
5042 // false. The TargetLowering::IsEligibleForTailCallOptimization function
5043 // must correctly identify tail call optimizable calls.
5044 if (!isMarkedTailCall) continue;
5046 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5047 // Not eligible. Mark CALL node as non tail call.
5048 SmallVector<SDValue, 32> Ops;
5050 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5051 E = OpCall.Val->op_end(); I != E; I++, idx++) {
5055 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5057 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
5059 // Look for tail call clobbered arguments. Emit a series of
5060 // copyto/copyfrom virtual register nodes to protect them.
5061 SmallVector<SDValue, 32> Ops;
5062 SDValue Chain = OpCall.getOperand(0), InFlag;
5064 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5065 E = OpCall.Val->op_end(); I != E; I++, idx++) {
5067 if (idx > 4 && (idx % 2)) {
5068 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5069 getArgFlags().isByVal();
5070 MachineFunction &MF = DAG.getMachineFunction();
5071 MachineFrameInfo *MFI = MF.getFrameInfo();
5073 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
5074 MVT VT = Arg.getValueType();
5075 unsigned VReg = MF.getRegInfo().
5076 createVirtualRegister(TLI.getRegClassFor(VT));
5077 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5078 InFlag = Chain.getValue(1);
5079 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5080 Chain = Arg.getValue(1);
5081 InFlag = Arg.getValue(2);
5086 // Link in chain of CopyTo/CopyFromReg.
5088 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
5094 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
5095 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5096 FunctionLoweringInfo &FuncInfo) {
5097 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GFI);
5098 BB = FuncInfo.MBBMap[LLVMBB];
5100 // Before doing SelectionDAG ISel, see if FastISel has been requested.
5101 // FastISel doesn't currently support entry blocks, because that
5102 // requires special handling for arguments. And it doesn't support EH
5103 // landing pads, which also require special handling.
5104 // For now, also exclude blocks with terminators that aren't
5105 // unconditional branches.
5106 if (EnableFastISel &&
5107 LLVMBB != &LLVMBB->getParent()->getEntryBlock() &&
5108 !BB->isLandingPad() &&
5109 isa<BranchInst>(LLVMBB->getTerminator()) &&
5110 cast<BranchInst>(LLVMBB->getTerminator())->isUnconditional()) {
5111 if (FastISel *F = TLI.createFastISel(BB, &FuncInfo.MF,
5112 TLI.getTargetMachine().getInstrInfo())) {
5113 BasicBlock::iterator I =
5114 F->SelectInstructions(LLVMBB->begin(), LLVMBB->end(), FuncInfo.ValueMap);
5115 if (I == LLVMBB->end())
5116 // The "fast" selector selected the entire block, so we're done.
5119 // The "fast" selector couldn't handle something and bailed.
5120 // For the temporary purpose of debugging, just abort.
5122 assert(0 && "FastISel didn't select the entire block");
5127 // Lower any arguments needed in this block if this is the entry block.
5128 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
5129 LowerArguments(LLVMBB, SDL);
5131 SDL.setCurrentBasicBlock(BB);
5133 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
5135 if (MMI && BB->isLandingPad()) {
5136 // Add a label to mark the beginning of the landing pad. Deletion of the
5137 // landing pad can thus be detected via the MachineModuleInfo.
5138 unsigned LabelID = MMI->addLandingPad(BB);
5139 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, DAG.getEntryNode(), LabelID));
5141 // Mark exception register as live in.
5142 unsigned Reg = TLI.getExceptionAddressRegister();
5143 if (Reg) BB->addLiveIn(Reg);
5145 // Mark exception selector register as live in.
5146 Reg = TLI.getExceptionSelectorRegister();
5147 if (Reg) BB->addLiveIn(Reg);
5149 // FIXME: Hack around an exception handling flaw (PR1508): the personality
5150 // function and list of typeids logically belong to the invoke (or, if you
5151 // like, the basic block containing the invoke), and need to be associated
5152 // with it in the dwarf exception handling tables. Currently however the
5153 // information is provided by an intrinsic (eh.selector) that can be moved
5154 // to unexpected places by the optimizers: if the unwind edge is critical,
5155 // then breaking it can result in the intrinsics being in the successor of
5156 // the landing pad, not the landing pad itself. This results in exceptions
5157 // not being caught because no typeids are associated with the invoke.
5158 // This may not be the only way things can go wrong, but it is the only way
5159 // we try to work around for the moment.
5160 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5162 if (Br && Br->isUnconditional()) { // Critical edge?
5163 BasicBlock::iterator I, E;
5164 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
5169 // No catch info found - try to extract some from the successor.
5170 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
5174 // Lower all of the non-terminator instructions.
5175 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
5179 // Ensure that all instructions which are used outside of their defining
5180 // blocks are available as virtual registers. Invoke is handled elsewhere.
5181 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
5182 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
5183 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
5184 if (VMI != FuncInfo.ValueMap.end())
5185 SDL.CopyValueToVirtualRegister(I, VMI->second);
5188 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5189 // ensure constants are generated when needed. Remember the virtual registers
5190 // that need to be added to the Machine PHI nodes as input. We cannot just
5191 // directly add them, because expansion might result in multiple MBB's for one
5192 // BB. As such, the start of the BB might correspond to a different MBB than
5195 TerminatorInst *TI = LLVMBB->getTerminator();
5197 // Emit constants only once even if used by multiple PHI nodes.
5198 std::map<Constant*, unsigned> ConstantsOut;
5200 // Vector bool would be better, but vector<bool> is really slow.
5201 std::vector<unsigned char> SuccsHandled;
5202 if (TI->getNumSuccessors())
5203 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
5205 // Check successor nodes' PHI nodes that expect a constant to be available
5207 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5208 BasicBlock *SuccBB = TI->getSuccessor(succ);
5209 if (!isa<PHINode>(SuccBB->begin())) continue;
5210 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
5212 // If this terminator has multiple identical successors (common for
5213 // switches), only handle each succ once.
5214 unsigned SuccMBBNo = SuccMBB->getNumber();
5215 if (SuccsHandled[SuccMBBNo]) continue;
5216 SuccsHandled[SuccMBBNo] = true;
5218 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5221 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5222 // nodes and Machine PHI nodes, but the incoming operands have not been
5224 for (BasicBlock::iterator I = SuccBB->begin();
5225 (PN = dyn_cast<PHINode>(I)); ++I) {
5226 // Ignore dead phi's.
5227 if (PN->use_empty()) continue;
5230 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5232 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5233 unsigned &RegOut = ConstantsOut[C];
5235 RegOut = FuncInfo.CreateRegForValue(C);
5236 SDL.CopyValueToVirtualRegister(C, RegOut);
5240 Reg = FuncInfo.ValueMap[PHIOp];
5242 assert(isa<AllocaInst>(PHIOp) &&
5243 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5244 "Didn't codegen value into a register!??");
5245 Reg = FuncInfo.CreateRegForValue(PHIOp);
5246 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
5250 // Remember that this register needs to added to the machine PHI node as
5251 // the input for this MBB.
5252 SmallVector<MVT, 4> ValueVTs;
5253 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5254 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5255 MVT VT = ValueVTs[vti];
5256 unsigned NumRegisters = TLI.getNumRegisters(VT);
5257 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5258 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5259 Reg += NumRegisters;
5263 ConstantsOut.clear();
5265 // Lower the terminator after the copies are emitted.
5266 SDL.visit(*LLVMBB->getTerminator());
5268 // Copy over any CaseBlock records that may now exist due to SwitchInst
5269 // lowering, as well as any jump table information.
5270 SwitchCases.clear();
5271 SwitchCases = SDL.SwitchCases;
5273 JTCases = SDL.JTCases;
5274 BitTestCases.clear();
5275 BitTestCases = SDL.BitTestCases;
5277 // Make sure the root of the DAG is up-to-date.
5278 DAG.setRoot(SDL.getControlRoot());
5280 // Check whether calls in this block are real tail calls. Fix up CALL nodes
5281 // with correct tailcall attribute so that the target can rely on the tailcall
5282 // attribute indicating whether the call is really eligible for tail call
5284 CheckDAGForTailCallsAndFixThem(DAG, TLI);
5287 void SelectionDAGISel::ComputeLiveOutVRegInfo(SelectionDAG &DAG) {
5288 SmallPtrSet<SDNode*, 128> VisitedNodes;
5289 SmallVector<SDNode*, 128> Worklist;
5291 Worklist.push_back(DAG.getRoot().Val);
5297 while (!Worklist.empty()) {
5298 SDNode *N = Worklist.back();
5299 Worklist.pop_back();
5301 // If we've already seen this node, ignore it.
5302 if (!VisitedNodes.insert(N))
5305 // Otherwise, add all chain operands to the worklist.
5306 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5307 if (N->getOperand(i).getValueType() == MVT::Other)
5308 Worklist.push_back(N->getOperand(i).Val);
5310 // If this is a CopyToReg with a vreg dest, process it.
5311 if (N->getOpcode() != ISD::CopyToReg)
5314 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
5315 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
5318 // Ignore non-scalar or non-integer values.
5319 SDValue Src = N->getOperand(2);
5320 MVT SrcVT = Src.getValueType();
5321 if (!SrcVT.isInteger() || SrcVT.isVector())
5324 unsigned NumSignBits = DAG.ComputeNumSignBits(Src);
5325 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
5326 DAG.ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
5328 // Only install this information if it tells us something.
5329 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
5330 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
5331 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5332 if (DestReg >= FLI.LiveOutRegInfo.size())
5333 FLI.LiveOutRegInfo.resize(DestReg+1);
5334 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
5335 LOI.NumSignBits = NumSignBits;
5336 LOI.KnownOne = NumSignBits;
5337 LOI.KnownZero = NumSignBits;
5342 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
5343 std::string GroupName;
5344 if (TimePassesIsEnabled)
5345 GroupName = "Instruction Selection and Scheduling";
5346 std::string BlockName;
5347 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
5348 ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs || ViewSUnitDAGs)
5349 BlockName = DAG.getMachineFunction().getFunction()->getName() + ':' +
5350 BB->getBasicBlock()->getName();
5352 DOUT << "Initial selection DAG:\n";
5355 if (ViewDAGCombine1) DAG.viewGraph("dag-combine1 input for " + BlockName);
5357 // Run the DAG combiner in pre-legalize mode.
5358 if (TimePassesIsEnabled) {
5359 NamedRegionTimer T("DAG Combining 1", GroupName);
5360 DAG.Combine(false, *AA);
5362 DAG.Combine(false, *AA);
5365 DOUT << "Optimized lowered selection DAG:\n";
5368 // Second step, hack on the DAG until it only uses operations and types that
5369 // the target supports.
5370 if (EnableLegalizeTypes) {// Enable this some day.
5371 if (ViewLegalizeTypesDAGs) DAG.viewGraph("legalize-types input for " +
5374 if (TimePassesIsEnabled) {
5375 NamedRegionTimer T("Type Legalization", GroupName);
5376 DAG.LegalizeTypes();
5378 DAG.LegalizeTypes();
5381 DOUT << "Type-legalized selection DAG:\n";
5384 // TODO: enable a dag combine pass here.
5387 if (ViewLegalizeDAGs) DAG.viewGraph("legalize input for " + BlockName);
5389 if (TimePassesIsEnabled) {
5390 NamedRegionTimer T("DAG Legalization", GroupName);
5396 DOUT << "Legalized selection DAG:\n";
5399 if (ViewDAGCombine2) DAG.viewGraph("dag-combine2 input for " + BlockName);
5401 // Run the DAG combiner in post-legalize mode.
5402 if (TimePassesIsEnabled) {
5403 NamedRegionTimer T("DAG Combining 2", GroupName);
5404 DAG.Combine(true, *AA);
5406 DAG.Combine(true, *AA);
5409 DOUT << "Optimized legalized selection DAG:\n";
5412 if (ViewISelDAGs) DAG.viewGraph("isel input for " + BlockName);
5414 if (!Fast && EnableValueProp)
5415 ComputeLiveOutVRegInfo(DAG);
5417 // Third, instruction select all of the operations to machine code, adding the
5418 // code to the MachineBasicBlock.
5419 if (TimePassesIsEnabled) {
5420 NamedRegionTimer T("Instruction Selection", GroupName);
5421 InstructionSelect(DAG);
5423 InstructionSelect(DAG);
5426 DOUT << "Selected selection DAG:\n";
5429 if (ViewSchedDAGs) DAG.viewGraph("scheduler input for " + BlockName);
5431 // Schedule machine code.
5432 ScheduleDAG *Scheduler;
5433 if (TimePassesIsEnabled) {
5434 NamedRegionTimer T("Instruction Scheduling", GroupName);
5435 Scheduler = Schedule(DAG);
5437 Scheduler = Schedule(DAG);
5440 if (ViewSUnitDAGs) Scheduler->viewGraph();
5442 // Emit machine code to BB. This can change 'BB' to the last block being
5444 if (TimePassesIsEnabled) {
5445 NamedRegionTimer T("Instruction Creation", GroupName);
5446 BB = Scheduler->EmitSchedule();
5448 BB = Scheduler->EmitSchedule();
5451 // Free the scheduler state.
5452 if (TimePassesIsEnabled) {
5453 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
5459 // Perform target specific isel post processing.
5460 if (TimePassesIsEnabled) {
5461 NamedRegionTimer T("Instruction Selection Post Processing", GroupName);
5462 InstructionSelectPostProcessing();
5464 InstructionSelectPostProcessing();
5467 DOUT << "Selected machine code:\n";
5471 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF,
5472 FunctionLoweringInfo &FuncInfo) {
5473 // Define NodeAllocator here so that memory allocation is reused for
5474 // each basic block.
5475 NodeAllocatorType NodeAllocator;
5477 SimpleBBISel SISel(MF, TLI);
5478 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5479 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
5480 BasicBlock *LLVMBB = &*I;
5481 PHINodesToUpdate.clear();
5483 if (!Fast || !SISel.SelectBasicBlock(LLVMBB, FuncInfo.MBBMap[LLVMBB]))
5484 SelectBasicBlock(LLVMBB, MF, FuncInfo, PHINodesToUpdate, NodeAllocator);
5485 FinishBasicBlock(LLVMBB, MF, FuncInfo, PHINodesToUpdate, NodeAllocator);
5490 SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5491 FunctionLoweringInfo &FuncInfo,
5492 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5493 NodeAllocatorType &NodeAllocator) {
5494 SelectionDAG DAG(TLI, MF, FuncInfo,
5495 getAnalysisToUpdate<MachineModuleInfo>(),
5499 // First step, lower LLVM code to some DAG. This DAG may use operations and
5500 // types that are not supported by the target.
5501 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5503 // Second step, emit the lowered DAG as machine code.
5504 CodeGenAndEmitDAG(DAG);
5508 SelectionDAGISel::FinishBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5509 FunctionLoweringInfo &FuncInfo,
5510 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5511 NodeAllocatorType &NodeAllocator) {
5512 DOUT << "Total amount of phi nodes to update: "
5513 << PHINodesToUpdate.size() << "\n";
5514 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5515 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5516 << ", " << PHINodesToUpdate[i].second << ")\n";);
5518 // Next, now that we know what the last MBB the LLVM BB expanded is, update
5519 // PHI nodes in successors.
5520 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
5521 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5522 MachineInstr *PHI = PHINodesToUpdate[i].first;
5523 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5524 "This is not a machine PHI node that we are updating!");
5525 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5527 PHI->addOperand(MachineOperand::CreateMBB(BB));
5532 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5533 // Lower header first, if it wasn't already lowered
5534 if (!BitTestCases[i].Emitted) {
5535 SelectionDAG HSDAG(TLI, MF, FuncInfo,
5536 getAnalysisToUpdate<MachineModuleInfo>(),
5539 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GFI);
5540 // Set the current basic block to the mbb we wish to insert the code into
5541 BB = BitTestCases[i].Parent;
5542 HSDL.setCurrentBasicBlock(BB);
5544 HSDL.visitBitTestHeader(BitTestCases[i]);
5545 HSDAG.setRoot(HSDL.getRoot());
5546 CodeGenAndEmitDAG(HSDAG);
5549 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5550 SelectionDAG BSDAG(TLI, MF, FuncInfo,
5551 getAnalysisToUpdate<MachineModuleInfo>(),
5554 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GFI);
5555 // Set the current basic block to the mbb we wish to insert the code into
5556 BB = BitTestCases[i].Cases[j].ThisBB;
5557 BSDL.setCurrentBasicBlock(BB);
5560 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5561 BitTestCases[i].Reg,
5562 BitTestCases[i].Cases[j]);
5564 BSDL.visitBitTestCase(BitTestCases[i].Default,
5565 BitTestCases[i].Reg,
5566 BitTestCases[i].Cases[j]);
5569 BSDAG.setRoot(BSDL.getRoot());
5570 CodeGenAndEmitDAG(BSDAG);
5574 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5575 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5576 MachineBasicBlock *PHIBB = PHI->getParent();
5577 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5578 "This is not a machine PHI node that we are updating!");
5579 // This is "default" BB. We have two jumps to it. From "header" BB and
5580 // from last "case" BB.
5581 if (PHIBB == BitTestCases[i].Default) {
5582 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5584 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5585 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5587 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5590 // One of "cases" BB.
5591 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5592 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5593 if (cBB->succ_end() !=
5594 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
5595 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5597 PHI->addOperand(MachineOperand::CreateMBB(cBB));
5603 // If the JumpTable record is filled in, then we need to emit a jump table.
5604 // Updating the PHI nodes is tricky in this case, since we need to determine
5605 // whether the PHI is a successor of the range check MBB or the jump table MBB
5606 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5607 // Lower header first, if it wasn't already lowered
5608 if (!JTCases[i].first.Emitted) {
5609 SelectionDAG HSDAG(TLI, MF, FuncInfo,
5610 getAnalysisToUpdate<MachineModuleInfo>(),
5613 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GFI);
5614 // Set the current basic block to the mbb we wish to insert the code into
5615 BB = JTCases[i].first.HeaderBB;
5616 HSDL.setCurrentBasicBlock(BB);
5618 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5619 HSDAG.setRoot(HSDL.getRoot());
5620 CodeGenAndEmitDAG(HSDAG);
5623 SelectionDAG JSDAG(TLI, MF, FuncInfo,
5624 getAnalysisToUpdate<MachineModuleInfo>(),
5627 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GFI);
5628 // Set the current basic block to the mbb we wish to insert the code into
5629 BB = JTCases[i].second.MBB;
5630 JSDL.setCurrentBasicBlock(BB);
5632 JSDL.visitJumpTable(JTCases[i].second);
5633 JSDAG.setRoot(JSDL.getRoot());
5634 CodeGenAndEmitDAG(JSDAG);
5637 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5638 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5639 MachineBasicBlock *PHIBB = PHI->getParent();
5640 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5641 "This is not a machine PHI node that we are updating!");
5642 // "default" BB. We can go there only from header BB.
5643 if (PHIBB == JTCases[i].second.Default) {
5644 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5646 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
5648 // JT BB. Just iterate over successors here
5649 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
5650 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5652 PHI->addOperand(MachineOperand::CreateMBB(BB));
5657 // If the switch block involved a branch to one of the actual successors, we
5658 // need to update PHI nodes in that block.
5659 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5660 MachineInstr *PHI = PHINodesToUpdate[i].first;
5661 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5662 "This is not a machine PHI node that we are updating!");
5663 if (BB->isSuccessor(PHI->getParent())) {
5664 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5666 PHI->addOperand(MachineOperand::CreateMBB(BB));
5670 // If we generated any switch lowering information, build and codegen any
5671 // additional DAGs necessary.
5672 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
5673 SelectionDAG SDAG(TLI, MF, FuncInfo,
5674 getAnalysisToUpdate<MachineModuleInfo>(),
5677 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GFI);
5679 // Set the current basic block to the mbb we wish to insert the code into
5680 BB = SwitchCases[i].ThisBB;
5681 SDL.setCurrentBasicBlock(BB);
5684 SDL.visitSwitchCase(SwitchCases[i]);
5685 SDAG.setRoot(SDL.getRoot());
5686 CodeGenAndEmitDAG(SDAG);
5688 // Handle any PHI nodes in successors of this chunk, as if we were coming
5689 // from the original BB before switch expansion. Note that PHI nodes can
5690 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5691 // handle them the right number of times.
5692 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
5693 for (MachineBasicBlock::iterator Phi = BB->begin();
5694 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5695 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5696 for (unsigned pn = 0; ; ++pn) {
5697 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5698 if (PHINodesToUpdate[pn].first == Phi) {
5699 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5701 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5707 // Don't process RHS if same block as LHS.
5708 if (BB == SwitchCases[i].FalseBB)
5709 SwitchCases[i].FalseBB = 0;
5711 // If we haven't handled the RHS, do so now. Otherwise, we're done.
5712 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5713 SwitchCases[i].FalseBB = 0;
5715 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5720 /// Schedule - Pick a safe ordering for instructions for each
5721 /// target node in the graph.
5723 ScheduleDAG *SelectionDAGISel::Schedule(SelectionDAG &DAG) {
5724 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5728 RegisterScheduler::setDefault(Ctor);
5731 ScheduleDAG *Scheduler = Ctor(this, &DAG, BB, Fast);
5738 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5739 return new HazardRecognizer();
5742 //===----------------------------------------------------------------------===//
5743 // Helper functions used by the generated instruction selector.
5744 //===----------------------------------------------------------------------===//
5745 // Calls to these methods are generated by tblgen.
5747 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
5748 /// the dag combiner simplified the 255, we still want to match. RHS is the
5749 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5750 /// specified in the .td file (e.g. 255).
5751 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
5752 int64_t DesiredMaskS) const {
5753 const APInt &ActualMask = RHS->getAPIntValue();
5754 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5756 // If the actual mask exactly matches, success!
5757 if (ActualMask == DesiredMask)
5760 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5761 if (ActualMask.intersects(~DesiredMask))
5764 // Otherwise, the DAG Combiner may have proven that the value coming in is
5765 // either already zero or is not demanded. Check for known zero input bits.
5766 APInt NeededMask = DesiredMask & ~ActualMask;
5767 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5770 // TODO: check to see if missing bits are just not demanded.
5772 // Otherwise, this pattern doesn't match.
5776 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
5777 /// the dag combiner simplified the 255, we still want to match. RHS is the
5778 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5779 /// specified in the .td file (e.g. 255).
5780 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
5781 int64_t DesiredMaskS) const {
5782 const APInt &ActualMask = RHS->getAPIntValue();
5783 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5785 // If the actual mask exactly matches, success!
5786 if (ActualMask == DesiredMask)
5789 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5790 if (ActualMask.intersects(~DesiredMask))
5793 // Otherwise, the DAG Combiner may have proven that the value coming in is
5794 // either already zero or is not demanded. Check for known zero input bits.
5795 APInt NeededMask = DesiredMask & ~ActualMask;
5797 APInt KnownZero, KnownOne;
5798 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5800 // If all the missing bits in the or are already known to be set, match!
5801 if ((NeededMask & KnownOne) == NeededMask)
5804 // TODO: check to see if missing bits are just not demanded.
5806 // Otherwise, this pattern doesn't match.
5811 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5812 /// by tblgen. Others should not call it.
5813 void SelectionDAGISel::
5814 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, SelectionDAG &DAG) {
5815 std::vector<SDValue> InOps;
5816 std::swap(InOps, Ops);
5818 Ops.push_back(InOps[0]); // input chain.
5819 Ops.push_back(InOps[1]); // input asm string.
5821 unsigned i = 2, e = InOps.size();
5822 if (InOps[e-1].getValueType() == MVT::Flag)
5823 --e; // Don't process a flag operand if it is here.
5826 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5827 if ((Flags & 7) != 4 /*MEM*/) {
5828 // Just skip over this operand, copying the operands verbatim.
5829 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5830 i += (Flags >> 3) + 1;
5832 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5833 // Otherwise, this is a memory operand. Ask the target to select it.
5834 std::vector<SDValue> SelOps;
5835 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5836 cerr << "Could not match memory address. Inline asm failure!\n";
5840 // Add this to the output node.
5841 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5842 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5844 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5849 // Add the flag input back if present.
5850 if (e != InOps.size())
5851 Ops.push_back(InOps.back());
5854 char SelectionDAGISel::ID = 0;