1 //===-- MSP430ISelLowering.cpp - MSP430 DAG Lowering Implementation ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the MSP430TargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "MSP430ISelLowering.h"
14 #include "MSP430.h"
15 #include "MSP430MachineFunctionInfo.h"
16 #include "MSP430SelectionDAGInfo.h"
17 #include "MSP430Subtarget.h"
18 #include "MSP430TargetMachine.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
25 #include "llvm/CodeGen/ValueTypes.h"
26 #include "llvm/IR/CallingConv.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm;
35
36 #define DEBUG_TYPE "msp430-lower"
37
38 static cl::opt<bool>MSP430NoLegalImmediate(
39 "msp430-no-legal-immediate", cl::Hidden,
40 cl::desc("Enable non legal immediates (for testing purposes only)"),
41 cl::init(false));
42
MSP430TargetLowering(const TargetMachine & TM,const MSP430Subtarget & STI)43 MSP430TargetLowering::MSP430TargetLowering(const TargetMachine &TM,
44 const MSP430Subtarget &STI)
45 : TargetLowering(TM) {
46
47 // Set up the register classes.
48 addRegisterClass(MVT::i8, &MSP430::GR8RegClass);
49 addRegisterClass(MVT::i16, &MSP430::GR16RegClass);
50
51 // Compute derived properties from the register classes
52 computeRegisterProperties(STI.getRegisterInfo());
53
54 // Provide all sorts of operation actions
55 setStackPointerRegisterToSaveRestore(MSP430::SP);
56 setBooleanContents(ZeroOrOneBooleanContent);
57 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
58
59 // We have post-incremented loads / stores.
60 setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
61 setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
62
63 for (MVT VT : MVT::integer_valuetypes()) {
64 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
65 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
66 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
67 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
68 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Expand);
69 }
70
71 // We don't have any truncstores
72 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
73
74 setOperationAction(ISD::SRA, MVT::i8, Custom);
75 setOperationAction(ISD::SHL, MVT::i8, Custom);
76 setOperationAction(ISD::SRL, MVT::i8, Custom);
77 setOperationAction(ISD::SRA, MVT::i16, Custom);
78 setOperationAction(ISD::SHL, MVT::i16, Custom);
79 setOperationAction(ISD::SRL, MVT::i16, Custom);
80 setOperationAction(ISD::ROTL, MVT::i8, Expand);
81 setOperationAction(ISD::ROTR, MVT::i8, Expand);
82 setOperationAction(ISD::ROTL, MVT::i16, Expand);
83 setOperationAction(ISD::ROTR, MVT::i16, Expand);
84 setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
85 setOperationAction(ISD::ExternalSymbol, MVT::i16, Custom);
86 setOperationAction(ISD::BlockAddress, MVT::i16, Custom);
87 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
88 setOperationAction(ISD::BR_CC, MVT::i8, Custom);
89 setOperationAction(ISD::BR_CC, MVT::i16, Custom);
90 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
91 setOperationAction(ISD::SETCC, MVT::i8, Custom);
92 setOperationAction(ISD::SETCC, MVT::i16, Custom);
93 setOperationAction(ISD::SELECT, MVT::i8, Expand);
94 setOperationAction(ISD::SELECT, MVT::i16, Expand);
95 setOperationAction(ISD::SELECT_CC, MVT::i8, Custom);
96 setOperationAction(ISD::SELECT_CC, MVT::i16, Custom);
97 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Custom);
98 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
99 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
100 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
101 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
102
103 setOperationAction(ISD::CTTZ, MVT::i8, Expand);
104 setOperationAction(ISD::CTTZ, MVT::i16, Expand);
105 setOperationAction(ISD::CTLZ, MVT::i8, Expand);
106 setOperationAction(ISD::CTLZ, MVT::i16, Expand);
107 setOperationAction(ISD::CTPOP, MVT::i8, Expand);
108 setOperationAction(ISD::CTPOP, MVT::i16, Expand);
109
110 setOperationAction(ISD::SHL_PARTS, MVT::i8, Expand);
111 setOperationAction(ISD::SHL_PARTS, MVT::i16, Expand);
112 setOperationAction(ISD::SRL_PARTS, MVT::i8, Expand);
113 setOperationAction(ISD::SRL_PARTS, MVT::i16, Expand);
114 setOperationAction(ISD::SRA_PARTS, MVT::i8, Expand);
115 setOperationAction(ISD::SRA_PARTS, MVT::i16, Expand);
116
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
118
119 // FIXME: Implement efficiently multiplication by a constant
120 setOperationAction(ISD::MUL, MVT::i8, Promote);
121 setOperationAction(ISD::MULHS, MVT::i8, Promote);
122 setOperationAction(ISD::MULHU, MVT::i8, Promote);
123 setOperationAction(ISD::SMUL_LOHI, MVT::i8, Promote);
124 setOperationAction(ISD::UMUL_LOHI, MVT::i8, Promote);
125 setOperationAction(ISD::MUL, MVT::i16, LibCall);
126 setOperationAction(ISD::MULHS, MVT::i16, Expand);
127 setOperationAction(ISD::MULHU, MVT::i16, Expand);
128 setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand);
129 setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand);
130
131 setOperationAction(ISD::UDIV, MVT::i8, Promote);
132 setOperationAction(ISD::UDIVREM, MVT::i8, Promote);
133 setOperationAction(ISD::UREM, MVT::i8, Promote);
134 setOperationAction(ISD::SDIV, MVT::i8, Promote);
135 setOperationAction(ISD::SDIVREM, MVT::i8, Promote);
136 setOperationAction(ISD::SREM, MVT::i8, Promote);
137 setOperationAction(ISD::UDIV, MVT::i16, LibCall);
138 setOperationAction(ISD::UDIVREM, MVT::i16, Expand);
139 setOperationAction(ISD::UREM, MVT::i16, LibCall);
140 setOperationAction(ISD::SDIV, MVT::i16, LibCall);
141 setOperationAction(ISD::SDIVREM, MVT::i16, Expand);
142 setOperationAction(ISD::SREM, MVT::i16, LibCall);
143
144 // varargs support
145 setOperationAction(ISD::VASTART, MVT::Other, Custom);
146 setOperationAction(ISD::VAARG, MVT::Other, Expand);
147 setOperationAction(ISD::VAEND, MVT::Other, Expand);
148 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
149 setOperationAction(ISD::JumpTable, MVT::i16, Custom);
150
151 if (STI.hasHWMult16()) {
152 const struct {
153 const RTLIB::Libcall Op;
154 const RTLIB::LibcallImpl Impl;
155 } LibraryCalls[] = {
156 // Integer Multiply - EABI Table 9
157 {RTLIB::MUL_I16, RTLIB::__mspabi_mpyi_hw},
158 {RTLIB::MUL_I32, RTLIB::__mspabi_mpyl_hw},
159 {RTLIB::MUL_I64, RTLIB::__mspabi_mpyll_hw},
160 // TODO The __mspabi_mpysl*_hw functions ARE implemented in libgcc
161 // TODO The __mspabi_mpyul*_hw functions ARE implemented in libgcc
162 };
163 for (const auto &LC : LibraryCalls) {
164 setLibcallImpl(LC.Op, LC.Impl);
165 }
166 } else if (STI.hasHWMult32()) {
167 const struct {
168 const RTLIB::Libcall Op;
169 const RTLIB::LibcallImpl Impl;
170 } LibraryCalls[] = {
171 // Integer Multiply - EABI Table 9
172 {RTLIB::MUL_I16, RTLIB::__mspabi_mpyi_hw},
173 {RTLIB::MUL_I32, RTLIB::__mspabi_mpyl_hw32},
174 {RTLIB::MUL_I64, RTLIB::__mspabi_mpyll_hw32},
175 // TODO The __mspabi_mpysl*_hw32 functions ARE implemented in libgcc
176 // TODO The __mspabi_mpyul*_hw32 functions ARE implemented in libgcc
177 };
178 for (const auto &LC : LibraryCalls) {
179 setLibcallImpl(LC.Op, LC.Impl);
180 }
181 } else if (STI.hasHWMultF5()) {
182 const struct {
183 const RTLIB::Libcall Op;
184 const RTLIB::LibcallImpl Impl;
185 } LibraryCalls[] = {
186 // Integer Multiply - EABI Table 9
187 {RTLIB::MUL_I16, RTLIB::__mspabi_mpyi_f5hw},
188 {RTLIB::MUL_I32, RTLIB::__mspabi_mpyl_f5hw},
189 {RTLIB::MUL_I64, RTLIB::__mspabi_mpyll_f5hw},
190 // TODO The __mspabi_mpysl*_f5hw functions ARE implemented in libgcc
191 // TODO The __mspabi_mpyul*_f5hw functions ARE implemented in libgcc
192 };
193 for (const auto &LC : LibraryCalls) {
194 setLibcallImpl(LC.Op, LC.Impl);
195 }
196 } else { // NoHWMult
197 const struct {
198 const RTLIB::Libcall Op;
199 const RTLIB::LibcallImpl Impl;
200 } LibraryCalls[] = {
201 // Integer Multiply - EABI Table 9
202 {RTLIB::MUL_I16, RTLIB::__mspabi_mpyi},
203 {RTLIB::MUL_I32, RTLIB::__mspabi_mpyl},
204 {RTLIB::MUL_I64, RTLIB::__mspabi_mpyll},
205 // The __mspabi_mpysl* functions are NOT implemented in libgcc
206 // The __mspabi_mpyul* functions are NOT implemented in libgcc
207 };
208 for (const auto &LC : LibraryCalls) {
209 setLibcallImpl(LC.Op, LC.Impl);
210 }
211 }
212
213 setMinFunctionAlignment(Align(2));
214 setPrefFunctionAlignment(Align(2));
215 setMaxAtomicSizeInBitsSupported(0);
216 }
217
LowerOperation(SDValue Op,SelectionDAG & DAG) const218 SDValue MSP430TargetLowering::LowerOperation(SDValue Op,
219 SelectionDAG &DAG) const {
220 switch (Op.getOpcode()) {
221 case ISD::SHL: // FALLTHROUGH
222 case ISD::SRL:
223 case ISD::SRA: return LowerShifts(Op, DAG);
224 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
225 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
226 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
227 case ISD::SETCC: return LowerSETCC(Op, DAG);
228 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
229 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
230 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
231 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
232 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
233 case ISD::VASTART: return LowerVASTART(Op, DAG);
234 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
235 default:
236 llvm_unreachable("unimplemented operand");
237 }
238 }
239
240 // Define non profitable transforms into shifts
shouldAvoidTransformToShift(EVT VT,unsigned Amount) const241 bool MSP430TargetLowering::shouldAvoidTransformToShift(EVT VT,
242 unsigned Amount) const {
243 return !(Amount == 8 || Amount == 9 || Amount<=2);
244 }
245
246 // Implemented to verify test case assertions in
247 // tests/codegen/msp430/shift-amount-threshold-b.ll
isLegalICmpImmediate(int64_t Immed) const248 bool MSP430TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
249 if (MSP430NoLegalImmediate)
250 return Immed >= -32 && Immed < 32;
251 return TargetLowering::isLegalICmpImmediate(Immed);
252 }
253
254 //===----------------------------------------------------------------------===//
255 // MSP430 Inline Assembly Support
256 //===----------------------------------------------------------------------===//
257
258 /// getConstraintType - Given a constraint letter, return the type of
259 /// constraint it is for this target.
260 TargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const261 MSP430TargetLowering::getConstraintType(StringRef Constraint) const {
262 if (Constraint.size() == 1) {
263 switch (Constraint[0]) {
264 case 'r':
265 return C_RegisterClass;
266 default:
267 break;
268 }
269 }
270 return TargetLowering::getConstraintType(Constraint);
271 }
272
273 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const274 MSP430TargetLowering::getRegForInlineAsmConstraint(
275 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
276 if (Constraint.size() == 1) {
277 // GCC Constraint Letters
278 switch (Constraint[0]) {
279 default: break;
280 case 'r': // GENERAL_REGS
281 if (VT == MVT::i8)
282 return std::make_pair(0U, &MSP430::GR8RegClass);
283
284 return std::make_pair(0U, &MSP430::GR16RegClass);
285 }
286 }
287
288 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
289 }
290
291 //===----------------------------------------------------------------------===//
292 // Calling Convention Implementation
293 //===----------------------------------------------------------------------===//
294
295 #include "MSP430GenCallingConv.inc"
296
297 /// For each argument in a function store the number of pieces it is composed
298 /// of.
299 template<typename ArgT>
ParseFunctionArgs(const SmallVectorImpl<ArgT> & Args,SmallVectorImpl<unsigned> & Out)300 static void ParseFunctionArgs(const SmallVectorImpl<ArgT> &Args,
301 SmallVectorImpl<unsigned> &Out) {
302 unsigned CurrentArgIndex;
303
304 if (Args.empty())
305 return;
306
307 CurrentArgIndex = Args[0].OrigArgIndex;
308 Out.push_back(0);
309
310 for (auto &Arg : Args) {
311 if (CurrentArgIndex == Arg.OrigArgIndex) {
312 Out.back() += 1;
313 } else {
314 Out.push_back(1);
315 CurrentArgIndex = Arg.OrigArgIndex;
316 }
317 }
318 }
319
AnalyzeVarArgs(CCState & State,const SmallVectorImpl<ISD::OutputArg> & Outs)320 static void AnalyzeVarArgs(CCState &State,
321 const SmallVectorImpl<ISD::OutputArg> &Outs) {
322 State.AnalyzeCallOperands(Outs, CC_MSP430_AssignStack);
323 }
324
AnalyzeVarArgs(CCState & State,const SmallVectorImpl<ISD::InputArg> & Ins)325 static void AnalyzeVarArgs(CCState &State,
326 const SmallVectorImpl<ISD::InputArg> &Ins) {
327 State.AnalyzeFormalArguments(Ins, CC_MSP430_AssignStack);
328 }
329
330 /// Analyze incoming and outgoing function arguments. We need custom C++ code
331 /// to handle special constraints in the ABI like reversing the order of the
332 /// pieces of splitted arguments. In addition, all pieces of a certain argument
333 /// have to be passed either using registers or the stack but never mixing both.
334 template<typename ArgT>
AnalyzeArguments(CCState & State,SmallVectorImpl<CCValAssign> & ArgLocs,const SmallVectorImpl<ArgT> & Args)335 static void AnalyzeArguments(CCState &State,
336 SmallVectorImpl<CCValAssign> &ArgLocs,
337 const SmallVectorImpl<ArgT> &Args) {
338 static const MCPhysReg CRegList[] = {
339 MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15
340 };
341 static const unsigned CNbRegs = std::size(CRegList);
342 static const MCPhysReg BuiltinRegList[] = {
343 MSP430::R8, MSP430::R9, MSP430::R10, MSP430::R11,
344 MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15
345 };
346 static const unsigned BuiltinNbRegs = std::size(BuiltinRegList);
347
348 ArrayRef<MCPhysReg> RegList;
349 unsigned NbRegs;
350
351 bool Builtin = (State.getCallingConv() == CallingConv::MSP430_BUILTIN);
352 if (Builtin) {
353 RegList = BuiltinRegList;
354 NbRegs = BuiltinNbRegs;
355 } else {
356 RegList = CRegList;
357 NbRegs = CNbRegs;
358 }
359
360 if (State.isVarArg()) {
361 AnalyzeVarArgs(State, Args);
362 return;
363 }
364
365 SmallVector<unsigned, 4> ArgsParts;
366 ParseFunctionArgs(Args, ArgsParts);
367
368 if (Builtin) {
369 assert(ArgsParts.size() == 2 &&
370 "Builtin calling convention requires two arguments");
371 }
372
373 unsigned RegsLeft = NbRegs;
374 bool UsedStack = false;
375 unsigned ValNo = 0;
376
377 for (unsigned i = 0, e = ArgsParts.size(); i != e; i++) {
378 MVT ArgVT = Args[ValNo].VT;
379 ISD::ArgFlagsTy ArgFlags = Args[ValNo].Flags;
380 MVT LocVT = ArgVT;
381 CCValAssign::LocInfo LocInfo = CCValAssign::Full;
382
383 // Promote i8 to i16
384 if (LocVT == MVT::i8) {
385 LocVT = MVT::i16;
386 if (ArgFlags.isSExt())
387 LocInfo = CCValAssign::SExt;
388 else if (ArgFlags.isZExt())
389 LocInfo = CCValAssign::ZExt;
390 else
391 LocInfo = CCValAssign::AExt;
392 }
393
394 // Handle byval arguments
395 if (ArgFlags.isByVal()) {
396 State.HandleByVal(ValNo++, ArgVT, LocVT, LocInfo, 2, Align(2), ArgFlags);
397 continue;
398 }
399
400 unsigned Parts = ArgsParts[i];
401
402 if (Builtin) {
403 assert(Parts == 4 &&
404 "Builtin calling convention requires 64-bit arguments");
405 }
406
407 if (!UsedStack && Parts == 2 && RegsLeft == 1) {
408 // Special case for 32-bit register split, see EABI section 3.3.3
409 MCRegister Reg = State.AllocateReg(RegList);
410 State.addLoc(CCValAssign::getReg(ValNo++, ArgVT, Reg, LocVT, LocInfo));
411 RegsLeft -= 1;
412
413 UsedStack = true;
414 CC_MSP430_AssignStack(ValNo++, ArgVT, LocVT, LocInfo, ArgFlags, State);
415 } else if (Parts <= RegsLeft) {
416 for (unsigned j = 0; j < Parts; j++) {
417 MCRegister Reg = State.AllocateReg(RegList);
418 State.addLoc(CCValAssign::getReg(ValNo++, ArgVT, Reg, LocVT, LocInfo));
419 RegsLeft--;
420 }
421 } else {
422 UsedStack = true;
423 for (unsigned j = 0; j < Parts; j++)
424 CC_MSP430_AssignStack(ValNo++, ArgVT, LocVT, LocInfo, ArgFlags, State);
425 }
426 }
427 }
428
AnalyzeRetResult(CCState & State,const SmallVectorImpl<ISD::InputArg> & Ins)429 static void AnalyzeRetResult(CCState &State,
430 const SmallVectorImpl<ISD::InputArg> &Ins) {
431 State.AnalyzeCallResult(Ins, RetCC_MSP430);
432 }
433
AnalyzeRetResult(CCState & State,const SmallVectorImpl<ISD::OutputArg> & Outs)434 static void AnalyzeRetResult(CCState &State,
435 const SmallVectorImpl<ISD::OutputArg> &Outs) {
436 State.AnalyzeReturn(Outs, RetCC_MSP430);
437 }
438
439 template<typename ArgT>
AnalyzeReturnValues(CCState & State,SmallVectorImpl<CCValAssign> & RVLocs,const SmallVectorImpl<ArgT> & Args)440 static void AnalyzeReturnValues(CCState &State,
441 SmallVectorImpl<CCValAssign> &RVLocs,
442 const SmallVectorImpl<ArgT> &Args) {
443 AnalyzeRetResult(State, Args);
444 }
445
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const446 SDValue MSP430TargetLowering::LowerFormalArguments(
447 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
448 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
449 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
450
451 switch (CallConv) {
452 default:
453 report_fatal_error("Unsupported calling convention");
454 case CallingConv::C:
455 case CallingConv::Fast:
456 return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
457 case CallingConv::MSP430_INTR:
458 if (Ins.empty())
459 return Chain;
460 report_fatal_error("ISRs cannot have arguments");
461 }
462 }
463
464 SDValue
LowerCall(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const465 MSP430TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
466 SmallVectorImpl<SDValue> &InVals) const {
467 SelectionDAG &DAG = CLI.DAG;
468 SDLoc &dl = CLI.DL;
469 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
470 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
471 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
472 SDValue Chain = CLI.Chain;
473 SDValue Callee = CLI.Callee;
474 bool &isTailCall = CLI.IsTailCall;
475 CallingConv::ID CallConv = CLI.CallConv;
476 bool isVarArg = CLI.IsVarArg;
477
478 // MSP430 target does not yet support tail call optimization.
479 isTailCall = false;
480
481 switch (CallConv) {
482 default:
483 report_fatal_error("Unsupported calling convention");
484 case CallingConv::MSP430_BUILTIN:
485 case CallingConv::Fast:
486 case CallingConv::C:
487 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
488 Outs, OutVals, Ins, dl, DAG, InVals);
489 case CallingConv::MSP430_INTR:
490 report_fatal_error("ISRs cannot be called directly");
491 }
492 }
493
494 /// LowerCCCArguments - transform physical registers into virtual registers and
495 /// generate load operations for arguments places on the stack.
496 // FIXME: struct return stuff
LowerCCCArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const497 SDValue MSP430TargetLowering::LowerCCCArguments(
498 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
499 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
500 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
501 MachineFunction &MF = DAG.getMachineFunction();
502 MachineFrameInfo &MFI = MF.getFrameInfo();
503 MachineRegisterInfo &RegInfo = MF.getRegInfo();
504 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
505
506 // Assign locations to all of the incoming arguments.
507 SmallVector<CCValAssign, 16> ArgLocs;
508 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
509 *DAG.getContext());
510 AnalyzeArguments(CCInfo, ArgLocs, Ins);
511
512 // Create frame index for the start of the first vararg value
513 if (isVarArg) {
514 unsigned Offset = CCInfo.getStackSize();
515 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, Offset, true));
516 }
517
518 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
519 CCValAssign &VA = ArgLocs[i];
520 if (VA.isRegLoc()) {
521 // Arguments passed in registers
522 EVT RegVT = VA.getLocVT();
523 switch (RegVT.getSimpleVT().SimpleTy) {
524 default:
525 {
526 #ifndef NDEBUG
527 errs() << "LowerFormalArguments Unhandled argument type: "
528 << RegVT << "\n";
529 #endif
530 llvm_unreachable(nullptr);
531 }
532 case MVT::i16:
533 Register VReg = RegInfo.createVirtualRegister(&MSP430::GR16RegClass);
534 RegInfo.addLiveIn(VA.getLocReg(), VReg);
535 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
536
537 // If this is an 8-bit value, it is really passed promoted to 16
538 // bits. Insert an assert[sz]ext to capture this, then truncate to the
539 // right size.
540 if (VA.getLocInfo() == CCValAssign::SExt)
541 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
542 DAG.getValueType(VA.getValVT()));
543 else if (VA.getLocInfo() == CCValAssign::ZExt)
544 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
545 DAG.getValueType(VA.getValVT()));
546
547 if (VA.getLocInfo() != CCValAssign::Full)
548 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
549
550 InVals.push_back(ArgValue);
551 }
552 } else {
553 // Only arguments passed on the stack should make it here.
554 assert(VA.isMemLoc());
555
556 SDValue InVal;
557 ISD::ArgFlagsTy Flags = Ins[i].Flags;
558
559 if (Flags.isByVal()) {
560 MVT PtrVT = VA.getLocVT();
561 int FI = MFI.CreateFixedObject(Flags.getByValSize(),
562 VA.getLocMemOffset(), true);
563 InVal = DAG.getFrameIndex(FI, PtrVT);
564 } else {
565 // Load the argument to a virtual register
566 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
567 if (ObjSize > 2) {
568 errs() << "LowerFormalArguments Unhandled argument type: "
569 << VA.getLocVT() << "\n";
570 }
571 // Create the frame index object for this incoming parameter...
572 int FI = MFI.CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
573
574 // Create the SelectionDAG nodes corresponding to a load
575 //from this parameter
576 SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
577 InVal = DAG.getLoad(
578 VA.getLocVT(), dl, Chain, FIN,
579 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
580 }
581
582 InVals.push_back(InVal);
583 }
584 }
585
586 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
587 if (Ins[i].Flags.isSRet()) {
588 Register Reg = FuncInfo->getSRetReturnReg();
589 if (!Reg) {
590 Reg = MF.getRegInfo().createVirtualRegister(
591 getRegClassFor(MVT::i16));
592 FuncInfo->setSRetReturnReg(Reg);
593 }
594 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
595 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
596 }
597 }
598
599 return Chain;
600 }
601
602 bool
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool IsVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context,const Type * RetTy) const603 MSP430TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
604 MachineFunction &MF,
605 bool IsVarArg,
606 const SmallVectorImpl<ISD::OutputArg> &Outs,
607 LLVMContext &Context,
608 const Type *RetTy) const {
609 SmallVector<CCValAssign, 16> RVLocs;
610 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
611 return CCInfo.CheckReturn(Outs, RetCC_MSP430);
612 }
613
614 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & dl,SelectionDAG & DAG) const615 MSP430TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
616 bool isVarArg,
617 const SmallVectorImpl<ISD::OutputArg> &Outs,
618 const SmallVectorImpl<SDValue> &OutVals,
619 const SDLoc &dl, SelectionDAG &DAG) const {
620
621 MachineFunction &MF = DAG.getMachineFunction();
622
623 // CCValAssign - represent the assignment of the return value to a location
624 SmallVector<CCValAssign, 16> RVLocs;
625
626 // ISRs cannot return any value.
627 if (CallConv == CallingConv::MSP430_INTR && !Outs.empty())
628 report_fatal_error("ISRs cannot return any value");
629
630 // CCState - Info about the registers and stack slot.
631 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
632 *DAG.getContext());
633
634 // Analize return values.
635 AnalyzeReturnValues(CCInfo, RVLocs, Outs);
636
637 SDValue Glue;
638 SmallVector<SDValue, 4> RetOps(1, Chain);
639
640 // Copy the result values into the output registers.
641 for (unsigned i = 0; i != RVLocs.size(); ++i) {
642 CCValAssign &VA = RVLocs[i];
643 assert(VA.isRegLoc() && "Can only return in registers!");
644
645 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
646 OutVals[i], Glue);
647
648 // Guarantee that all emitted copies are stuck together,
649 // avoiding something bad.
650 Glue = Chain.getValue(1);
651 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
652 }
653
654 if (MF.getFunction().hasStructRetAttr()) {
655 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
656 Register Reg = FuncInfo->getSRetReturnReg();
657
658 if (!Reg)
659 llvm_unreachable("sret virtual register not created in entry block");
660
661 MVT PtrVT = getFrameIndexTy(DAG.getDataLayout());
662 SDValue Val =
663 DAG.getCopyFromReg(Chain, dl, Reg, PtrVT);
664 unsigned R12 = MSP430::R12;
665
666 Chain = DAG.getCopyToReg(Chain, dl, R12, Val, Glue);
667 Glue = Chain.getValue(1);
668 RetOps.push_back(DAG.getRegister(R12, PtrVT));
669 }
670
671 unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
672 MSP430ISD::RETI_GLUE : MSP430ISD::RET_GLUE);
673
674 RetOps[0] = Chain; // Update chain.
675
676 // Add the glue if we have it.
677 if (Glue.getNode())
678 RetOps.push_back(Glue);
679
680 return DAG.getNode(Opc, dl, MVT::Other, RetOps);
681 }
682
683 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
684 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
LowerCCCCallTo(SDValue Chain,SDValue Callee,CallingConv::ID CallConv,bool isVarArg,bool isTailCall,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const685 SDValue MSP430TargetLowering::LowerCCCCallTo(
686 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
687 bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs,
688 const SmallVectorImpl<SDValue> &OutVals,
689 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
690 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
691 // Analyze operands of the call, assigning locations to each operand.
692 SmallVector<CCValAssign, 16> ArgLocs;
693 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
694 *DAG.getContext());
695 AnalyzeArguments(CCInfo, ArgLocs, Outs);
696
697 // Get a count of how many bytes are to be pushed on the stack.
698 unsigned NumBytes = CCInfo.getStackSize();
699 MVT PtrVT = getFrameIndexTy(DAG.getDataLayout());
700
701 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
702
703 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
704 SmallVector<SDValue, 12> MemOpChains;
705 SDValue StackPtr;
706
707 // Walk the register/memloc assignments, inserting copies/loads.
708 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
709 CCValAssign &VA = ArgLocs[i];
710
711 SDValue Arg = OutVals[i];
712
713 // Promote the value if needed.
714 switch (VA.getLocInfo()) {
715 default: llvm_unreachable("Unknown loc info!");
716 case CCValAssign::Full: break;
717 case CCValAssign::SExt:
718 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
719 break;
720 case CCValAssign::ZExt:
721 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
722 break;
723 case CCValAssign::AExt:
724 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
725 break;
726 }
727
728 // Arguments that can be passed on register must be kept at RegsToPass
729 // vector
730 if (VA.isRegLoc()) {
731 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
732 } else {
733 assert(VA.isMemLoc());
734
735 if (!StackPtr.getNode())
736 StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SP, PtrVT);
737
738 SDValue PtrOff =
739 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
740 DAG.getIntPtrConstant(VA.getLocMemOffset(), dl));
741
742 SDValue MemOp;
743 ISD::ArgFlagsTy Flags = Outs[i].Flags;
744
745 if (Flags.isByVal()) {
746 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i16);
747 MemOp = DAG.getMemcpy(Chain, dl, PtrOff, Arg, SizeNode,
748 Flags.getNonZeroByValAlign(),
749 /*isVolatile*/ false,
750 /*AlwaysInline=*/true,
751 /*CI=*/nullptr, std::nullopt,
752 MachinePointerInfo(), MachinePointerInfo());
753 } else {
754 MemOp = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
755 }
756
757 MemOpChains.push_back(MemOp);
758 }
759 }
760
761 // Transform all store nodes into one single node because all store nodes are
762 // independent of each other.
763 if (!MemOpChains.empty())
764 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
765
766 // Build a sequence of copy-to-reg nodes chained together with token chain and
767 // flag operands which copy the outgoing args into registers. The InGlue in
768 // necessary since all emitted instructions must be stuck together.
769 SDValue InGlue;
770 for (const auto &[Reg, N] : RegsToPass) {
771 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
772 InGlue = Chain.getValue(1);
773 }
774
775 // If the callee is a GlobalAddress node (quite common, every direct call is)
776 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
777 // Likewise ExternalSymbol -> TargetExternalSymbol.
778 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
779 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i16);
780 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
781 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
782
783 // Returns a chain & a flag for retval copy to use.
784 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
785 SmallVector<SDValue, 8> Ops;
786 Ops.push_back(Chain);
787 Ops.push_back(Callee);
788
789 // Add argument registers to the end of the list so that they are
790 // known live into the call.
791 for (const auto &[Reg, N] : RegsToPass)
792 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
793
794 if (InGlue.getNode())
795 Ops.push_back(InGlue);
796
797 Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, Ops);
798 InGlue = Chain.getValue(1);
799
800 // Create the CALLSEQ_END node.
801 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, dl);
802 InGlue = Chain.getValue(1);
803
804 // Handle result values, copying them out of physregs into vregs that we
805 // return.
806 return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, dl,
807 DAG, InVals);
808 }
809
810 /// LowerCallResult - Lower the result values of a call into the
811 /// appropriate copies out of appropriate physical registers.
812 ///
LowerCallResult(SDValue Chain,SDValue InGlue,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const813 SDValue MSP430TargetLowering::LowerCallResult(
814 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
815 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
816 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
817
818 // Assign locations to each value returned by this call.
819 SmallVector<CCValAssign, 16> RVLocs;
820 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
821 *DAG.getContext());
822
823 AnalyzeReturnValues(CCInfo, RVLocs, Ins);
824
825 // Copy all of the result registers out of their specified physreg.
826 for (unsigned i = 0; i != RVLocs.size(); ++i) {
827 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
828 RVLocs[i].getValVT(), InGlue).getValue(1);
829 InGlue = Chain.getValue(2);
830 InVals.push_back(Chain.getValue(0));
831 }
832
833 return Chain;
834 }
835
LowerShifts(SDValue Op,SelectionDAG & DAG) const836 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
837 SelectionDAG &DAG) const {
838 unsigned Opc = Op.getOpcode();
839 SDNode* N = Op.getNode();
840 EVT VT = Op.getValueType();
841 SDLoc dl(N);
842
843 // Expand non-constant shifts to loops:
844 if (!isa<ConstantSDNode>(N->getOperand(1)))
845 return Op;
846
847 uint64_t ShiftAmount = N->getConstantOperandVal(1);
848
849 // Expand the stuff into sequence of shifts.
850 SDValue Victim = N->getOperand(0);
851
852 if (ShiftAmount >= 8) {
853 assert(VT == MVT::i16 && "Can not shift i8 by 8 and more");
854 switch(Opc) {
855 default:
856 llvm_unreachable("Unknown shift");
857 case ISD::SHL:
858 // foo << (8 + N) => swpb(zext(foo)) << N
859 Victim = DAG.getZeroExtendInReg(Victim, dl, MVT::i8);
860 Victim = DAG.getNode(ISD::BSWAP, dl, VT, Victim);
861 break;
862 case ISD::SRA:
863 case ISD::SRL:
864 // foo >> (8 + N) => sxt(swpb(foo)) >> N
865 Victim = DAG.getNode(ISD::BSWAP, dl, VT, Victim);
866 Victim = (Opc == ISD::SRA)
867 ? DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Victim,
868 DAG.getValueType(MVT::i8))
869 : DAG.getZeroExtendInReg(Victim, dl, MVT::i8);
870 break;
871 }
872 ShiftAmount -= 8;
873 }
874
875 if (Opc == ISD::SRL && ShiftAmount) {
876 // Emit a special goodness here:
877 // srl A, 1 => clrc; rrc A
878 Victim = DAG.getNode(MSP430ISD::RRCL, dl, VT, Victim);
879 ShiftAmount -= 1;
880 }
881
882 while (ShiftAmount--)
883 Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
884 dl, VT, Victim);
885
886 return Victim;
887 }
888
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const889 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op,
890 SelectionDAG &DAG) const {
891 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
892 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
893 EVT PtrVT = Op.getValueType();
894
895 // Create the TargetGlobalAddress node, folding in the constant offset.
896 SDValue Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op), PtrVT, Offset);
897 return DAG.getNode(MSP430ISD::Wrapper, SDLoc(Op), PtrVT, Result);
898 }
899
LowerExternalSymbol(SDValue Op,SelectionDAG & DAG) const900 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
901 SelectionDAG &DAG) const {
902 SDLoc dl(Op);
903 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
904 EVT PtrVT = Op.getValueType();
905 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT);
906
907 return DAG.getNode(MSP430ISD::Wrapper, dl, PtrVT, Result);
908 }
909
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const910 SDValue MSP430TargetLowering::LowerBlockAddress(SDValue Op,
911 SelectionDAG &DAG) const {
912 SDLoc dl(Op);
913 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
914 EVT PtrVT = Op.getValueType();
915 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT);
916
917 return DAG.getNode(MSP430ISD::Wrapper, dl, PtrVT, Result);
918 }
919
EmitCMP(SDValue & LHS,SDValue & RHS,SDValue & TargetCC,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG)920 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
921 ISD::CondCode CC, const SDLoc &dl, SelectionDAG &DAG) {
922 // FIXME: Handle bittests someday
923 assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
924
925 // FIXME: Handle jump negative someday
926 MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
927 switch (CC) {
928 default: llvm_unreachable("Invalid integer condition!");
929 case ISD::SETEQ:
930 TCC = MSP430CC::COND_E; // aka COND_Z
931 // Minor optimization: if LHS is a constant, swap operands, then the
932 // constant can be folded into comparison.
933 if (LHS.getOpcode() == ISD::Constant)
934 std::swap(LHS, RHS);
935 break;
936 case ISD::SETNE:
937 TCC = MSP430CC::COND_NE; // aka COND_NZ
938 // Minor optimization: if LHS is a constant, swap operands, then the
939 // constant can be folded into comparison.
940 if (LHS.getOpcode() == ISD::Constant)
941 std::swap(LHS, RHS);
942 break;
943 case ISD::SETULE:
944 std::swap(LHS, RHS);
945 [[fallthrough]];
946 case ISD::SETUGE:
947 // Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to
948 // fold constant into instruction.
949 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
950 LHS = RHS;
951 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
952 TCC = MSP430CC::COND_LO;
953 break;
954 }
955 TCC = MSP430CC::COND_HS; // aka COND_C
956 break;
957 case ISD::SETUGT:
958 std::swap(LHS, RHS);
959 [[fallthrough]];
960 case ISD::SETULT:
961 // Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to
962 // fold constant into instruction.
963 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
964 LHS = RHS;
965 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
966 TCC = MSP430CC::COND_HS;
967 break;
968 }
969 TCC = MSP430CC::COND_LO; // aka COND_NC
970 break;
971 case ISD::SETLE:
972 std::swap(LHS, RHS);
973 [[fallthrough]];
974 case ISD::SETGE:
975 // Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to
976 // fold constant into instruction.
977 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
978 LHS = RHS;
979 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
980 TCC = MSP430CC::COND_L;
981 break;
982 }
983 TCC = MSP430CC::COND_GE;
984 break;
985 case ISD::SETGT:
986 std::swap(LHS, RHS);
987 [[fallthrough]];
988 case ISD::SETLT:
989 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
990 // fold constant into instruction.
991 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
992 LHS = RHS;
993 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
994 TCC = MSP430CC::COND_GE;
995 break;
996 }
997 TCC = MSP430CC::COND_L;
998 break;
999 }
1000
1001 TargetCC = DAG.getConstant(TCC, dl, MVT::i8);
1002 return DAG.getNode(MSP430ISD::CMP, dl, MVT::Glue, LHS, RHS);
1003 }
1004
1005
LowerBR_CC(SDValue Op,SelectionDAG & DAG) const1006 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1007 SDValue Chain = Op.getOperand(0);
1008 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1009 SDValue LHS = Op.getOperand(2);
1010 SDValue RHS = Op.getOperand(3);
1011 SDValue Dest = Op.getOperand(4);
1012 SDLoc dl (Op);
1013
1014 SDValue TargetCC;
1015 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1016
1017 return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
1018 Chain, Dest, TargetCC, Flag);
1019 }
1020
LowerSETCC(SDValue Op,SelectionDAG & DAG) const1021 SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1022 SDValue LHS = Op.getOperand(0);
1023 SDValue RHS = Op.getOperand(1);
1024 SDLoc dl (Op);
1025
1026 // If we are doing an AND and testing against zero, then the CMP
1027 // will not be generated. The AND (or BIT) will generate the condition codes,
1028 // but they are different from CMP.
1029 // FIXME: since we're doing a post-processing, use a pseudoinstr here, so
1030 // lowering & isel wouldn't diverge.
1031 bool andCC = isNullConstant(RHS) && LHS.hasOneUse() &&
1032 (LHS.getOpcode() == ISD::AND ||
1033 (LHS.getOpcode() == ISD::TRUNCATE &&
1034 LHS.getOperand(0).getOpcode() == ISD::AND));
1035 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1036 SDValue TargetCC;
1037 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1038
1039 // Get the condition codes directly from the status register, if its easy.
1040 // Otherwise a branch will be generated. Note that the AND and BIT
1041 // instructions generate different flags than CMP, the carry bit can be used
1042 // for NE/EQ.
1043 bool Invert = false;
1044 bool Shift = false;
1045 bool Convert = true;
1046 switch (TargetCC->getAsZExtVal()) {
1047 default:
1048 Convert = false;
1049 break;
1050 case MSP430CC::COND_HS:
1051 // Res = SR & 1, no processing is required
1052 break;
1053 case MSP430CC::COND_LO:
1054 // Res = ~(SR & 1)
1055 Invert = true;
1056 break;
1057 case MSP430CC::COND_NE:
1058 if (andCC) {
1059 // C = ~Z, thus Res = SR & 1, no processing is required
1060 } else {
1061 // Res = ~((SR >> 1) & 1)
1062 Shift = true;
1063 Invert = true;
1064 }
1065 break;
1066 case MSP430CC::COND_E:
1067 Shift = true;
1068 // C = ~Z for AND instruction, thus we can put Res = ~(SR & 1), however,
1069 // Res = (SR >> 1) & 1 is 1 word shorter.
1070 break;
1071 }
1072 EVT VT = Op.getValueType();
1073 SDValue One = DAG.getConstant(1, dl, VT);
1074 if (Convert) {
1075 SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, MSP430::SR,
1076 MVT::i16, Flag);
1077 if (Shift)
1078 // FIXME: somewhere this is turned into a SRL, lower it MSP specific?
1079 SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One);
1080 SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One);
1081 if (Invert)
1082 SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One);
1083 return SR;
1084 } else {
1085 SDValue Zero = DAG.getConstant(0, dl, VT);
1086 SDValue Ops[] = {One, Zero, TargetCC, Flag};
1087 return DAG.getNode(MSP430ISD::SELECT_CC, dl, Op.getValueType(), Ops);
1088 }
1089 }
1090
LowerSELECT_CC(SDValue Op,SelectionDAG & DAG) const1091 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op,
1092 SelectionDAG &DAG) const {
1093 SDValue LHS = Op.getOperand(0);
1094 SDValue RHS = Op.getOperand(1);
1095 SDValue TrueV = Op.getOperand(2);
1096 SDValue FalseV = Op.getOperand(3);
1097 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1098 SDLoc dl (Op);
1099
1100 SDValue TargetCC;
1101 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1102
1103 SDValue Ops[] = {TrueV, FalseV, TargetCC, Flag};
1104
1105 return DAG.getNode(MSP430ISD::SELECT_CC, dl, Op.getValueType(), Ops);
1106 }
1107
LowerSIGN_EXTEND(SDValue Op,SelectionDAG & DAG) const1108 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
1109 SelectionDAG &DAG) const {
1110 SDValue Val = Op.getOperand(0);
1111 EVT VT = Op.getValueType();
1112 SDLoc dl(Op);
1113
1114 assert(VT == MVT::i16 && "Only support i16 for now!");
1115
1116 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
1117 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
1118 DAG.getValueType(Val.getValueType()));
1119 }
1120
1121 SDValue
getReturnAddressFrameIndex(SelectionDAG & DAG) const1122 MSP430TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
1123 MachineFunction &MF = DAG.getMachineFunction();
1124 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1125 int ReturnAddrIndex = FuncInfo->getRAIndex();
1126 MVT PtrVT = getFrameIndexTy(MF.getDataLayout());
1127
1128 if (ReturnAddrIndex == 0) {
1129 // Set up a frame object for the return address.
1130 uint64_t SlotSize = PtrVT.getStoreSize();
1131 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize, -SlotSize,
1132 true);
1133 FuncInfo->setRAIndex(ReturnAddrIndex);
1134 }
1135
1136 return DAG.getFrameIndex(ReturnAddrIndex, PtrVT);
1137 }
1138
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const1139 SDValue MSP430TargetLowering::LowerRETURNADDR(SDValue Op,
1140 SelectionDAG &DAG) const {
1141 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1142 MFI.setReturnAddressIsTaken(true);
1143
1144 unsigned Depth = Op.getConstantOperandVal(0);
1145 SDLoc dl(Op);
1146 EVT PtrVT = Op.getValueType();
1147
1148 if (Depth > 0) {
1149 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1150 SDValue Offset =
1151 DAG.getConstant(PtrVT.getStoreSize(), dl, MVT::i16);
1152 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1153 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
1154 MachinePointerInfo());
1155 }
1156
1157 // Just load the return address.
1158 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
1159 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
1160 MachinePointerInfo());
1161 }
1162
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const1163 SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op,
1164 SelectionDAG &DAG) const {
1165 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1166 MFI.setFrameAddressIsTaken(true);
1167
1168 EVT VT = Op.getValueType();
1169 SDLoc dl(Op); // FIXME probably not meaningful
1170 unsigned Depth = Op.getConstantOperandVal(0);
1171 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1172 MSP430::R4, VT);
1173 while (Depth--)
1174 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1175 MachinePointerInfo());
1176 return FrameAddr;
1177 }
1178
LowerVASTART(SDValue Op,SelectionDAG & DAG) const1179 SDValue MSP430TargetLowering::LowerVASTART(SDValue Op,
1180 SelectionDAG &DAG) const {
1181 MachineFunction &MF = DAG.getMachineFunction();
1182 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1183
1184 SDValue Ptr = Op.getOperand(1);
1185 EVT PtrVT = Ptr.getValueType();
1186
1187 // Frame index of first vararg argument
1188 SDValue FrameIndex =
1189 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1190 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1191
1192 // Create a store of the frame index to the location operand
1193 return DAG.getStore(Op.getOperand(0), SDLoc(Op), FrameIndex, Ptr,
1194 MachinePointerInfo(SV));
1195 }
1196
LowerJumpTable(SDValue Op,SelectionDAG & DAG) const1197 SDValue MSP430TargetLowering::LowerJumpTable(SDValue Op,
1198 SelectionDAG &DAG) const {
1199 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1200 EVT PtrVT = Op.getValueType();
1201 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1202 return DAG.getNode(MSP430ISD::Wrapper, SDLoc(JT), PtrVT, Result);
1203 }
1204
1205 /// getPostIndexedAddressParts - returns true by value, base pointer and
1206 /// offset pointer and addressing mode by reference if this node can be
1207 /// combined with a load / store to form a post-indexed load / store.
getPostIndexedAddressParts(SDNode * N,SDNode * Op,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const1208 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
1209 SDValue &Base,
1210 SDValue &Offset,
1211 ISD::MemIndexedMode &AM,
1212 SelectionDAG &DAG) const {
1213
1214 LoadSDNode *LD = cast<LoadSDNode>(N);
1215 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1216 return false;
1217
1218 EVT VT = LD->getMemoryVT();
1219 if (VT != MVT::i8 && VT != MVT::i16)
1220 return false;
1221
1222 if (Op->getOpcode() != ISD::ADD)
1223 return false;
1224
1225 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1226 uint64_t RHSC = RHS->getZExtValue();
1227 if ((VT == MVT::i16 && RHSC != 2) ||
1228 (VT == MVT::i8 && RHSC != 1))
1229 return false;
1230
1231 Base = Op->getOperand(0);
1232 Offset = DAG.getConstant(RHSC, SDLoc(N), VT);
1233 AM = ISD::POST_INC;
1234 return true;
1235 }
1236
1237 return false;
1238 }
1239
isTruncateFree(Type * Ty1,Type * Ty2) const1240 bool MSP430TargetLowering::isTruncateFree(Type *Ty1,
1241 Type *Ty2) const {
1242 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
1243 return false;
1244
1245 return (Ty1->getPrimitiveSizeInBits().getFixedValue() >
1246 Ty2->getPrimitiveSizeInBits().getFixedValue());
1247 }
1248
isTruncateFree(EVT VT1,EVT VT2) const1249 bool MSP430TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1250 if (!VT1.isInteger() || !VT2.isInteger())
1251 return false;
1252
1253 return (VT1.getFixedSizeInBits() > VT2.getFixedSizeInBits());
1254 }
1255
isZExtFree(Type * Ty1,Type * Ty2) const1256 bool MSP430TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
1257 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1258 return false && Ty1->isIntegerTy(8) && Ty2->isIntegerTy(16);
1259 }
1260
isZExtFree(EVT VT1,EVT VT2) const1261 bool MSP430TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
1262 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1263 return false && VT1 == MVT::i8 && VT2 == MVT::i16;
1264 }
1265
1266 //===----------------------------------------------------------------------===//
1267 // Other Lowering Code
1268 //===----------------------------------------------------------------------===//
1269
1270 MachineBasicBlock *
EmitShiftInstr(MachineInstr & MI,MachineBasicBlock * BB) const1271 MSP430TargetLowering::EmitShiftInstr(MachineInstr &MI,
1272 MachineBasicBlock *BB) const {
1273 MachineFunction *F = BB->getParent();
1274 MachineRegisterInfo &RI = F->getRegInfo();
1275 DebugLoc dl = MI.getDebugLoc();
1276 const TargetInstrInfo &TII = *F->getSubtarget().getInstrInfo();
1277
1278 unsigned Opc;
1279 bool ClearCarry = false;
1280 const TargetRegisterClass * RC;
1281 switch (MI.getOpcode()) {
1282 default: llvm_unreachable("Invalid shift opcode!");
1283 case MSP430::Shl8:
1284 Opc = MSP430::ADD8rr;
1285 RC = &MSP430::GR8RegClass;
1286 break;
1287 case MSP430::Shl16:
1288 Opc = MSP430::ADD16rr;
1289 RC = &MSP430::GR16RegClass;
1290 break;
1291 case MSP430::Sra8:
1292 Opc = MSP430::RRA8r;
1293 RC = &MSP430::GR8RegClass;
1294 break;
1295 case MSP430::Sra16:
1296 Opc = MSP430::RRA16r;
1297 RC = &MSP430::GR16RegClass;
1298 break;
1299 case MSP430::Srl8:
1300 ClearCarry = true;
1301 Opc = MSP430::RRC8r;
1302 RC = &MSP430::GR8RegClass;
1303 break;
1304 case MSP430::Srl16:
1305 ClearCarry = true;
1306 Opc = MSP430::RRC16r;
1307 RC = &MSP430::GR16RegClass;
1308 break;
1309 case MSP430::Rrcl8:
1310 case MSP430::Rrcl16: {
1311 BuildMI(*BB, MI, dl, TII.get(MSP430::BIC16rc), MSP430::SR)
1312 .addReg(MSP430::SR).addImm(1);
1313 Register SrcReg = MI.getOperand(1).getReg();
1314 Register DstReg = MI.getOperand(0).getReg();
1315 unsigned RrcOpc = MI.getOpcode() == MSP430::Rrcl16
1316 ? MSP430::RRC16r : MSP430::RRC8r;
1317 BuildMI(*BB, MI, dl, TII.get(RrcOpc), DstReg)
1318 .addReg(SrcReg);
1319 MI.eraseFromParent(); // The pseudo instruction is gone now.
1320 return BB;
1321 }
1322 }
1323
1324 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1325 MachineFunction::iterator I = ++BB->getIterator();
1326
1327 // Create loop block
1328 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1329 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB);
1330
1331 F->insert(I, LoopBB);
1332 F->insert(I, RemBB);
1333
1334 // Update machine-CFG edges by transferring all successors of the current
1335 // block to the block containing instructions after shift.
1336 RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
1337 BB->end());
1338 RemBB->transferSuccessorsAndUpdatePHIs(BB);
1339
1340 // Add edges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB
1341 BB->addSuccessor(LoopBB);
1342 BB->addSuccessor(RemBB);
1343 LoopBB->addSuccessor(RemBB);
1344 LoopBB->addSuccessor(LoopBB);
1345
1346 Register ShiftAmtReg = RI.createVirtualRegister(&MSP430::GR8RegClass);
1347 Register ShiftAmtReg2 = RI.createVirtualRegister(&MSP430::GR8RegClass);
1348 Register ShiftReg = RI.createVirtualRegister(RC);
1349 Register ShiftReg2 = RI.createVirtualRegister(RC);
1350 Register ShiftAmtSrcReg = MI.getOperand(2).getReg();
1351 Register SrcReg = MI.getOperand(1).getReg();
1352 Register DstReg = MI.getOperand(0).getReg();
1353
1354 // BB:
1355 // cmp 0, N
1356 // je RemBB
1357 BuildMI(BB, dl, TII.get(MSP430::CMP8ri))
1358 .addReg(ShiftAmtSrcReg).addImm(0);
1359 BuildMI(BB, dl, TII.get(MSP430::JCC))
1360 .addMBB(RemBB)
1361 .addImm(MSP430CC::COND_E);
1362
1363 // LoopBB:
1364 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1365 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB]
1366 // ShiftReg2 = shift ShiftReg
1367 // ShiftAmt2 = ShiftAmt - 1;
1368 BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftReg)
1369 .addReg(SrcReg).addMBB(BB)
1370 .addReg(ShiftReg2).addMBB(LoopBB);
1371 BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftAmtReg)
1372 .addReg(ShiftAmtSrcReg).addMBB(BB)
1373 .addReg(ShiftAmtReg2).addMBB(LoopBB);
1374 if (ClearCarry)
1375 BuildMI(LoopBB, dl, TII.get(MSP430::BIC16rc), MSP430::SR)
1376 .addReg(MSP430::SR).addImm(1);
1377 if (Opc == MSP430::ADD8rr || Opc == MSP430::ADD16rr)
1378 BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
1379 .addReg(ShiftReg)
1380 .addReg(ShiftReg);
1381 else
1382 BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
1383 .addReg(ShiftReg);
1384 BuildMI(LoopBB, dl, TII.get(MSP430::SUB8ri), ShiftAmtReg2)
1385 .addReg(ShiftAmtReg).addImm(1);
1386 BuildMI(LoopBB, dl, TII.get(MSP430::JCC))
1387 .addMBB(LoopBB)
1388 .addImm(MSP430CC::COND_NE);
1389
1390 // RemBB:
1391 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1392 BuildMI(*RemBB, RemBB->begin(), dl, TII.get(MSP430::PHI), DstReg)
1393 .addReg(SrcReg).addMBB(BB)
1394 .addReg(ShiftReg2).addMBB(LoopBB);
1395
1396 MI.eraseFromParent(); // The pseudo instruction is gone now.
1397 return RemBB;
1398 }
1399
1400 MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const1401 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1402 MachineBasicBlock *BB) const {
1403 unsigned Opc = MI.getOpcode();
1404
1405 if (Opc == MSP430::Shl8 || Opc == MSP430::Shl16 ||
1406 Opc == MSP430::Sra8 || Opc == MSP430::Sra16 ||
1407 Opc == MSP430::Srl8 || Opc == MSP430::Srl16 ||
1408 Opc == MSP430::Rrcl8 || Opc == MSP430::Rrcl16)
1409 return EmitShiftInstr(MI, BB);
1410
1411 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
1412 DebugLoc dl = MI.getDebugLoc();
1413
1414 assert((Opc == MSP430::Select16 || Opc == MSP430::Select8) &&
1415 "Unexpected instr type to insert");
1416
1417 // To "insert" a SELECT instruction, we actually have to insert the diamond
1418 // control-flow pattern. The incoming instruction knows the destination vreg
1419 // to set, the condition code register to branch on, the true/false values to
1420 // select between, and a branch opcode to use.
1421 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1422 MachineFunction::iterator I = ++BB->getIterator();
1423
1424 // thisMBB:
1425 // ...
1426 // TrueVal = ...
1427 // cmpTY ccX, r1, r2
1428 // jCC copy1MBB
1429 // fallthrough --> copy0MBB
1430 MachineBasicBlock *thisMBB = BB;
1431 MachineFunction *F = BB->getParent();
1432 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1433 MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
1434 F->insert(I, copy0MBB);
1435 F->insert(I, copy1MBB);
1436 // Update machine-CFG edges by transferring all successors of the current
1437 // block to the new block which will contain the Phi node for the select.
1438 copy1MBB->splice(copy1MBB->begin(), BB,
1439 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1440 copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
1441 // Next, add the true and fallthrough blocks as its successors.
1442 BB->addSuccessor(copy0MBB);
1443 BB->addSuccessor(copy1MBB);
1444
1445 BuildMI(BB, dl, TII.get(MSP430::JCC))
1446 .addMBB(copy1MBB)
1447 .addImm(MI.getOperand(3).getImm());
1448
1449 // copy0MBB:
1450 // %FalseValue = ...
1451 // # fallthrough to copy1MBB
1452 BB = copy0MBB;
1453
1454 // Update machine-CFG edges
1455 BB->addSuccessor(copy1MBB);
1456
1457 // copy1MBB:
1458 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1459 // ...
1460 BB = copy1MBB;
1461 BuildMI(*BB, BB->begin(), dl, TII.get(MSP430::PHI), MI.getOperand(0).getReg())
1462 .addReg(MI.getOperand(2).getReg())
1463 .addMBB(copy0MBB)
1464 .addReg(MI.getOperand(1).getReg())
1465 .addMBB(thisMBB);
1466
1467 MI.eraseFromParent(); // The pseudo instruction is gone now.
1468 return BB;
1469 }
1470