1 //===-- MSP430ISelDAGToDAG.cpp - A dag to dag inst selector for MSP430 ----===//
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 file defines an instruction selector for the MSP430 target.
12 //===----------------------------------------------------------------------===//
15 #include "MSP430ISelLowering.h"
16 #include "MSP430TargetMachine.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/SelectionDAGISel.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/Statistic.h"
40 ViewRMWDAGs("view-msp430-rmw-dags", cl::Hidden,
41 cl::desc("Pop up a window to show isel dags after RMW preprocess"));
43 static const bool ViewRMWDAGs = false;
46 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
50 struct MSP430ISelAddressMode {
56 struct { // This is really a union, discriminated by BaseType!
64 BlockAddress *BlockAddr;
67 unsigned Align; // CP alignment.
69 MSP430ISelAddressMode()
70 : BaseType(RegBase), Disp(0), GV(0), CP(0), BlockAddr(0),
71 ES(0), JT(-1), Align(0) {
74 bool hasSymbolicDisplacement() const {
75 return GV != 0 || CP != 0 || ES != 0 || JT != -1;
78 bool hasBaseReg() const {
79 return Base.Reg.getNode() != 0;
82 void setBaseReg(SDValue Reg) {
88 errs() << "MSP430ISelAddressMode " << this << '\n';
89 if (Base.Reg.getNode() != 0) {
90 errs() << "Base.Reg ";
91 Base.Reg.getNode()->dump();
93 errs() << " Base.FrameIndex " << Base.FrameIndex << '\n';
95 errs() << " Disp " << Disp << '\n';
102 errs() << " Align" << Align << '\n';
105 errs() << ES << '\n';
107 errs() << " JT" << JT << " Align" << Align << '\n';
112 /// MSP430DAGToDAGISel - MSP430 specific code to select MSP430 machine
113 /// instructions for SelectionDAG operations.
116 class MSP430DAGToDAGISel : public SelectionDAGISel {
117 MSP430TargetLowering &Lowering;
118 const MSP430Subtarget &Subtarget;
121 MSP430DAGToDAGISel(MSP430TargetMachine &TM, CodeGenOpt::Level OptLevel)
122 : SelectionDAGISel(TM, OptLevel),
123 Lowering(*TM.getTargetLowering()),
124 Subtarget(*TM.getSubtargetImpl()) { }
126 virtual void InstructionSelect();
128 virtual const char *getPassName() const {
129 return "MSP430 DAG->DAG Pattern Instruction Selection";
132 bool MatchAddress(SDValue N, MSP430ISelAddressMode &AM);
133 bool MatchWrapper(SDValue N, MSP430ISelAddressMode &AM);
134 bool MatchAddressBase(SDValue N, MSP430ISelAddressMode &AM);
136 bool IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
140 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
141 std::vector<SDValue> &OutOps);
143 // Include the pieces autogenerated from the target description.
144 #include "MSP430GenDAGISel.inc"
147 DenseMap<SDNode*, SDNode*> RMWStores;
148 void PreprocessForRMW();
149 SDNode *Select(SDValue Op);
150 bool SelectAddr(SDValue Op, SDValue Addr, SDValue &Base, SDValue &Disp);
156 } // end anonymous namespace
158 /// createMSP430ISelDag - This pass converts a legalized DAG into a
159 /// MSP430-specific DAG, ready for instruction scheduling.
161 FunctionPass *llvm::createMSP430ISelDag(MSP430TargetMachine &TM,
162 CodeGenOpt::Level OptLevel) {
163 return new MSP430DAGToDAGISel(TM, OptLevel);
167 /// MatchWrapper - Try to match MSP430ISD::Wrapper node into an addressing mode.
168 /// These wrap things that will resolve down into a symbol reference. If no
169 /// match is possible, this returns true, otherwise it returns false.
170 bool MSP430DAGToDAGISel::MatchWrapper(SDValue N, MSP430ISelAddressMode &AM) {
171 // If the addressing mode already has a symbol as the displacement, we can
172 // never match another symbol.
173 if (AM.hasSymbolicDisplacement())
176 SDValue N0 = N.getOperand(0);
178 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
179 AM.GV = G->getGlobal();
180 AM.Disp += G->getOffset();
181 //AM.SymbolFlags = G->getTargetFlags();
182 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
183 AM.CP = CP->getConstVal();
184 AM.Align = CP->getAlignment();
185 AM.Disp += CP->getOffset();
186 //AM.SymbolFlags = CP->getTargetFlags();
187 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
188 AM.ES = S->getSymbol();
189 //AM.SymbolFlags = S->getTargetFlags();
190 } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
191 AM.JT = J->getIndex();
192 //AM.SymbolFlags = J->getTargetFlags();
194 AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
195 //AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
200 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
201 /// specified addressing mode without any further recursion.
202 bool MSP430DAGToDAGISel::MatchAddressBase(SDValue N, MSP430ISelAddressMode &AM) {
203 // Is the base register already occupied?
204 if (AM.BaseType != MSP430ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
205 // If so, we cannot select it.
209 // Default, generate it as a register.
210 AM.BaseType = MSP430ISelAddressMode::RegBase;
215 bool MSP430DAGToDAGISel::MatchAddress(SDValue N, MSP430ISelAddressMode &AM) {
216 DebugLoc dl = N.getDebugLoc();
218 errs() << "MatchAddress: ";
222 switch (N.getOpcode()) {
224 case ISD::Constant: {
225 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
230 case MSP430ISD::Wrapper:
231 if (!MatchWrapper(N, AM))
235 case ISD::FrameIndex:
236 if (AM.BaseType == MSP430ISelAddressMode::RegBase
237 && AM.Base.Reg.getNode() == 0) {
238 AM.BaseType = MSP430ISelAddressMode::FrameIndexBase;
239 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
245 MSP430ISelAddressMode Backup = AM;
246 if (!MatchAddress(N.getNode()->getOperand(0), AM) &&
247 !MatchAddress(N.getNode()->getOperand(1), AM))
250 if (!MatchAddress(N.getNode()->getOperand(1), AM) &&
251 !MatchAddress(N.getNode()->getOperand(0), AM))
259 // Handle "X | C" as "X + C" iff X is known to have C bits clear.
260 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
261 MSP430ISelAddressMode Backup = AM;
262 uint64_t Offset = CN->getSExtValue();
263 // Start with the LHS as an addr mode.
264 if (!MatchAddress(N.getOperand(0), AM) &&
265 // Address could not have picked a GV address for the displacement.
267 // Check to see if the LHS & C is zero.
268 CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
277 return MatchAddressBase(N, AM);
280 /// SelectAddr - returns true if it is able pattern match an addressing mode.
281 /// It returns the operands which make up the maximal addressing mode it can
282 /// match by reference.
283 bool MSP430DAGToDAGISel::SelectAddr(SDValue Op, SDValue N,
284 SDValue &Base, SDValue &Disp) {
285 MSP430ISelAddressMode AM;
287 if (MatchAddress(N, AM))
290 EVT VT = N.getValueType();
291 if (AM.BaseType == MSP430ISelAddressMode::RegBase) {
292 if (!AM.Base.Reg.getNode())
293 AM.Base.Reg = CurDAG->getRegister(0, VT);
296 Base = (AM.BaseType == MSP430ISelAddressMode::FrameIndexBase) ?
297 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
301 Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i16, AM.Disp,
302 0/*AM.SymbolFlags*/);
304 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i16,
305 AM.Align, AM.Disp, 0/*AM.SymbolFlags*/);
307 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i16, 0/*AM.SymbolFlags*/);
308 else if (AM.JT != -1)
309 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i16, 0/*AM.SymbolFlags*/);
310 else if (AM.BlockAddr)
311 Disp = CurDAG->getBlockAddress(AM.BlockAddr, DebugLoc()/*MVT::i32*/,
312 true /*AM.SymbolFlags*/);
314 Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i16);
319 bool MSP430DAGToDAGISel::
320 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
321 std::vector<SDValue> &OutOps) {
323 switch (ConstraintCode) {
324 default: return true;
326 if (!SelectAddr(Op, Op, Op0, Op1))
331 OutOps.push_back(Op0);
332 OutOps.push_back(Op1);
336 bool MSP430DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
337 SDNode *Root) const {
338 if (OptLevel == CodeGenOpt::None) return false;
340 /// RMW preprocessing creates the following code:
357 /// The path Store => Load2 => Load1 is via chain. Note that in general it is
358 /// not allowed to fold Load1 into Op (and Store) since it will creates a
359 /// cycle. However, this is perfectly legal for the loads moved below the
360 /// TokenFactor by PreprocessForRMW. Query the map Store => Load1 (created
361 /// during preprocessing) to determine whether it's legal to introduce such
362 /// "cycle" for a moment.
363 DenseMap<SDNode*, SDNode*>::iterator I = RMWStores.find(Root);
364 if (I != RMWStores.end() && I->second == N)
367 // Proceed to 'generic' cycle finder code
368 return SelectionDAGISel::IsLegalAndProfitableToFold(N, U, Root);
372 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
373 /// and move load below the TokenFactor. Replace store's chain operand with
374 /// load's chain result.
375 static void MoveBelowTokenFactor(SelectionDAG *CurDAG, SDValue Load,
376 SDValue Store, SDValue TF) {
377 SmallVector<SDValue, 4> Ops;
378 for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i)
379 if (Load.getNode() == TF.getOperand(i).getNode())
380 Ops.push_back(Load.getOperand(0));
382 Ops.push_back(TF.getOperand(i));
383 SDValue NewTF = CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
384 SDValue NewLoad = CurDAG->UpdateNodeOperands(Load, NewTF,
387 CurDAG->UpdateNodeOperands(Store, NewLoad.getValue(1), Store.getOperand(1),
388 Store.getOperand(2), Store.getOperand(3));
391 /// MoveBelowTokenFactor2 - Replace TokenFactor operand with load's chain operand
392 /// and move load below the TokenFactor. Replace store's chain operand with
393 /// load's chain result. This a version which sinks two loads below token factor.
394 /// Look into PreprocessForRMW comments for explanation of transform.
395 static void MoveBelowTokenFactor2(SelectionDAG *CurDAG,
396 SDValue Load1, SDValue Load2,
397 SDValue Store, SDValue TF) {
398 SmallVector<SDValue, 4> Ops;
399 for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i) {
400 SDNode* N = TF.getOperand(i).getNode();
401 if (Load2.getNode() == N)
402 Ops.push_back(Load2.getOperand(0));
403 else if (Load1.getNode() != N)
404 Ops.push_back(TF.getOperand(i));
407 SDValue NewTF = SDValue(CurDAG->MorphNodeTo(TF.getNode(),
409 TF.getNode()->getVTList(),
410 &Ops[0], Ops.size()), TF.getResNo());
411 SDValue NewLoad2 = CurDAG->UpdateNodeOperands(Load2, NewTF,
413 Load2.getOperand(2));
415 SDValue NewLoad1 = CurDAG->UpdateNodeOperands(Load1, NewLoad2.getValue(1),
417 Load1.getOperand(2));
419 CurDAG->UpdateNodeOperands(Store,
420 NewLoad1.getValue(1),
422 Store.getOperand(2), Store.getOperand(3));
425 /// isAllowedToSink - return true if N a load which can be moved below token
426 /// factor. Basically, the load should be non-volatile and has single use.
427 static bool isLoadAllowedToSink(SDValue N, SDValue Chain) {
428 if (N.getOpcode() == ISD::BIT_CONVERT)
431 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
432 if (!LD || LD->isVolatile())
434 if (LD->getAddressingMode() != ISD::UNINDEXED)
437 ISD::LoadExtType ExtType = LD->getExtensionType();
438 if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
441 return (N.hasOneUse() &&
442 LD->hasNUsesOfValue(1, 1) &&
443 LD->isOperandOf(Chain.getNode()));
447 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
448 /// The chain produced by the load must only be used by the store's chain
449 /// operand, otherwise this may produce a cycle in the DAG.
450 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
452 if (isLoadAllowedToSink(N, Chain) &&
453 N.getOperand(1) == Address) {
460 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
461 /// This is only run if not in -O0 mode.
462 /// This allows the instruction selector to pick more read-modify-write
463 /// instructions. This is a common case:
473 /// [TokenFactor] [Op]
480 /// The fact the store's chain operand != load's chain will prevent the
481 /// (store (op (load))) instruction from being selected. We can transform it to:
501 /// We also recognize the case where second operand of Op is load as well and
502 /// move it below token factor as well creating DAG as follows:
526 /// This allows selection of mem-mem instructions. Yay!
528 void MSP430DAGToDAGISel::PreprocessForRMW() {
529 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
530 E = CurDAG->allnodes_end(); I != E; ++I) {
531 if (!ISD::isNON_TRUNCStore(I))
533 SDValue Chain = I->getOperand(0);
535 if (Chain.getNode()->getOpcode() != ISD::TokenFactor)
538 SDValue N1 = I->getOperand(1);
539 SDValue N2 = I->getOperand(2);
540 if ((N1.getValueType().isFloatingPoint() &&
541 !N1.getValueType().isVector()) ||
546 SDValue Load1, Load2;
547 unsigned Opcode = N1.getNode()->getOpcode();
555 SDValue N10 = N1.getOperand(0);
556 SDValue N11 = N1.getOperand(1);
557 if (isRMWLoad(N10, Chain, N2, Load1)) {
558 if (isLoadAllowedToSink(N11, Chain)) {
563 } else if (isRMWLoad(N11, Chain, N2, Load1)) {
564 if (isLoadAllowedToSink(N10, Chain)) {
575 SDValue N10 = N1.getOperand(0);
576 SDValue N11 = N1.getOperand(1);
577 if (isRMWLoad(N10, Chain, N2, Load1)) {
578 if (isLoadAllowedToSink(N11, Chain)) {
588 NumLoadMoved += RModW;
590 MoveBelowTokenFactor(CurDAG, Load1, SDValue(I, 0), Chain);
591 else if (RModW == 2) {
592 MoveBelowTokenFactor2(CurDAG, Load1, Load2, SDValue(I, 0), Chain);
594 RMWStores[Store] = Load2.getNode();
599 /// InstructionSelect - This callback is invoked by
600 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
601 void MSP430DAGToDAGISel::InstructionSelect() {
602 std::string BlockName;
604 BlockName = MF->getFunction()->getNameStr() + ":" +
605 BB->getBasicBlock()->getNameStr();
609 if (ViewRMWDAGs) CurDAG->viewGraph("RMW preprocessed:" + BlockName);
611 DEBUG(errs() << "Selection DAG after RMW preprocessing:\n");
612 DEBUG(CurDAG->dump());
614 // Codegen the basic block.
615 DEBUG(errs() << "===== Instruction selection begins:\n");
618 DEBUG(errs() << "===== Instruction selection ends:\n");
620 CurDAG->RemoveDeadNodes();
624 SDNode *MSP430DAGToDAGISel::Select(SDValue Op) {
625 SDNode *Node = Op.getNode();
626 DebugLoc dl = Op.getDebugLoc();
628 // Dump information about the Node being selected
629 DEBUG(errs().indent(Indent) << "Selecting: ");
630 DEBUG(Node->dump(CurDAG));
631 DEBUG(errs() << "\n");
634 // If we have a custom node, we already have selected!
635 if (Node->isMachineOpcode()) {
636 DEBUG(errs().indent(Indent-2) << "== ";
643 // Few custom selection stuff.
644 switch (Node->getOpcode()) {
646 case ISD::FrameIndex: {
647 assert(Op.getValueType() == MVT::i16);
648 int FI = cast<FrameIndexSDNode>(Node)->getIndex();
649 SDValue TFI = CurDAG->getTargetFrameIndex(FI, MVT::i16);
650 if (Node->hasOneUse())
651 return CurDAG->SelectNodeTo(Node, MSP430::ADD16ri, MVT::i16,
652 TFI, CurDAG->getTargetConstant(0, MVT::i16));
653 return CurDAG->getMachineNode(MSP430::ADD16ri, dl, MVT::i16,
654 TFI, CurDAG->getTargetConstant(0, MVT::i16));
658 // Select the default instruction
659 SDNode *ResNode = SelectCode(Op);
661 DEBUG(errs() << std::string(Indent-2, ' ') << "=> ");
662 if (ResNode == NULL || ResNode == Op.getNode())
663 DEBUG(Op.getNode()->dump(CurDAG));
665 DEBUG(ResNode->dump(CurDAG));
666 DEBUG(errs() << "\n");