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 "ScheduleDAGSDNodes.h"
16 #include "SelectionDAGBuild.h"
17 #include "llvm/CodeGen/SelectionDAGISel.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/CodeGen/FastISel.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/GCMetadata.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
38 #include "llvm/CodeGen/SchedulerRegistry.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/CodeGen/DwarfWriter.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/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/Timer.h"
57 DisableLegalizeTypes("disable-legalize-types", cl::Hidden);
59 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
60 cl::desc("Enable verbose messages in the \"fast\" "
61 "instruction selector"));
63 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
64 cl::desc("Enable abort calls when \"fast\" instruction fails"));
66 SchedLiveInCopies("schedule-livein-copies",
67 cl::desc("Schedule copies of livein registers"),
72 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
73 cl::desc("Pop up a window to show dags before the first "
76 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
77 cl::desc("Pop up a window to show dags before legalize types"));
79 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
80 cl::desc("Pop up a window to show dags before legalize"));
82 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
83 cl::desc("Pop up a window to show dags before the second "
86 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
87 cl::desc("Pop up a window to show dags before the post legalize types"
88 " dag combine pass"));
90 ViewISelDAGs("view-isel-dags", cl::Hidden,
91 cl::desc("Pop up a window to show isel dags as they are selected"));
93 ViewSchedDAGs("view-sched-dags", cl::Hidden,
94 cl::desc("Pop up a window to show sched dags as they are processed"));
96 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
97 cl::desc("Pop up a window to show SUnit dags after they are processed"));
99 static const bool ViewDAGCombine1 = false,
100 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
101 ViewDAGCombine2 = false,
102 ViewDAGCombineLT = false,
103 ViewISelDAGs = false, ViewSchedDAGs = false,
104 ViewSUnitDAGs = false;
107 //===---------------------------------------------------------------------===//
109 /// RegisterScheduler class - Track the registration of instruction schedulers.
111 //===---------------------------------------------------------------------===//
112 MachinePassRegistry RegisterScheduler::Registry;
114 //===---------------------------------------------------------------------===//
116 /// ISHeuristic command line option for instruction schedulers.
118 //===---------------------------------------------------------------------===//
119 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
120 RegisterPassParser<RegisterScheduler> >
121 ISHeuristic("pre-RA-sched",
122 cl::init(&createDefaultScheduler),
123 cl::desc("Instruction schedulers available (before register"
126 static RegisterScheduler
127 defaultListDAGScheduler("default", "Best scheduler for the target",
128 createDefaultScheduler);
131 //===--------------------------------------------------------------------===//
132 /// createDefaultScheduler - This creates an instruction scheduler appropriate
134 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
135 CodeGenOpt::Level OptLevel) {
136 const TargetLowering &TLI = IS->getTargetLowering();
138 if (OptLevel == CodeGenOpt::None)
139 return createFastDAGScheduler(IS, OptLevel);
140 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
141 return createTDListDAGScheduler(IS, OptLevel);
142 assert(TLI.getSchedulingPreference() ==
143 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
144 return createBURRListDAGScheduler(IS, OptLevel);
148 // EmitInstrWithCustomInserter - This method should be implemented by targets
149 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
150 // instructions are special in various ways, which require special support to
151 // insert. The specified MachineInstr is created but not inserted into any
152 // basic blocks, and the scheduler passes ownership of it to this method.
153 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
154 MachineBasicBlock *MBB) const {
155 llvm_report_error("If a target marks an instruction with "
156 "'usesCustomDAGSchedInserter', it must implement "
157 "TargetLowering::EmitInstrWithCustomInserter!");
161 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
162 /// physical register has only a single copy use, then coalesced the copy
164 static void EmitLiveInCopy(MachineBasicBlock *MBB,
165 MachineBasicBlock::iterator &InsertPos,
166 unsigned VirtReg, unsigned PhysReg,
167 const TargetRegisterClass *RC,
168 DenseMap<MachineInstr*, unsigned> &CopyRegMap,
169 const MachineRegisterInfo &MRI,
170 const TargetRegisterInfo &TRI,
171 const TargetInstrInfo &TII) {
172 unsigned NumUses = 0;
173 MachineInstr *UseMI = NULL;
174 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
175 UE = MRI.use_end(); UI != UE; ++UI) {
181 // If the number of uses is not one, or the use is not a move instruction,
182 // don't coalesce. Also, only coalesce away a virtual register to virtual
184 bool Coalesced = false;
185 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
187 TII.isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
188 TargetRegisterInfo::isVirtualRegister(DstReg)) {
193 // Now find an ideal location to insert the copy.
194 MachineBasicBlock::iterator Pos = InsertPos;
195 while (Pos != MBB->begin()) {
196 MachineInstr *PrevMI = prior(Pos);
197 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
198 // copyRegToReg might emit multiple instructions to do a copy.
199 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
200 if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
201 // This is what the BB looks like right now:
206 // We want to insert "r1025 = mov r1". Inserting this copy below the
207 // move to r1024 makes it impossible for that move to be coalesced.
214 break; // Woot! Found a good location.
218 bool Emitted = TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
219 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
222 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
224 if (&*InsertPos == UseMI) ++InsertPos;
229 /// EmitLiveInCopies - If this is the first basic block in the function,
230 /// and if it has live ins that need to be copied into vregs, emit the
231 /// copies into the block.
232 static void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
233 const MachineRegisterInfo &MRI,
234 const TargetRegisterInfo &TRI,
235 const TargetInstrInfo &TII) {
236 if (SchedLiveInCopies) {
237 // Emit the copies at a heuristically-determined location in the block.
238 DenseMap<MachineInstr*, unsigned> CopyRegMap;
239 MachineBasicBlock::iterator InsertPos = EntryMBB->begin();
240 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
241 E = MRI.livein_end(); LI != E; ++LI)
243 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
244 EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
245 RC, CopyRegMap, MRI, TRI, TII);
248 // Emit the copies into the top of the block.
249 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
250 E = MRI.livein_end(); LI != E; ++LI)
252 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
253 bool Emitted = TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
254 LI->second, LI->first, RC, RC);
255 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
261 //===----------------------------------------------------------------------===//
262 // SelectionDAGISel code
263 //===----------------------------------------------------------------------===//
265 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) :
266 FunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
267 FuncInfo(new FunctionLoweringInfo(TLI)),
268 CurDAG(new SelectionDAG(TLI, *FuncInfo)),
269 SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo, OL)),
275 SelectionDAGISel::~SelectionDAGISel() {
281 unsigned SelectionDAGISel::MakeReg(MVT VT) {
282 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
285 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
286 AU.addRequired<AliasAnalysis>();
287 AU.addRequired<GCModuleInfo>();
288 AU.addRequired<DwarfWriter>();
289 AU.setPreservesAll();
292 bool SelectionDAGISel::runOnFunction(Function &Fn) {
293 // Do some sanity-checking on the command-line options.
294 assert((!EnableFastISelVerbose || EnableFastISel) &&
295 "-fast-isel-verbose requires -fast-isel");
296 assert((!EnableFastISelAbort || EnableFastISel) &&
297 "-fast-isel-abort requires -fast-isel");
299 // Do not codegen any 'available_externally' functions at all, they have
300 // definitions outside the translation unit.
301 if (Fn.hasAvailableExternallyLinkage())
305 // Get alias analysis for load/store combining.
306 AA = &getAnalysis<AliasAnalysis>();
308 TargetMachine &TM = TLI.getTargetMachine();
309 MF = &MachineFunction::construct(&Fn, TM);
310 const TargetInstrInfo &TII = *TM.getInstrInfo();
311 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
313 if (MF->getFunction()->hasGC())
314 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF->getFunction());
317 RegInfo = &MF->getRegInfo();
318 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
320 MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
321 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
322 CurDAG->init(*MF, MMI, DW);
323 FuncInfo->set(Fn, *MF, *CurDAG, EnableFastISel);
326 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
327 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
329 FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
331 SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII);
333 // If the first basic block in the function has live ins that need to be
334 // copied into vregs, emit the copies into the top of the block before
335 // emitting the code for the block.
336 EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII);
338 // Add function live-ins to entry block live-in set.
339 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
340 E = RegInfo->livein_end(); I != E; ++I)
341 MF->begin()->addLiveIn(I->first);
344 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
345 "Not all catch info was assigned to a landing pad!");
353 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
354 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
355 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
356 if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
357 // Apply the catch info to DestBB.
358 AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
360 if (!FLI.MBBMap[SrcBB]->isLandingPad())
361 FLI.CatchInfoFound.insert(EHSel);
366 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
367 /// whether object offset >= 0.
369 IsFixedFrameObjectWithPosOffset(MachineFrameInfo *MFI, SDValue Op) {
370 if (!isa<FrameIndexSDNode>(Op)) return false;
372 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
373 int FrameIdx = FrameIdxNode->getIndex();
374 return MFI->isFixedObjectIndex(FrameIdx) &&
375 MFI->getObjectOffset(FrameIdx) >= 0;
378 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
379 /// possibly be overwritten when lowering the outgoing arguments in a tail
380 /// call. Currently the implementation of this call is very conservative and
381 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
382 /// virtual registers would be overwritten by direct lowering.
383 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
384 MachineFrameInfo *MFI) {
385 RegisterSDNode * OpReg = NULL;
386 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
387 (Op.getOpcode()== ISD::CopyFromReg &&
388 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
389 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
390 (Op.getOpcode() == ISD::LOAD &&
391 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
392 (Op.getOpcode() == ISD::MERGE_VALUES &&
393 Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
394 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
400 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
401 /// DAG and fixes their tailcall attribute operand.
402 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
403 const TargetLowering& TLI) {
405 SDValue Terminator = DAG.getRoot();
408 if (Terminator.getOpcode() == ISD::RET) {
409 Ret = Terminator.getNode();
412 // Fix tail call attribute of CALL nodes.
413 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
414 BI = DAG.allnodes_end(); BI != BE; ) {
416 if (CallSDNode *TheCall = dyn_cast<CallSDNode>(BI)) {
417 SDValue OpRet(Ret, 0);
418 SDValue OpCall(BI, 0);
419 bool isMarkedTailCall = TheCall->isTailCall();
420 // If CALL node has tail call attribute set to true and the call is not
421 // eligible (no RET or the target rejects) the attribute is fixed to
422 // false. The TargetLowering::IsEligibleForTailCallOptimization function
423 // must correctly identify tail call optimizable calls.
424 if (!isMarkedTailCall) continue;
426 !TLI.IsEligibleForTailCallOptimization(TheCall, OpRet, DAG)) {
427 // Not eligible. Mark CALL node as non tail call. Note that we
428 // can modify the call node in place since calls are not CSE'd.
429 TheCall->setNotTailCall();
431 // Look for tail call clobbered arguments. Emit a series of
432 // copyto/copyfrom virtual register nodes to protect them.
433 SmallVector<SDValue, 32> Ops;
434 SDValue Chain = TheCall->getChain(), InFlag;
435 Ops.push_back(Chain);
436 Ops.push_back(TheCall->getCallee());
437 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; ++i) {
438 SDValue Arg = TheCall->getArg(i);
439 bool isByVal = TheCall->getArgFlags(i).isByVal();
440 MachineFunction &MF = DAG.getMachineFunction();
441 MachineFrameInfo *MFI = MF.getFrameInfo();
443 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
444 MVT VT = Arg.getValueType();
445 unsigned VReg = MF.getRegInfo().
446 createVirtualRegister(TLI.getRegClassFor(VT));
447 Chain = DAG.getCopyToReg(Chain, Arg.getDebugLoc(),
449 InFlag = Chain.getValue(1);
450 Arg = DAG.getCopyFromReg(Chain, Arg.getDebugLoc(),
452 Chain = Arg.getValue(1);
453 InFlag = Arg.getValue(2);
456 Ops.push_back(TheCall->getArgFlagsVal(i));
458 // Link in chain of CopyTo/CopyFromReg.
460 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
466 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
467 BasicBlock::iterator Begin,
468 BasicBlock::iterator End) {
469 SDL->setCurrentBasicBlock(BB);
471 // Lower all of the non-terminator instructions.
472 for (BasicBlock::iterator I = Begin; I != End; ++I)
473 if (!isa<TerminatorInst>(I))
476 // Ensure that all instructions which are used outside of their defining
477 // blocks are available as virtual registers. Invoke is handled elsewhere.
478 for (BasicBlock::iterator I = Begin; I != End; ++I)
479 if (!isa<PHINode>(I) && !isa<InvokeInst>(I))
480 SDL->CopyToExportRegsIfNeeded(I);
482 // Handle PHI nodes in successor blocks.
483 if (End == LLVMBB->end()) {
484 HandlePHINodesInSuccessorBlocks(LLVMBB);
486 // Lower the terminator after the copies are emitted.
487 SDL->visit(*LLVMBB->getTerminator());
490 // Make sure the root of the DAG is up-to-date.
491 CurDAG->setRoot(SDL->getControlRoot());
493 // Check whether calls in this block are real tail calls. Fix up CALL nodes
494 // with correct tailcall attribute so that the target can rely on the tailcall
495 // attribute indicating whether the call is really eligible for tail call
497 if (PerformTailCallOpt)
498 CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
500 // Final step, emit the lowered DAG as machine code.
505 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
506 SmallPtrSet<SDNode*, 128> VisitedNodes;
507 SmallVector<SDNode*, 128> Worklist;
509 Worklist.push_back(CurDAG->getRoot().getNode());
515 while (!Worklist.empty()) {
516 SDNode *N = Worklist.back();
519 // If we've already seen this node, ignore it.
520 if (!VisitedNodes.insert(N))
523 // Otherwise, add all chain operands to the worklist.
524 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
525 if (N->getOperand(i).getValueType() == MVT::Other)
526 Worklist.push_back(N->getOperand(i).getNode());
528 // If this is a CopyToReg with a vreg dest, process it.
529 if (N->getOpcode() != ISD::CopyToReg)
532 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
533 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
536 // Ignore non-scalar or non-integer values.
537 SDValue Src = N->getOperand(2);
538 MVT SrcVT = Src.getValueType();
539 if (!SrcVT.isInteger() || SrcVT.isVector())
542 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
543 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
544 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
546 // Only install this information if it tells us something.
547 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
548 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
549 FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
550 if (DestReg >= FLI.LiveOutRegInfo.size())
551 FLI.LiveOutRegInfo.resize(DestReg+1);
552 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
553 LOI.NumSignBits = NumSignBits;
554 LOI.KnownOne = KnownOne;
555 LOI.KnownZero = KnownZero;
560 void SelectionDAGISel::CodeGenAndEmitDAG() {
561 std::string GroupName;
562 if (TimePassesIsEnabled)
563 GroupName = "Instruction Selection and Scheduling";
564 std::string BlockName;
565 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
566 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
568 BlockName = CurDAG->getMachineFunction().getFunction()->getName() + ':' +
569 BB->getBasicBlock()->getName();
571 DOUT << "Initial selection DAG:\n";
572 DEBUG(CurDAG->dump());
574 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
576 // Run the DAG combiner in pre-legalize mode.
577 if (TimePassesIsEnabled) {
578 NamedRegionTimer T("DAG Combining 1", GroupName);
579 CurDAG->Combine(Unrestricted, *AA, OptLevel);
581 CurDAG->Combine(Unrestricted, *AA, OptLevel);
584 DOUT << "Optimized lowered selection DAG:\n";
585 DEBUG(CurDAG->dump());
587 // Second step, hack on the DAG until it only uses operations and types that
588 // the target supports.
589 if (!DisableLegalizeTypes) {
590 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
594 if (TimePassesIsEnabled) {
595 NamedRegionTimer T("Type Legalization", GroupName);
596 Changed = CurDAG->LegalizeTypes();
598 Changed = CurDAG->LegalizeTypes();
601 DOUT << "Type-legalized selection DAG:\n";
602 DEBUG(CurDAG->dump());
605 if (ViewDAGCombineLT)
606 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
608 // Run the DAG combiner in post-type-legalize mode.
609 if (TimePassesIsEnabled) {
610 NamedRegionTimer T("DAG Combining after legalize types", GroupName);
611 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
613 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
616 DOUT << "Optimized type-legalized selection DAG:\n";
617 DEBUG(CurDAG->dump());
620 if (TimePassesIsEnabled) {
621 NamedRegionTimer T("Vector Legalization", GroupName);
622 Changed = CurDAG->LegalizeVectors();
624 Changed = CurDAG->LegalizeVectors();
628 if (TimePassesIsEnabled) {
629 NamedRegionTimer T("Type Legalization 2", GroupName);
630 Changed = CurDAG->LegalizeTypes();
632 Changed = CurDAG->LegalizeTypes();
635 if (ViewDAGCombineLT)
636 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
638 // Run the DAG combiner in post-type-legalize mode.
639 if (TimePassesIsEnabled) {
640 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
641 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
643 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
646 DOUT << "Optimized vector-legalized selection DAG:\n";
647 DEBUG(CurDAG->dump());
651 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
653 if (TimePassesIsEnabled) {
654 NamedRegionTimer T("DAG Legalization", GroupName);
655 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
657 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
660 DOUT << "Legalized selection DAG:\n";
661 DEBUG(CurDAG->dump());
663 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
665 // Run the DAG combiner in post-legalize mode.
666 if (TimePassesIsEnabled) {
667 NamedRegionTimer T("DAG Combining 2", GroupName);
668 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
670 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
673 DOUT << "Optimized legalized selection DAG:\n";
674 DEBUG(CurDAG->dump());
676 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
678 if (OptLevel != CodeGenOpt::None)
679 ComputeLiveOutVRegInfo();
681 // Third, instruction select all of the operations to machine code, adding the
682 // code to the MachineBasicBlock.
683 if (TimePassesIsEnabled) {
684 NamedRegionTimer T("Instruction Selection", GroupName);
690 DOUT << "Selected selection DAG:\n";
691 DEBUG(CurDAG->dump());
693 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
695 // Schedule machine code.
696 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
697 if (TimePassesIsEnabled) {
698 NamedRegionTimer T("Instruction Scheduling", GroupName);
699 Scheduler->Run(CurDAG, BB, BB->end());
701 Scheduler->Run(CurDAG, BB, BB->end());
704 if (ViewSUnitDAGs) Scheduler->viewGraph();
706 // Emit machine code to BB. This can change 'BB' to the last block being
708 if (TimePassesIsEnabled) {
709 NamedRegionTimer T("Instruction Creation", GroupName);
710 BB = Scheduler->EmitSchedule();
712 BB = Scheduler->EmitSchedule();
715 // Free the scheduler state.
716 if (TimePassesIsEnabled) {
717 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
723 DOUT << "Selected machine code:\n";
727 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
729 MachineModuleInfo *MMI,
731 const TargetInstrInfo &TII) {
732 // Initialize the Fast-ISel state, if needed.
733 FastISel *FastIS = 0;
735 FastIS = TLI.createFastISel(MF, MMI, DW,
738 FuncInfo->StaticAllocaMap
740 , FuncInfo->CatchInfoLost
744 // Iterate over all basic blocks in the function.
745 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
746 BasicBlock *LLVMBB = &*I;
747 BB = FuncInfo->MBBMap[LLVMBB];
749 BasicBlock::iterator const Begin = LLVMBB->begin();
750 BasicBlock::iterator const End = LLVMBB->end();
751 BasicBlock::iterator BI = Begin;
753 // Lower any arguments needed in this block if this is the entry block.
754 bool SuppressFastISel = false;
755 if (LLVMBB == &Fn.getEntryBlock()) {
756 LowerArguments(LLVMBB);
758 // If any of the arguments has the byval attribute, forgo
759 // fast-isel in the entry block.
762 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
764 if (Fn.paramHasAttr(j, Attribute::ByVal)) {
765 if (EnableFastISelVerbose || EnableFastISelAbort)
766 cerr << "FastISel skips entry block due to byval argument\n";
767 SuppressFastISel = true;
773 if (MMI && BB->isLandingPad()) {
774 // Add a label to mark the beginning of the landing pad. Deletion of the
775 // landing pad can thus be detected via the MachineModuleInfo.
776 unsigned LabelID = MMI->addLandingPad(BB);
778 const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
779 BuildMI(BB, SDL->getCurDebugLoc(), II).addImm(LabelID);
781 // Mark exception register as live in.
782 unsigned Reg = TLI.getExceptionAddressRegister();
783 if (Reg) BB->addLiveIn(Reg);
785 // Mark exception selector register as live in.
786 Reg = TLI.getExceptionSelectorRegister();
787 if (Reg) BB->addLiveIn(Reg);
789 // FIXME: Hack around an exception handling flaw (PR1508): the personality
790 // function and list of typeids logically belong to the invoke (or, if you
791 // like, the basic block containing the invoke), and need to be associated
792 // with it in the dwarf exception handling tables. Currently however the
793 // information is provided by an intrinsic (eh.selector) that can be moved
794 // to unexpected places by the optimizers: if the unwind edge is critical,
795 // then breaking it can result in the intrinsics being in the successor of
796 // the landing pad, not the landing pad itself. This results in exceptions
797 // not being caught because no typeids are associated with the invoke.
798 // This may not be the only way things can go wrong, but it is the only way
799 // we try to work around for the moment.
800 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
802 if (Br && Br->isUnconditional()) { // Critical edge?
803 BasicBlock::iterator I, E;
804 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
805 if (isa<EHSelectorInst>(I))
809 // No catch info found - try to extract some from the successor.
810 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
814 // Before doing SelectionDAG ISel, see if FastISel has been requested.
815 if (FastIS && !SuppressFastISel) {
816 // Emit code for any incoming arguments. This must happen before
817 // beginning FastISel on the entry block.
818 if (LLVMBB == &Fn.getEntryBlock()) {
819 CurDAG->setRoot(SDL->getControlRoot());
823 FastIS->startNewBlock(BB);
824 // Do FastISel on as many instructions as possible.
825 for (; BI != End; ++BI) {
826 // Just before the terminator instruction, insert instructions to
827 // feed PHI nodes in successor blocks.
828 if (isa<TerminatorInst>(BI))
829 if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
830 if (EnableFastISelVerbose || EnableFastISelAbort) {
831 cerr << "FastISel miss: ";
834 if (EnableFastISelAbort)
835 LLVM_UNREACHABLE("FastISel didn't handle a PHI in a successor");
839 // First try normal tablegen-generated "fast" selection.
840 if (FastIS->SelectInstruction(BI))
843 // Next, try calling the target to attempt to handle the instruction.
844 if (FastIS->TargetSelectInstruction(BI))
847 // Then handle certain instructions as single-LLVM-Instruction blocks.
848 if (isa<CallInst>(BI)) {
849 if (EnableFastISelVerbose || EnableFastISelAbort) {
850 cerr << "FastISel missed call: ";
854 if (BI->getType() != Type::VoidTy) {
855 unsigned &R = FuncInfo->ValueMap[BI];
857 R = FuncInfo->CreateRegForValue(BI);
860 SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
861 SelectBasicBlock(LLVMBB, BI, next(BI));
862 // If the instruction was codegen'd with multiple blocks,
863 // inform the FastISel object where to resume inserting.
864 FastIS->setCurrentBlock(BB);
868 // Otherwise, give up on FastISel for the rest of the block.
869 // For now, be a little lenient about non-branch terminators.
870 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
871 if (EnableFastISelVerbose || EnableFastISelAbort) {
872 cerr << "FastISel miss: ";
875 if (EnableFastISelAbort)
876 // The "fast" selector couldn't handle something and bailed.
877 // For the purpose of debugging, just abort.
878 LLVM_UNREACHABLE("FastISel didn't select the entire block");
884 // Run SelectionDAG instruction selection on the remainder of the block
885 // not handled by FastISel. If FastISel is not run, this is the entire
888 // If FastISel is run and it has known DebugLoc then use it.
889 if (FastIS && !FastIS->getCurDebugLoc().isUnknown())
890 SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
891 SelectBasicBlock(LLVMBB, BI, End);
901 SelectionDAGISel::FinishBasicBlock() {
903 DOUT << "Target-post-processed machine code:\n";
906 DOUT << "Total amount of phi nodes to update: "
907 << SDL->PHINodesToUpdate.size() << "\n";
908 DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
909 DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
910 << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
912 // Next, now that we know what the last MBB the LLVM BB expanded is, update
913 // PHI nodes in successors.
914 if (SDL->SwitchCases.empty() &&
915 SDL->JTCases.empty() &&
916 SDL->BitTestCases.empty()) {
917 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
918 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
919 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
920 "This is not a machine PHI node that we are updating!");
921 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
923 PHI->addOperand(MachineOperand::CreateMBB(BB));
925 SDL->PHINodesToUpdate.clear();
929 for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
930 // Lower header first, if it wasn't already lowered
931 if (!SDL->BitTestCases[i].Emitted) {
932 // Set the current basic block to the mbb we wish to insert the code into
933 BB = SDL->BitTestCases[i].Parent;
934 SDL->setCurrentBasicBlock(BB);
936 SDL->visitBitTestHeader(SDL->BitTestCases[i]);
937 CurDAG->setRoot(SDL->getRoot());
942 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
943 // Set the current basic block to the mbb we wish to insert the code into
944 BB = SDL->BitTestCases[i].Cases[j].ThisBB;
945 SDL->setCurrentBasicBlock(BB);
948 SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
949 SDL->BitTestCases[i].Reg,
950 SDL->BitTestCases[i].Cases[j]);
952 SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
953 SDL->BitTestCases[i].Reg,
954 SDL->BitTestCases[i].Cases[j]);
957 CurDAG->setRoot(SDL->getRoot());
963 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
964 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
965 MachineBasicBlock *PHIBB = PHI->getParent();
966 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
967 "This is not a machine PHI node that we are updating!");
968 // This is "default" BB. We have two jumps to it. From "header" BB and
969 // from last "case" BB.
970 if (PHIBB == SDL->BitTestCases[i].Default) {
971 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
973 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
974 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
976 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
979 // One of "cases" BB.
980 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
982 MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
983 if (cBB->succ_end() !=
984 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
985 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
987 PHI->addOperand(MachineOperand::CreateMBB(cBB));
992 SDL->BitTestCases.clear();
994 // If the JumpTable record is filled in, then we need to emit a jump table.
995 // Updating the PHI nodes is tricky in this case, since we need to determine
996 // whether the PHI is a successor of the range check MBB or the jump table MBB
997 for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
998 // Lower header first, if it wasn't already lowered
999 if (!SDL->JTCases[i].first.Emitted) {
1000 // Set the current basic block to the mbb we wish to insert the code into
1001 BB = SDL->JTCases[i].first.HeaderBB;
1002 SDL->setCurrentBasicBlock(BB);
1004 SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
1005 CurDAG->setRoot(SDL->getRoot());
1006 CodeGenAndEmitDAG();
1010 // Set the current basic block to the mbb we wish to insert the code into
1011 BB = SDL->JTCases[i].second.MBB;
1012 SDL->setCurrentBasicBlock(BB);
1014 SDL->visitJumpTable(SDL->JTCases[i].second);
1015 CurDAG->setRoot(SDL->getRoot());
1016 CodeGenAndEmitDAG();
1020 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
1021 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
1022 MachineBasicBlock *PHIBB = PHI->getParent();
1023 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1024 "This is not a machine PHI node that we are updating!");
1025 // "default" BB. We can go there only from header BB.
1026 if (PHIBB == SDL->JTCases[i].second.Default) {
1027 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
1029 PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
1031 // JT BB. Just iterate over successors here
1032 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
1033 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
1035 PHI->addOperand(MachineOperand::CreateMBB(BB));
1039 SDL->JTCases.clear();
1041 // If the switch block involved a branch to one of the actual successors, we
1042 // need to update PHI nodes in that block.
1043 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
1044 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
1045 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1046 "This is not a machine PHI node that we are updating!");
1047 if (BB->isSuccessor(PHI->getParent())) {
1048 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
1050 PHI->addOperand(MachineOperand::CreateMBB(BB));
1054 // If we generated any switch lowering information, build and codegen any
1055 // additional DAGs necessary.
1056 for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
1057 // Set the current basic block to the mbb we wish to insert the code into
1058 BB = SDL->SwitchCases[i].ThisBB;
1059 SDL->setCurrentBasicBlock(BB);
1062 SDL->visitSwitchCase(SDL->SwitchCases[i]);
1063 CurDAG->setRoot(SDL->getRoot());
1064 CodeGenAndEmitDAG();
1067 // Handle any PHI nodes in successors of this chunk, as if we were coming
1068 // from the original BB before switch expansion. Note that PHI nodes can
1069 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1070 // handle them the right number of times.
1071 while ((BB = SDL->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
1072 for (MachineBasicBlock::iterator Phi = BB->begin();
1073 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
1074 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
1075 for (unsigned pn = 0; ; ++pn) {
1076 assert(pn != SDL->PHINodesToUpdate.size() &&
1077 "Didn't find PHI entry!");
1078 if (SDL->PHINodesToUpdate[pn].first == Phi) {
1079 Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
1081 Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
1087 // Don't process RHS if same block as LHS.
1088 if (BB == SDL->SwitchCases[i].FalseBB)
1089 SDL->SwitchCases[i].FalseBB = 0;
1091 // If we haven't handled the RHS, do so now. Otherwise, we're done.
1092 SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
1093 SDL->SwitchCases[i].FalseBB = 0;
1095 assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
1097 SDL->SwitchCases.clear();
1099 SDL->PHINodesToUpdate.clear();
1103 /// Create the scheduler. If a specific scheduler was specified
1104 /// via the SchedulerRegistry, use it, otherwise select the
1105 /// one preferred by the target.
1107 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1108 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1112 RegisterScheduler::setDefault(Ctor);
1115 return Ctor(this, OptLevel);
1118 ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1119 return new ScheduleHazardRecognizer();
1122 //===----------------------------------------------------------------------===//
1123 // Helper functions used by the generated instruction selector.
1124 //===----------------------------------------------------------------------===//
1125 // Calls to these methods are generated by tblgen.
1127 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1128 /// the dag combiner simplified the 255, we still want to match. RHS is the
1129 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1130 /// specified in the .td file (e.g. 255).
1131 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1132 int64_t DesiredMaskS) const {
1133 const APInt &ActualMask = RHS->getAPIntValue();
1134 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1136 // If the actual mask exactly matches, success!
1137 if (ActualMask == DesiredMask)
1140 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1141 if (ActualMask.intersects(~DesiredMask))
1144 // Otherwise, the DAG Combiner may have proven that the value coming in is
1145 // either already zero or is not demanded. Check for known zero input bits.
1146 APInt NeededMask = DesiredMask & ~ActualMask;
1147 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1150 // TODO: check to see if missing bits are just not demanded.
1152 // Otherwise, this pattern doesn't match.
1156 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1157 /// the dag combiner simplified the 255, we still want to match. RHS is the
1158 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1159 /// specified in the .td file (e.g. 255).
1160 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1161 int64_t DesiredMaskS) const {
1162 const APInt &ActualMask = RHS->getAPIntValue();
1163 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1165 // If the actual mask exactly matches, success!
1166 if (ActualMask == DesiredMask)
1169 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1170 if (ActualMask.intersects(~DesiredMask))
1173 // Otherwise, the DAG Combiner may have proven that the value coming in is
1174 // either already zero or is not demanded. Check for known zero input bits.
1175 APInt NeededMask = DesiredMask & ~ActualMask;
1177 APInt KnownZero, KnownOne;
1178 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1180 // If all the missing bits in the or are already known to be set, match!
1181 if ((NeededMask & KnownOne) == NeededMask)
1184 // TODO: check to see if missing bits are just not demanded.
1186 // Otherwise, this pattern doesn't match.
1191 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1192 /// by tblgen. Others should not call it.
1193 void SelectionDAGISel::
1194 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1195 std::vector<SDValue> InOps;
1196 std::swap(InOps, Ops);
1198 Ops.push_back(InOps[0]); // input chain.
1199 Ops.push_back(InOps[1]); // input asm string.
1201 unsigned i = 2, e = InOps.size();
1202 if (InOps[e-1].getValueType() == MVT::Flag)
1203 --e; // Don't process a flag operand if it is here.
1206 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1207 if ((Flags & 7) != 4 /*MEM*/) {
1208 // Just skip over this operand, copying the operands verbatim.
1209 Ops.insert(Ops.end(), InOps.begin()+i,
1210 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1211 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1213 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1214 "Memory operand with multiple values?");
1215 // Otherwise, this is a memory operand. Ask the target to select it.
1216 std::vector<SDValue> SelOps;
1217 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
1218 llvm_report_error("Could not match memory address. Inline asm"
1222 // Add this to the output node.
1223 MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
1224 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
1226 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1231 // Add the flag input back if present.
1232 if (e != InOps.size())
1233 Ops.push_back(InOps.back());
1236 /// findFlagUse - Return use of MVT::Flag value produced by the specified
1239 static SDNode *findFlagUse(SDNode *N) {
1240 unsigned FlagResNo = N->getNumValues()-1;
1241 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1242 SDUse &Use = I.getUse();
1243 if (Use.getResNo() == FlagResNo)
1244 return Use.getUser();
1249 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1250 /// This function recursively traverses up the operand chain, ignoring
1252 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1254 SmallPtrSet<SDNode*, 16> &Visited) {
1255 if (Use->getNodeId() < Def->getNodeId() ||
1256 !Visited.insert(Use))
1259 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1260 SDNode *N = Use->getOperand(i).getNode();
1262 if (Use == ImmedUse || Use == Root)
1263 continue; // We are not looking for immediate use.
1268 // Traverse up the operand chain.
1269 if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
1275 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
1276 /// be reached. Return true if that's the case. However, ignore direct uses
1277 /// by ImmedUse (which would be U in the example illustrated in
1278 /// IsLegalAndProfitableToFold) and by Root (which can happen in the store
1280 /// FIXME: to be really generic, we should allow direct use by any node
1281 /// that is being folded. But realisticly since we only fold loads which
1282 /// have one non-chain use, we only need to watch out for load/op/store
1283 /// and load/op/cmp case where the root (store / cmp) may reach the load via
1284 /// its chain operand.
1285 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
1286 SmallPtrSet<SDNode*, 16> Visited;
1287 return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
1290 /// IsLegalAndProfitableToFold - Returns true if the specific operand node N of
1291 /// U can be folded during instruction selection that starts at Root and
1292 /// folding N is profitable.
1293 bool SelectionDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
1294 SDNode *Root) const {
1295 if (OptLevel == CodeGenOpt::None) return false;
1297 // If Root use can somehow reach N through a path that that doesn't contain
1298 // U then folding N would create a cycle. e.g. In the following
1299 // diagram, Root can reach N through X. If N is folded into into Root, then
1300 // X is both a predecessor and a successor of U.
1311 // * indicates nodes to be folded together.
1313 // If Root produces a flag, then it gets (even more) interesting. Since it
1314 // will be "glued" together with its flag use in the scheduler, we need to
1315 // check if it might reach N.
1334 // If FU (flag use) indirectly reaches N (the load), and Root folds N
1335 // (call it Fold), then X is a predecessor of FU and a successor of
1336 // Fold. But since Fold and FU are flagged together, this will create
1337 // a cycle in the scheduling graph.
1339 MVT VT = Root->getValueType(Root->getNumValues()-1);
1340 while (VT == MVT::Flag) {
1341 SDNode *FU = findFlagUse(Root);
1345 VT = Root->getValueType(Root->getNumValues()-1);
1348 return !isNonImmUse(Root, N, U);
1352 char SelectionDAGISel::ID = 0;