[C++] Use 'nullptr'. Target edition.
[oota-llvm.git] / lib / Target / Hexagon / HexagonISelLowering.cpp
1 //===-- HexagonISelLowering.cpp - Hexagon DAG Lowering Implementation -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interfaces that Hexagon uses to lower LLVM code
11 // into a selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "HexagonISelLowering.h"
16 #include "HexagonMachineFunctionInfo.h"
17 #include "HexagonSubtarget.h"
18 #include "HexagonTargetMachine.h"
19 #include "HexagonTargetObjectFile.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/ValueTypes.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39
40 using namespace llvm;
41
42 #define DEBUG_TYPE "hexagon-lowering"
43
44 static cl::opt<bool>
45 EmitJumpTables("hexagon-emit-jump-tables", cl::init(true), cl::Hidden,
46                cl::desc("Control jump table emission on Hexagon target"));
47
48 namespace {
49 class HexagonCCState : public CCState {
50   int NumNamedVarArgParams;
51
52 public:
53   HexagonCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
54                  const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
55                  LLVMContext &C, int NumNamedVarArgParams)
56       : CCState(CC, isVarArg, MF, TM, locs, C),
57         NumNamedVarArgParams(NumNamedVarArgParams) {}
58
59   int getNumNamedVarArgParams() const { return NumNamedVarArgParams; }
60 };
61 }
62
63 // Implement calling convention for Hexagon.
64 static bool
65 CC_Hexagon(unsigned ValNo, MVT ValVT,
66            MVT LocVT, CCValAssign::LocInfo LocInfo,
67            ISD::ArgFlagsTy ArgFlags, CCState &State);
68
69 static bool
70 CC_Hexagon32(unsigned ValNo, MVT ValVT,
71              MVT LocVT, CCValAssign::LocInfo LocInfo,
72              ISD::ArgFlagsTy ArgFlags, CCState &State);
73
74 static bool
75 CC_Hexagon64(unsigned ValNo, MVT ValVT,
76              MVT LocVT, CCValAssign::LocInfo LocInfo,
77              ISD::ArgFlagsTy ArgFlags, CCState &State);
78
79 static bool
80 RetCC_Hexagon(unsigned ValNo, MVT ValVT,
81               MVT LocVT, CCValAssign::LocInfo LocInfo,
82               ISD::ArgFlagsTy ArgFlags, CCState &State);
83
84 static bool
85 RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
86                 MVT LocVT, CCValAssign::LocInfo LocInfo,
87                 ISD::ArgFlagsTy ArgFlags, CCState &State);
88
89 static bool
90 RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
91                 MVT LocVT, CCValAssign::LocInfo LocInfo,
92                 ISD::ArgFlagsTy ArgFlags, CCState &State);
93
94 static bool
95 CC_Hexagon_VarArg (unsigned ValNo, MVT ValVT,
96             MVT LocVT, CCValAssign::LocInfo LocInfo,
97             ISD::ArgFlagsTy ArgFlags, CCState &State) {
98   HexagonCCState &HState = static_cast<HexagonCCState &>(State);
99
100   // NumNamedVarArgParams can not be zero for a VarArg function.
101   assert((HState.getNumNamedVarArgParams() > 0) &&
102          "NumNamedVarArgParams is not bigger than zero.");
103
104   if ((int)ValNo < HState.getNumNamedVarArgParams()) {
105     // Deal with named arguments.
106     return CC_Hexagon(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State);
107   }
108
109   // Deal with un-named arguments.
110   unsigned ofst;
111   if (ArgFlags.isByVal()) {
112     // If pass-by-value, the size allocated on stack is decided
113     // by ArgFlags.getByValSize(), not by the size of LocVT.
114     assert ((ArgFlags.getByValSize() > 8) &&
115             "ByValSize must be bigger than 8 bytes");
116     ofst = State.AllocateStack(ArgFlags.getByValSize(), 4);
117     State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
118     return false;
119   }
120   if (LocVT == MVT::i1 || LocVT == MVT::i8 || LocVT == MVT::i16) {
121     LocVT = MVT::i32;
122     ValVT = MVT::i32;
123     if (ArgFlags.isSExt())
124       LocInfo = CCValAssign::SExt;
125     else if (ArgFlags.isZExt())
126       LocInfo = CCValAssign::ZExt;
127     else
128       LocInfo = CCValAssign::AExt;
129   }
130   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
131     ofst = State.AllocateStack(4, 4);
132     State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
133     return false;
134   }
135   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
136     ofst = State.AllocateStack(8, 8);
137     State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
138     return false;
139   }
140   llvm_unreachable(0);
141 }
142
143
144 static bool
145 CC_Hexagon (unsigned ValNo, MVT ValVT,
146             MVT LocVT, CCValAssign::LocInfo LocInfo,
147             ISD::ArgFlagsTy ArgFlags, CCState &State) {
148
149   if (ArgFlags.isByVal()) {
150     // Passed on stack.
151     assert ((ArgFlags.getByValSize() > 8) &&
152             "ByValSize must be bigger than 8 bytes");
153     unsigned Offset = State.AllocateStack(ArgFlags.getByValSize(), 4);
154     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
155     return false;
156   }
157
158   if (LocVT == MVT::i1 || LocVT == MVT::i8 || LocVT == MVT::i16) {
159     LocVT = MVT::i32;
160     ValVT = MVT::i32;
161     if (ArgFlags.isSExt())
162       LocInfo = CCValAssign::SExt;
163     else if (ArgFlags.isZExt())
164       LocInfo = CCValAssign::ZExt;
165     else
166       LocInfo = CCValAssign::AExt;
167   }
168
169   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
170     if (!CC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
171       return false;
172   }
173
174   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
175     if (!CC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
176       return false;
177   }
178
179   return true;  // CC didn't match.
180 }
181
182
183 static bool CC_Hexagon32(unsigned ValNo, MVT ValVT,
184                          MVT LocVT, CCValAssign::LocInfo LocInfo,
185                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
186
187   static const MCPhysReg RegList[] = {
188     Hexagon::R0, Hexagon::R1, Hexagon::R2, Hexagon::R3, Hexagon::R4,
189     Hexagon::R5
190   };
191   if (unsigned Reg = State.AllocateReg(RegList, 6)) {
192     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
193     return false;
194   }
195
196   unsigned Offset = State.AllocateStack(4, 4);
197   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
198   return false;
199 }
200
201 static bool CC_Hexagon64(unsigned ValNo, MVT ValVT,
202                          MVT LocVT, CCValAssign::LocInfo LocInfo,
203                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
204
205   if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
206     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
207     return false;
208   }
209
210   static const MCPhysReg RegList1[] = {
211     Hexagon::D1, Hexagon::D2
212   };
213   static const MCPhysReg RegList2[] = {
214     Hexagon::R1, Hexagon::R3
215   };
216   if (unsigned Reg = State.AllocateReg(RegList1, RegList2, 2)) {
217     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
218     return false;
219   }
220
221   unsigned Offset = State.AllocateStack(8, 8, Hexagon::D2);
222   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
223   return false;
224 }
225
226 static bool RetCC_Hexagon(unsigned ValNo, MVT ValVT,
227                           MVT LocVT, CCValAssign::LocInfo LocInfo,
228                           ISD::ArgFlagsTy ArgFlags, CCState &State) {
229
230
231   if (LocVT == MVT::i1 ||
232       LocVT == MVT::i8 ||
233       LocVT == MVT::i16) {
234     LocVT = MVT::i32;
235     ValVT = MVT::i32;
236     if (ArgFlags.isSExt())
237       LocInfo = CCValAssign::SExt;
238     else if (ArgFlags.isZExt())
239       LocInfo = CCValAssign::ZExt;
240     else
241       LocInfo = CCValAssign::AExt;
242   }
243
244   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
245     if (!RetCC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
246     return false;
247   }
248
249   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
250     if (!RetCC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
251     return false;
252   }
253
254   return true;  // CC didn't match.
255 }
256
257 static bool RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
258                             MVT LocVT, CCValAssign::LocInfo LocInfo,
259                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
260
261   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
262     if (unsigned Reg = State.AllocateReg(Hexagon::R0)) {
263       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
264       return false;
265     }
266   }
267
268   unsigned Offset = State.AllocateStack(4, 4);
269   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
270   return false;
271 }
272
273 static bool RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
274                             MVT LocVT, CCValAssign::LocInfo LocInfo,
275                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
276   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
277     if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
278       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
279       return false;
280     }
281   }
282
283   unsigned Offset = State.AllocateStack(8, 8);
284   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
285   return false;
286 }
287
288 SDValue
289 HexagonTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG)
290 const {
291   return SDValue();
292 }
293
294 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
295 /// by "Src" to address "Dst" of size "Size".  Alignment information is
296 /// specified by the specific parameter attribute. The copy will be passed as
297 /// a byval function parameter.  Sometimes what we are copying is the end of a
298 /// larger object, the part that does not fit in registers.
299 static SDValue
300 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
301                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
302                           SDLoc dl) {
303
304   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
305   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
306                        /*isVolatile=*/false, /*AlwaysInline=*/false,
307                        MachinePointerInfo(), MachinePointerInfo());
308 }
309
310
311 // LowerReturn - Lower ISD::RET. If a struct is larger than 8 bytes and is
312 // passed by value, the function prototype is modified to return void and
313 // the value is stored in memory pointed by a pointer passed by caller.
314 SDValue
315 HexagonTargetLowering::LowerReturn(SDValue Chain,
316                                    CallingConv::ID CallConv, bool isVarArg,
317                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
318                                    const SmallVectorImpl<SDValue> &OutVals,
319                                    SDLoc dl, SelectionDAG &DAG) const {
320
321   // CCValAssign - represent the assignment of the return value to locations.
322   SmallVector<CCValAssign, 16> RVLocs;
323
324   // CCState - Info about the registers and stack slot.
325   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
326                  getTargetMachine(), RVLocs, *DAG.getContext());
327
328   // Analyze return values of ISD::RET
329   CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon);
330
331   SDValue Flag;
332   SmallVector<SDValue, 4> RetOps(1, Chain);
333
334   // Copy the result values into the output registers.
335   for (unsigned i = 0; i != RVLocs.size(); ++i) {
336     CCValAssign &VA = RVLocs[i];
337
338     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
339
340     // Guarantee that all emitted copies are stuck together with flags.
341     Flag = Chain.getValue(1);
342     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
343   }
344
345   RetOps[0] = Chain;  // Update chain.
346
347   // Add the flag if we have it.
348   if (Flag.getNode())
349     RetOps.push_back(Flag);
350
351   return DAG.getNode(HexagonISD::RET_FLAG, dl, MVT::Other,
352                      &RetOps[0], RetOps.size());
353 }
354
355
356
357
358 /// LowerCallResult - Lower the result values of an ISD::CALL into the
359 /// appropriate copies out of appropriate physical registers.  This assumes that
360 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
361 /// being lowered. Returns a SDNode with the same number of values as the
362 /// ISD::CALL.
363 SDValue
364 HexagonTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
365                                        CallingConv::ID CallConv, bool isVarArg,
366                                        const
367                                        SmallVectorImpl<ISD::InputArg> &Ins,
368                                        SDLoc dl, SelectionDAG &DAG,
369                                        SmallVectorImpl<SDValue> &InVals,
370                                        const SmallVectorImpl<SDValue> &OutVals,
371                                        SDValue Callee) const {
372
373   // Assign locations to each value returned by this call.
374   SmallVector<CCValAssign, 16> RVLocs;
375
376   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
377                  getTargetMachine(), RVLocs, *DAG.getContext());
378
379   CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon);
380
381   // Copy all of the result registers out of their specified physreg.
382   for (unsigned i = 0; i != RVLocs.size(); ++i) {
383     Chain = DAG.getCopyFromReg(Chain, dl,
384                                RVLocs[i].getLocReg(),
385                                RVLocs[i].getValVT(), InFlag).getValue(1);
386     InFlag = Chain.getValue(2);
387     InVals.push_back(Chain.getValue(0));
388   }
389
390   return Chain;
391 }
392
393 /// LowerCall - Functions arguments are copied from virtual regs to
394 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
395 SDValue
396 HexagonTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
397                                  SmallVectorImpl<SDValue> &InVals) const {
398   SelectionDAG &DAG                     = CLI.DAG;
399   SDLoc &dl                             = CLI.DL;
400   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
401   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
402   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
403   SDValue Chain                         = CLI.Chain;
404   SDValue Callee                        = CLI.Callee;
405   bool &isTailCall                      = CLI.IsTailCall;
406   CallingConv::ID CallConv              = CLI.CallConv;
407   bool isVarArg                         = CLI.IsVarArg;
408
409   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
410
411   // Check for varargs.
412   int NumNamedVarArgParams = -1;
413   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee))
414   {
415     const Function* CalleeFn = nullptr;
416     Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, MVT::i32);
417     if ((CalleeFn = dyn_cast<Function>(GA->getGlobal())))
418     {
419       // If a function has zero args and is a vararg function, that's
420       // disallowed so it must be an undeclared function.  Do not assume
421       // varargs if the callee is undefined.
422       if (CalleeFn->isVarArg() &&
423           CalleeFn->getFunctionType()->getNumParams() != 0) {
424         NumNamedVarArgParams = CalleeFn->getFunctionType()->getNumParams();
425       }
426     }
427   }
428
429   // Analyze operands of the call, assigning locations to each operand.
430   SmallVector<CCValAssign, 16> ArgLocs;
431   HexagonCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
432                         getTargetMachine(), ArgLocs, *DAG.getContext(),
433                         NumNamedVarArgParams);
434
435   if (NumNamedVarArgParams > 0)
436     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon_VarArg);
437   else
438     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon);
439
440
441   if(isTailCall) {
442     bool StructAttrFlag =
443       DAG.getMachineFunction().getFunction()->hasStructRetAttr();
444     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
445                                                    isVarArg, IsStructRet,
446                                                    StructAttrFlag,
447                                                    Outs, OutVals, Ins, DAG);
448     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i){
449       CCValAssign &VA = ArgLocs[i];
450       if (VA.isMemLoc()) {
451         isTailCall = false;
452         break;
453       }
454     }
455     if (isTailCall) {
456       DEBUG(dbgs () << "Eligible for Tail Call\n");
457     } else {
458       DEBUG(dbgs () <<
459             "Argument must be passed on stack. Not eligible for Tail Call\n");
460     }
461   }
462   // Get a count of how many bytes are to be pushed on the stack.
463   unsigned NumBytes = CCInfo.getNextStackOffset();
464   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
465   SmallVector<SDValue, 8> MemOpChains;
466
467   SDValue StackPtr =
468     DAG.getCopyFromReg(Chain, dl, TM.getRegisterInfo()->getStackRegister(),
469                        getPointerTy());
470
471   // Walk the register/memloc assignments, inserting copies/loads.
472   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
473     CCValAssign &VA = ArgLocs[i];
474     SDValue Arg = OutVals[i];
475     ISD::ArgFlagsTy Flags = Outs[i].Flags;
476
477     // Promote the value if needed.
478     switch (VA.getLocInfo()) {
479       default:
480         // Loc info must be one of Full, SExt, ZExt, or AExt.
481         llvm_unreachable("Unknown loc info!");
482       case CCValAssign::Full:
483         break;
484       case CCValAssign::SExt:
485         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
486         break;
487       case CCValAssign::ZExt:
488         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
489         break;
490       case CCValAssign::AExt:
491         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
492         break;
493     }
494
495     if (VA.isMemLoc()) {
496       unsigned LocMemOffset = VA.getLocMemOffset();
497       SDValue PtrOff = DAG.getConstant(LocMemOffset, StackPtr.getValueType());
498       PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
499
500       if (Flags.isByVal()) {
501         // The argument is a struct passed by value. According to LLVM, "Arg"
502         // is is pointer.
503         MemOpChains.push_back(CreateCopyOfByValArgument(Arg, PtrOff, Chain,
504                                                         Flags, DAG, dl));
505       } else {
506         // The argument is not passed by value. "Arg" is a buildin type. It is
507         // not a pointer.
508         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
509                                            MachinePointerInfo(),false, false,
510                                            0));
511       }
512       continue;
513     }
514
515     // Arguments that can be passed on register must be kept at RegsToPass
516     // vector.
517     if (VA.isRegLoc()) {
518       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
519     }
520   }
521
522   // Transform all store nodes into one single node because all store
523   // nodes are independent of each other.
524   if (!MemOpChains.empty()) {
525     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &MemOpChains[0],
526                         MemOpChains.size());
527   }
528
529   if (!isTailCall)
530     Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes,
531                                                         getPointerTy(), true),
532                                  dl);
533
534   // Build a sequence of copy-to-reg nodes chained together with token
535   // chain and flag operands which copy the outgoing args into registers.
536   // The InFlag in necessary since all emitted instructions must be
537   // stuck together.
538   SDValue InFlag;
539   if (!isTailCall) {
540     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
541       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
542                                RegsToPass[i].second, InFlag);
543       InFlag = Chain.getValue(1);
544     }
545   }
546
547   // For tail calls lower the arguments to the 'real' stack slot.
548   if (isTailCall) {
549     // Force all the incoming stack arguments to be loaded from the stack
550     // before any new outgoing arguments are stored to the stack, because the
551     // outgoing stack slots may alias the incoming argument stack slots, and
552     // the alias isn't otherwise explicit. This is slightly more conservative
553     // than necessary, because it means that each store effectively depends
554     // on every argument instead of just those arguments it would clobber.
555     //
556     // Do not flag preceding copytoreg stuff together with the following stuff.
557     InFlag = SDValue();
558     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
559       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
560                                RegsToPass[i].second, InFlag);
561       InFlag = Chain.getValue(1);
562     }
563     InFlag =SDValue();
564   }
565
566   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
567   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
568   // node so that legalize doesn't hack it.
569   if (flag_aligned_memcpy) {
570     const char *MemcpyName =
571       "__hexagon_memcpy_likely_aligned_min32bytes_mult8bytes";
572     Callee =
573       DAG.getTargetExternalSymbol(MemcpyName, getPointerTy());
574     flag_aligned_memcpy = false;
575   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
576     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy());
577   } else if (ExternalSymbolSDNode *S =
578              dyn_cast<ExternalSymbolSDNode>(Callee)) {
579     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
580   }
581
582   // Returns a chain & a flag for retval copy to use.
583   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
584   SmallVector<SDValue, 8> Ops;
585   Ops.push_back(Chain);
586   Ops.push_back(Callee);
587
588   // Add argument registers to the end of the list so that they are
589   // known live into the call.
590   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
591     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
592                                   RegsToPass[i].second.getValueType()));
593   }
594
595   if (InFlag.getNode()) {
596     Ops.push_back(InFlag);
597   }
598
599   if (isTailCall)
600     return DAG.getNode(HexagonISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
601
602   Chain = DAG.getNode(HexagonISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
603   InFlag = Chain.getValue(1);
604
605   // Create the CALLSEQ_END node.
606   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
607                              DAG.getIntPtrConstant(0, true), InFlag, dl);
608   InFlag = Chain.getValue(1);
609
610   // Handle result values, copying them out of physregs into vregs that we
611   // return.
612   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
613                          InVals, OutVals, Callee);
614 }
615
616 static bool getIndexedAddressParts(SDNode *Ptr, EVT VT,
617                                    bool isSEXTLoad, SDValue &Base,
618                                    SDValue &Offset, bool &isInc,
619                                    SelectionDAG &DAG) {
620   if (Ptr->getOpcode() != ISD::ADD)
621   return false;
622
623   if (VT == MVT::i64 || VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
624     isInc = (Ptr->getOpcode() == ISD::ADD);
625     Base = Ptr->getOperand(0);
626     Offset = Ptr->getOperand(1);
627     // Ensure that Offset is a constant.
628     return (isa<ConstantSDNode>(Offset));
629   }
630
631   return false;
632 }
633
634 // TODO: Put this function along with the other isS* functions in
635 // HexagonISelDAGToDAG.cpp into a common file. Or better still, use the
636 // functions defined in HexagonOperands.td.
637 static bool Is_PostInc_S4_Offset(SDNode * S, int ShiftAmount) {
638   ConstantSDNode *N = cast<ConstantSDNode>(S);
639
640   // immS4 predicate - True if the immediate fits in a 4-bit sign extended.
641   // field.
642   int64_t v = (int64_t)N->getSExtValue();
643   int64_t m = 0;
644   if (ShiftAmount > 0) {
645     m = v % ShiftAmount;
646     v = v >> ShiftAmount;
647   }
648   return (v <= 7) && (v >= -8) && (m == 0);
649 }
650
651 /// getPostIndexedAddressParts - returns true by value, base pointer and
652 /// offset pointer and addressing mode by reference if this node can be
653 /// combined with a load / store to form a post-indexed load / store.
654 bool HexagonTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
655                                                        SDValue &Base,
656                                                        SDValue &Offset,
657                                                        ISD::MemIndexedMode &AM,
658                                                        SelectionDAG &DAG) const
659 {
660   EVT VT;
661   SDValue Ptr;
662   bool isSEXTLoad = false;
663
664   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
665     VT  = LD->getMemoryVT();
666     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
667   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
668     VT  = ST->getMemoryVT();
669     if (ST->getValue().getValueType() == MVT::i64 && ST->isTruncatingStore()) {
670       return false;
671     }
672   } else {
673     return false;
674   }
675
676   bool isInc = false;
677   bool isLegal = getIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
678                                         isInc, DAG);
679   // ShiftAmount = number of left-shifted bits in the Hexagon instruction.
680   int ShiftAmount = VT.getSizeInBits() / 16;
681   if (isLegal && Is_PostInc_S4_Offset(Offset.getNode(), ShiftAmount)) {
682     AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
683     return true;
684   }
685
686   return false;
687 }
688
689 SDValue HexagonTargetLowering::LowerINLINEASM(SDValue Op,
690                                               SelectionDAG &DAG) const {
691   SDNode *Node = Op.getNode();
692   MachineFunction &MF = DAG.getMachineFunction();
693   HexagonMachineFunctionInfo *FuncInfo =
694     MF.getInfo<HexagonMachineFunctionInfo>();
695   switch (Node->getOpcode()) {
696     case ISD::INLINEASM: {
697       unsigned NumOps = Node->getNumOperands();
698       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
699         --NumOps;  // Ignore the flag operand.
700
701       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
702         if (FuncInfo->hasClobberLR())
703           break;
704         unsigned Flags =
705           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
706         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
707         ++i;  // Skip the ID value.
708
709         switch (InlineAsm::getKind(Flags)) {
710         default: llvm_unreachable("Bad flags!");
711           case InlineAsm::Kind_RegDef:
712           case InlineAsm::Kind_RegUse:
713           case InlineAsm::Kind_Imm:
714           case InlineAsm::Kind_Clobber:
715           case InlineAsm::Kind_Mem: {
716             for (; NumVals; --NumVals, ++i) {}
717             break;
718           }
719           case InlineAsm::Kind_RegDefEarlyClobber: {
720             for (; NumVals; --NumVals, ++i) {
721               unsigned Reg =
722                 cast<RegisterSDNode>(Node->getOperand(i))->getReg();
723
724               // Check it to be lr
725               if (Reg == TM.getRegisterInfo()->getRARegister()) {
726                 FuncInfo->setHasClobberLR(true);
727                 break;
728               }
729             }
730             break;
731           }
732         }
733       }
734     }
735   } // Node->getOpcode
736   return Op;
737 }
738
739
740 //
741 // Taken from the XCore backend.
742 //
743 SDValue HexagonTargetLowering::
744 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
745 {
746   SDValue Chain = Op.getOperand(0);
747   SDValue Table = Op.getOperand(1);
748   SDValue Index = Op.getOperand(2);
749   SDLoc dl(Op);
750   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
751   unsigned JTI = JT->getIndex();
752   MachineFunction &MF = DAG.getMachineFunction();
753   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
754   SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
755
756   // Mark all jump table targets as address taken.
757   const std::vector<MachineJumpTableEntry> &JTE = MJTI->getJumpTables();
758   const std::vector<MachineBasicBlock*> &JTBBs = JTE[JTI].MBBs;
759   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
760     MachineBasicBlock *MBB = JTBBs[i];
761     MBB->setHasAddressTaken();
762     // This line is needed to set the hasAddressTaken flag on the BasicBlock
763     // object.
764     BlockAddress::get(const_cast<BasicBlock *>(MBB->getBasicBlock()));
765   }
766
767   SDValue JumpTableBase = DAG.getNode(HexagonISD::WrapperJT, dl,
768                                       getPointerTy(), TargetJT);
769   SDValue ShiftIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
770                                    DAG.getConstant(2, MVT::i32));
771   SDValue JTAddress = DAG.getNode(ISD::ADD, dl, MVT::i32, JumpTableBase,
772                                   ShiftIndex);
773   SDValue LoadTarget = DAG.getLoad(MVT::i32, dl, Chain, JTAddress,
774                                    MachinePointerInfo(), false, false, false,
775                                    0);
776   return DAG.getNode(HexagonISD::BR_JT, dl, MVT::Other, Chain, LoadTarget);
777 }
778
779
780 SDValue
781 HexagonTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
782                                                SelectionDAG &DAG) const {
783   SDValue Chain = Op.getOperand(0);
784   SDValue Size = Op.getOperand(1);
785   SDLoc dl(Op);
786
787   unsigned SPReg = getStackPointerRegisterToSaveRestore();
788
789   // Get a reference to the stack pointer.
790   SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
791
792   // Subtract the dynamic size from the actual stack size to
793   // obtain the new stack size.
794   SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
795
796   //
797   // For Hexagon, the outgoing memory arguments area should be on top of the
798   // alloca area on the stack i.e., the outgoing memory arguments should be
799   // at a lower address than the alloca area. Move the alloca area down the
800   // stack by adding back the space reserved for outgoing arguments to SP
801   // here.
802   //
803   // We do not know what the size of the outgoing args is at this point.
804   // So, we add a pseudo instruction ADJDYNALLOC that will adjust the
805   // stack pointer. We patch this instruction with the correct, known
806   // offset in emitPrologue().
807   //
808   // Use a placeholder immediate (zero) for now. This will be patched up
809   // by emitPrologue().
810   SDValue ArgAdjust = DAG.getNode(HexagonISD::ADJDYNALLOC, dl,
811                                   MVT::i32,
812                                   Sub,
813                                   DAG.getConstant(0, MVT::i32));
814
815   // The Sub result contains the new stack start address, so it
816   // must be placed in the stack pointer register.
817   SDValue CopyChain = DAG.getCopyToReg(Chain, dl,
818                                        TM.getRegisterInfo()->getStackRegister(),
819                                        Sub);
820
821   SDValue Ops[2] = { ArgAdjust, CopyChain };
822   return DAG.getMergeValues(Ops, 2, dl);
823 }
824
825 SDValue
826 HexagonTargetLowering::LowerFormalArguments(SDValue Chain,
827                                             CallingConv::ID CallConv,
828                                             bool isVarArg,
829                                             const
830                                             SmallVectorImpl<ISD::InputArg> &Ins,
831                                             SDLoc dl, SelectionDAG &DAG,
832                                             SmallVectorImpl<SDValue> &InVals)
833 const {
834
835   MachineFunction &MF = DAG.getMachineFunction();
836   MachineFrameInfo *MFI = MF.getFrameInfo();
837   MachineRegisterInfo &RegInfo = MF.getRegInfo();
838   HexagonMachineFunctionInfo *FuncInfo =
839     MF.getInfo<HexagonMachineFunctionInfo>();
840
841
842   // Assign locations to all of the incoming arguments.
843   SmallVector<CCValAssign, 16> ArgLocs;
844   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
845                  getTargetMachine(), ArgLocs, *DAG.getContext());
846
847   CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon);
848
849   // For LLVM, in the case when returning a struct by value (>8byte),
850   // the first argument is a pointer that points to the location on caller's
851   // stack where the return value will be stored. For Hexagon, the location on
852   // caller's stack is passed only when the struct size is smaller than (and
853   // equal to) 8 bytes. If not, no address will be passed into callee and
854   // callee return the result direclty through R0/R1.
855
856   SmallVector<SDValue, 4> MemOps;
857
858   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
859     CCValAssign &VA = ArgLocs[i];
860     ISD::ArgFlagsTy Flags = Ins[i].Flags;
861     unsigned ObjSize;
862     unsigned StackLocation;
863     int FI;
864
865     if (   (VA.isRegLoc() && !Flags.isByVal())
866         || (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() > 8)) {
867       // Arguments passed in registers
868       // 1. int, long long, ptr args that get allocated in register.
869       // 2. Large struct that gets an register to put its address in.
870       EVT RegVT = VA.getLocVT();
871       if (RegVT == MVT::i8 || RegVT == MVT::i16 ||
872           RegVT == MVT::i32 || RegVT == MVT::f32) {
873         unsigned VReg =
874           RegInfo.createVirtualRegister(&Hexagon::IntRegsRegClass);
875         RegInfo.addLiveIn(VA.getLocReg(), VReg);
876         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
877       } else if (RegVT == MVT::i64) {
878         unsigned VReg =
879           RegInfo.createVirtualRegister(&Hexagon::DoubleRegsRegClass);
880         RegInfo.addLiveIn(VA.getLocReg(), VReg);
881         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
882       } else {
883         assert (0);
884       }
885     } else if (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() <= 8) {
886       assert (0 && "ByValSize must be bigger than 8 bytes");
887     } else {
888       // Sanity check.
889       assert(VA.isMemLoc());
890
891       if (Flags.isByVal()) {
892         // If it's a byval parameter, then we need to compute the
893         // "real" size, not the size of the pointer.
894         ObjSize = Flags.getByValSize();
895       } else {
896         ObjSize = VA.getLocVT().getStoreSizeInBits() >> 3;
897       }
898
899       StackLocation = HEXAGON_LRFP_SIZE + VA.getLocMemOffset();
900       // Create the frame index object for this incoming parameter...
901       FI = MFI->CreateFixedObject(ObjSize, StackLocation, true);
902
903       // Create the SelectionDAG nodes cordl, responding to a load
904       // from this parameter.
905       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
906
907       if (Flags.isByVal()) {
908         // If it's a pass-by-value aggregate, then do not dereference the stack
909         // location. Instead, we should generate a reference to the stack
910         // location.
911         InVals.push_back(FIN);
912       } else {
913         InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
914                                      MachinePointerInfo(), false, false,
915                                      false, 0));
916       }
917     }
918   }
919
920   if (!MemOps.empty())
921     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &MemOps[0],
922                         MemOps.size());
923
924   if (isVarArg) {
925     // This will point to the next argument passed via stack.
926     int FrameIndex = MFI->CreateFixedObject(Hexagon_PointerSize,
927                                             HEXAGON_LRFP_SIZE +
928                                             CCInfo.getNextStackOffset(),
929                                             true);
930     FuncInfo->setVarArgsFrameIndex(FrameIndex);
931   }
932
933   return Chain;
934 }
935
936 SDValue
937 HexagonTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
938   // VASTART stores the address of the VarArgsFrameIndex slot into the
939   // memory location argument.
940   MachineFunction &MF = DAG.getMachineFunction();
941   HexagonMachineFunctionInfo *QFI = MF.getInfo<HexagonMachineFunctionInfo>();
942   SDValue Addr = DAG.getFrameIndex(QFI->getVarArgsFrameIndex(), MVT::i32);
943   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
944   return DAG.getStore(Op.getOperand(0), SDLoc(Op), Addr,
945                       Op.getOperand(1), MachinePointerInfo(SV), false,
946                       false, 0);
947 }
948
949 SDValue
950 HexagonTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
951   SDValue LHS = Op.getOperand(0);
952   SDValue RHS = Op.getOperand(1);
953   SDValue CC = Op.getOperand(4);
954   SDValue TrueVal = Op.getOperand(2);
955   SDValue FalseVal = Op.getOperand(3);
956   SDLoc dl(Op);
957   SDNode* OpNode = Op.getNode();
958   EVT SVT = OpNode->getValueType(0);
959
960   SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i1, LHS, RHS, CC);
961   return DAG.getNode(ISD::SELECT, dl, SVT, Cond, TrueVal, FalseVal);
962 }
963
964 SDValue
965 HexagonTargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
966   EVT ValTy = Op.getValueType();
967   SDLoc dl(Op);
968   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
969   SDValue Res;
970   if (CP->isMachineConstantPoolEntry())
971     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), ValTy,
972                                     CP->getAlignment());
973   else
974     Res = DAG.getTargetConstantPool(CP->getConstVal(), ValTy,
975                                     CP->getAlignment());
976   return DAG.getNode(HexagonISD::CONST32, dl, ValTy, Res);
977 }
978
979 SDValue
980 HexagonTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
981   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
982   MachineFunction &MF = DAG.getMachineFunction();
983   MachineFrameInfo *MFI = MF.getFrameInfo();
984   MFI->setReturnAddressIsTaken(true);
985
986   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
987     return SDValue();
988
989   EVT VT = Op.getValueType();
990   SDLoc dl(Op);
991   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
992   if (Depth) {
993     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
994     SDValue Offset = DAG.getConstant(4, MVT::i32);
995     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
996                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
997                        MachinePointerInfo(), false, false, false, 0);
998   }
999
1000   // Return LR, which contains the return address. Mark it an implicit live-in.
1001   unsigned Reg = MF.addLiveIn(TRI->getRARegister(), getRegClassFor(MVT::i32));
1002   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
1003 }
1004
1005 SDValue
1006 HexagonTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1007   const HexagonRegisterInfo  *TRI = TM.getRegisterInfo();
1008   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1009   MFI->setFrameAddressIsTaken(true);
1010
1011   EVT VT = Op.getValueType();
1012   SDLoc dl(Op);
1013   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1014   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1015                                          TRI->getFrameRegister(), VT);
1016   while (Depth--)
1017     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1018                             MachinePointerInfo(),
1019                             false, false, false, 0);
1020   return FrameAddr;
1021 }
1022
1023 SDValue HexagonTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1024                                                  SelectionDAG& DAG) const {
1025   SDLoc dl(Op);
1026   return DAG.getNode(HexagonISD::BARRIER, dl, MVT::Other, Op.getOperand(0));
1027 }
1028
1029
1030 SDValue HexagonTargetLowering::LowerGLOBALADDRESS(SDValue Op,
1031                                                   SelectionDAG &DAG) const {
1032   SDValue Result;
1033   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1034   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
1035   SDLoc dl(Op);
1036   Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
1037
1038   const HexagonTargetObjectFile &TLOF =
1039       static_cast<const HexagonTargetObjectFile &>(getObjFileLowering());
1040   if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1041     return DAG.getNode(HexagonISD::CONST32_GP, dl, getPointerTy(), Result);
1042   }
1043
1044   return DAG.getNode(HexagonISD::CONST32, dl, getPointerTy(), Result);
1045 }
1046
1047 SDValue
1048 HexagonTargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1049   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1050   SDValue BA_SD =  DAG.getTargetBlockAddress(BA, MVT::i32);
1051   SDLoc dl(Op);
1052   return DAG.getNode(HexagonISD::CONST32_GP, dl, getPointerTy(), BA_SD);
1053 }
1054
1055 //===----------------------------------------------------------------------===//
1056 // TargetLowering Implementation
1057 //===----------------------------------------------------------------------===//
1058
1059 HexagonTargetLowering::HexagonTargetLowering(HexagonTargetMachine
1060                                              &targetmachine)
1061   : TargetLowering(targetmachine, new HexagonTargetObjectFile()),
1062     TM(targetmachine) {
1063
1064     const HexagonRegisterInfo* QRI = TM.getRegisterInfo();
1065
1066     // Set up the register classes.
1067     addRegisterClass(MVT::i32, &Hexagon::IntRegsRegClass);
1068     addRegisterClass(MVT::i64, &Hexagon::DoubleRegsRegClass);
1069
1070     if (QRI->Subtarget.hasV5TOps()) {
1071       addRegisterClass(MVT::f32, &Hexagon::IntRegsRegClass);
1072       addRegisterClass(MVT::f64, &Hexagon::DoubleRegsRegClass);
1073     }
1074
1075     addRegisterClass(MVT::i1, &Hexagon::PredRegsRegClass);
1076
1077     computeRegisterProperties();
1078
1079     // Align loop entry
1080     setPrefLoopAlignment(4);
1081
1082     // Limits for inline expansion of memcpy/memmove
1083     MaxStoresPerMemcpy = 6;
1084     MaxStoresPerMemmove = 6;
1085
1086     //
1087     // Library calls for unsupported operations
1088     //
1089
1090     setLibcallName(RTLIB::SINTTOFP_I128_F64, "__hexagon_floattidf");
1091     setLibcallName(RTLIB::SINTTOFP_I128_F32, "__hexagon_floattisf");
1092
1093     setLibcallName(RTLIB::FPTOUINT_F32_I128, "__hexagon_fixunssfti");
1094     setLibcallName(RTLIB::FPTOUINT_F64_I128, "__hexagon_fixunsdfti");
1095
1096     setLibcallName(RTLIB::FPTOSINT_F32_I128, "__hexagon_fixsfti");
1097     setLibcallName(RTLIB::FPTOSINT_F64_I128, "__hexagon_fixdfti");
1098
1099     setLibcallName(RTLIB::SDIV_I32, "__hexagon_divsi3");
1100     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
1101     setLibcallName(RTLIB::SREM_I32, "__hexagon_umodsi3");
1102     setOperationAction(ISD::SREM,  MVT::i32, Expand);
1103
1104     setLibcallName(RTLIB::SDIV_I64, "__hexagon_divdi3");
1105     setOperationAction(ISD::SDIV,  MVT::i64, Expand);
1106     setLibcallName(RTLIB::SREM_I64, "__hexagon_moddi3");
1107     setOperationAction(ISD::SREM,  MVT::i64, Expand);
1108
1109     setLibcallName(RTLIB::UDIV_I32, "__hexagon_udivsi3");
1110     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
1111
1112     setLibcallName(RTLIB::UDIV_I64, "__hexagon_udivdi3");
1113     setOperationAction(ISD::UDIV,  MVT::i64, Expand);
1114
1115     setLibcallName(RTLIB::UREM_I32, "__hexagon_umodsi3");
1116     setOperationAction(ISD::UREM,  MVT::i32, Expand);
1117
1118     setLibcallName(RTLIB::UREM_I64, "__hexagon_umoddi3");
1119     setOperationAction(ISD::UREM,  MVT::i64, Expand);
1120
1121     setLibcallName(RTLIB::DIV_F32, "__hexagon_divsf3");
1122     setOperationAction(ISD::FDIV,  MVT::f32, Expand);
1123
1124     setLibcallName(RTLIB::DIV_F64, "__hexagon_divdf3");
1125     setOperationAction(ISD::FDIV,  MVT::f64, Expand);
1126
1127     setOperationAction(ISD::FSQRT,  MVT::f32, Expand);
1128     setOperationAction(ISD::FSQRT,  MVT::f64, Expand);
1129     setOperationAction(ISD::FSIN,  MVT::f32, Expand);
1130     setOperationAction(ISD::FSIN,  MVT::f64, Expand);
1131
1132     if (QRI->Subtarget.hasV5TOps()) {
1133       // Hexagon V5 Support.
1134       setOperationAction(ISD::FADD,       MVT::f32, Legal);
1135       setOperationAction(ISD::FADD,       MVT::f64, Legal);
1136       setOperationAction(ISD::FP_EXTEND,  MVT::f32, Legal);
1137       setCondCodeAction(ISD::SETOEQ,      MVT::f32, Legal);
1138       setCondCodeAction(ISD::SETOEQ,      MVT::f64, Legal);
1139       setCondCodeAction(ISD::SETUEQ,      MVT::f32, Legal);
1140       setCondCodeAction(ISD::SETUEQ,      MVT::f64, Legal);
1141
1142       setCondCodeAction(ISD::SETOGE,      MVT::f32, Legal);
1143       setCondCodeAction(ISD::SETOGE,      MVT::f64, Legal);
1144       setCondCodeAction(ISD::SETUGE,      MVT::f32, Legal);
1145       setCondCodeAction(ISD::SETUGE,      MVT::f64, Legal);
1146
1147       setCondCodeAction(ISD::SETOGT,      MVT::f32, Legal);
1148       setCondCodeAction(ISD::SETOGT,      MVT::f64, Legal);
1149       setCondCodeAction(ISD::SETUGT,      MVT::f32, Legal);
1150       setCondCodeAction(ISD::SETUGT,      MVT::f64, Legal);
1151
1152       setCondCodeAction(ISD::SETOLE,      MVT::f32, Legal);
1153       setCondCodeAction(ISD::SETOLE,      MVT::f64, Legal);
1154       setCondCodeAction(ISD::SETOLT,      MVT::f32, Legal);
1155       setCondCodeAction(ISD::SETOLT,      MVT::f64, Legal);
1156
1157       setOperationAction(ISD::ConstantFP,  MVT::f32, Legal);
1158       setOperationAction(ISD::ConstantFP,  MVT::f64, Legal);
1159
1160       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
1161       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
1162       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
1163       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
1164
1165       setOperationAction(ISD::FP_TO_UINT, MVT::i8, Promote);
1166       setOperationAction(ISD::FP_TO_SINT, MVT::i8, Promote);
1167       setOperationAction(ISD::UINT_TO_FP, MVT::i8, Promote);
1168       setOperationAction(ISD::SINT_TO_FP, MVT::i8, Promote);
1169
1170       setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
1171       setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
1172       setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
1173       setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
1174
1175       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1176       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1177       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1178       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1179
1180       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1181       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1182       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1183       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1184
1185       setOperationAction(ISD::FABS,  MVT::f32, Legal);
1186       setOperationAction(ISD::FABS,  MVT::f64, Expand);
1187
1188       setOperationAction(ISD::FNEG,  MVT::f32, Legal);
1189       setOperationAction(ISD::FNEG,  MVT::f64, Expand);
1190     } else {
1191
1192       // Expand fp<->uint.
1193       setOperationAction(ISD::FP_TO_SINT,  MVT::i32, Expand);
1194       setOperationAction(ISD::FP_TO_UINT,  MVT::i32, Expand);
1195
1196       setOperationAction(ISD::SINT_TO_FP,  MVT::i32, Expand);
1197       setOperationAction(ISD::UINT_TO_FP,  MVT::i32, Expand);
1198
1199       setLibcallName(RTLIB::SINTTOFP_I64_F32, "__hexagon_floatdisf");
1200       setLibcallName(RTLIB::UINTTOFP_I64_F32, "__hexagon_floatundisf");
1201
1202       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__hexagon_floatunsisf");
1203       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__hexagon_floatsisf");
1204
1205       setLibcallName(RTLIB::SINTTOFP_I64_F64, "__hexagon_floatdidf");
1206       setLibcallName(RTLIB::UINTTOFP_I64_F64, "__hexagon_floatundidf");
1207
1208       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__hexagon_floatunsidf");
1209       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__hexagon_floatsidf");
1210
1211       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__hexagon_fixunssfsi");
1212       setLibcallName(RTLIB::FPTOUINT_F32_I64, "__hexagon_fixunssfdi");
1213
1214       setLibcallName(RTLIB::FPTOSINT_F64_I64, "__hexagon_fixdfdi");
1215       setLibcallName(RTLIB::FPTOSINT_F32_I64, "__hexagon_fixsfdi");
1216
1217       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__hexagon_fixunsdfsi");
1218       setLibcallName(RTLIB::FPTOUINT_F64_I64, "__hexagon_fixunsdfdi");
1219
1220       setLibcallName(RTLIB::ADD_F64, "__hexagon_adddf3");
1221       setOperationAction(ISD::FADD,  MVT::f64, Expand);
1222
1223       setLibcallName(RTLIB::ADD_F32, "__hexagon_addsf3");
1224       setOperationAction(ISD::FADD,  MVT::f32, Expand);
1225
1226       setLibcallName(RTLIB::FPEXT_F32_F64, "__hexagon_extendsfdf2");
1227       setOperationAction(ISD::FP_EXTEND,  MVT::f32, Expand);
1228
1229       setLibcallName(RTLIB::OEQ_F32, "__hexagon_eqsf2");
1230       setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
1231
1232       setLibcallName(RTLIB::OEQ_F64, "__hexagon_eqdf2");
1233       setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
1234
1235       setLibcallName(RTLIB::OGE_F32, "__hexagon_gesf2");
1236       setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
1237
1238       setLibcallName(RTLIB::OGE_F64, "__hexagon_gedf2");
1239       setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
1240
1241       setLibcallName(RTLIB::OGT_F32, "__hexagon_gtsf2");
1242       setCondCodeAction(ISD::SETOGT, MVT::f32, Expand);
1243
1244       setLibcallName(RTLIB::OGT_F64, "__hexagon_gtdf2");
1245       setCondCodeAction(ISD::SETOGT, MVT::f64, Expand);
1246
1247       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__hexagon_fixdfsi");
1248       setOperationAction(ISD::FP_TO_SINT, MVT::f64, Expand);
1249
1250       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__hexagon_fixsfsi");
1251       setOperationAction(ISD::FP_TO_SINT, MVT::f32, Expand);
1252
1253       setLibcallName(RTLIB::OLE_F64, "__hexagon_ledf2");
1254       setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
1255
1256       setLibcallName(RTLIB::OLE_F32, "__hexagon_lesf2");
1257       setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
1258
1259       setLibcallName(RTLIB::OLT_F64, "__hexagon_ltdf2");
1260       setCondCodeAction(ISD::SETOLT, MVT::f64, Expand);
1261
1262       setLibcallName(RTLIB::OLT_F32, "__hexagon_ltsf2");
1263       setCondCodeAction(ISD::SETOLT, MVT::f32, Expand);
1264
1265       setLibcallName(RTLIB::MUL_F64, "__hexagon_muldf3");
1266       setOperationAction(ISD::FMUL, MVT::f64, Expand);
1267
1268       setLibcallName(RTLIB::MUL_F32, "__hexagon_mulsf3");
1269       setOperationAction(ISD::MUL, MVT::f32, Expand);
1270
1271       setLibcallName(RTLIB::UNE_F64, "__hexagon_nedf2");
1272       setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
1273
1274       setLibcallName(RTLIB::UNE_F32, "__hexagon_nesf2");
1275
1276       setLibcallName(RTLIB::SUB_F64, "__hexagon_subdf3");
1277       setOperationAction(ISD::SUB, MVT::f64, Expand);
1278
1279       setLibcallName(RTLIB::SUB_F32, "__hexagon_subsf3");
1280       setOperationAction(ISD::SUB, MVT::f32, Expand);
1281
1282       setLibcallName(RTLIB::FPROUND_F64_F32, "__hexagon_truncdfsf2");
1283       setOperationAction(ISD::FP_ROUND, MVT::f64, Expand);
1284
1285       setLibcallName(RTLIB::UO_F64, "__hexagon_unorddf2");
1286       setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
1287
1288       setLibcallName(RTLIB::O_F64, "__hexagon_unorddf2");
1289       setCondCodeAction(ISD::SETO, MVT::f64, Expand);
1290
1291       setLibcallName(RTLIB::O_F32, "__hexagon_unordsf2");
1292       setCondCodeAction(ISD::SETO, MVT::f32, Expand);
1293
1294       setLibcallName(RTLIB::UO_F32, "__hexagon_unordsf2");
1295       setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
1296
1297       setOperationAction(ISD::FABS,  MVT::f32, Expand);
1298       setOperationAction(ISD::FABS,  MVT::f64, Expand);
1299       setOperationAction(ISD::FNEG,  MVT::f32, Expand);
1300       setOperationAction(ISD::FNEG,  MVT::f64, Expand);
1301     }
1302
1303     setLibcallName(RTLIB::SREM_I32, "__hexagon_modsi3");
1304     setOperationAction(ISD::SREM, MVT::i32, Expand);
1305
1306     setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
1307     setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
1308     setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
1309     setIndexedLoadAction(ISD::POST_INC, MVT::i64, Legal);
1310
1311     setIndexedStoreAction(ISD::POST_INC, MVT::i8, Legal);
1312     setIndexedStoreAction(ISD::POST_INC, MVT::i16, Legal);
1313     setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1314     setIndexedStoreAction(ISD::POST_INC, MVT::i64, Legal);
1315
1316     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
1317
1318     // Turn FP extload into load/fextend.
1319     setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
1320     // Hexagon has a i1 sign extending load.
1321     setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
1322     // Turn FP truncstore into trunc + store.
1323     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1324
1325     // Custom legalize GlobalAddress nodes into CONST32.
1326     setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1327     setOperationAction(ISD::GlobalAddress, MVT::i8, Custom);
1328     setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1329     // Truncate action?
1330     setOperationAction(ISD::TRUNCATE, MVT::i64, Expand);
1331
1332     // Hexagon doesn't have sext_inreg, replace them with shl/sra.
1333     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
1334
1335     // Hexagon has no REM or DIVREM operations.
1336     setOperationAction(ISD::UREM, MVT::i32, Expand);
1337     setOperationAction(ISD::SREM, MVT::i32, Expand);
1338     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1339     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1340     setOperationAction(ISD::SREM, MVT::i64, Expand);
1341     setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
1342     setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
1343
1344     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
1345
1346     // Lower SELECT_CC to SETCC and SELECT.
1347     setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
1348     setOperationAction(ISD::SELECT_CC, MVT::i64,   Custom);
1349
1350     if (QRI->Subtarget.hasV5TOps()) {
1351
1352       // We need to make the operation type of SELECT node to be Custom,
1353       // such that we don't go into the infinite loop of
1354       // select ->  setcc -> select_cc -> select loop.
1355       setOperationAction(ISD::SELECT, MVT::f32, Custom);
1356       setOperationAction(ISD::SELECT, MVT::f64, Custom);
1357
1358       setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
1359       setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
1360       setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
1361
1362     } else {
1363
1364       // Hexagon has no select or setcc: expand to SELECT_CC.
1365       setOperationAction(ISD::SELECT, MVT::f32, Expand);
1366       setOperationAction(ISD::SELECT, MVT::f64, Expand);
1367
1368       // This is a workaround documented in DAGCombiner.cpp:2892 We don't
1369       // support SELECT_CC on every type.
1370       setOperationAction(ISD::SELECT_CC, MVT::Other,   Expand);
1371
1372     }
1373
1374     if (EmitJumpTables) {
1375       setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1376     } else {
1377       setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1378     }
1379     // Increase jump tables cutover to 5, was 4.
1380     setMinimumJumpTableEntries(5);
1381
1382     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
1383     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
1384     setOperationAction(ISD::BR_CC, MVT::i1,  Expand);
1385     setOperationAction(ISD::BR_CC, MVT::i32, Expand);
1386     setOperationAction(ISD::BR_CC, MVT::i64, Expand);
1387
1388     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1389
1390     setOperationAction(ISD::FSIN , MVT::f64, Expand);
1391     setOperationAction(ISD::FCOS , MVT::f64, Expand);
1392     setOperationAction(ISD::FREM , MVT::f64, Expand);
1393     setOperationAction(ISD::FSIN , MVT::f32, Expand);
1394     setOperationAction(ISD::FCOS , MVT::f32, Expand);
1395     setOperationAction(ISD::FREM , MVT::f32, Expand);
1396     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1397     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1398
1399     // In V4, we have double word add/sub with carry. The problem with
1400     // modelling this instruction is that it produces 2 results - Rdd and Px.
1401     // To model update of Px, we will have to use Defs[p0..p3] which will
1402     // cause any predicate live range to spill. So, we pretend we dont't
1403     // have these instructions.
1404     setOperationAction(ISD::ADDE, MVT::i8, Expand);
1405     setOperationAction(ISD::ADDE, MVT::i16, Expand);
1406     setOperationAction(ISD::ADDE, MVT::i32, Expand);
1407     setOperationAction(ISD::ADDE, MVT::i64, Expand);
1408     setOperationAction(ISD::SUBE, MVT::i8, Expand);
1409     setOperationAction(ISD::SUBE, MVT::i16, Expand);
1410     setOperationAction(ISD::SUBE, MVT::i32, Expand);
1411     setOperationAction(ISD::SUBE, MVT::i64, Expand);
1412     setOperationAction(ISD::ADDC, MVT::i8, Expand);
1413     setOperationAction(ISD::ADDC, MVT::i16, Expand);
1414     setOperationAction(ISD::ADDC, MVT::i32, Expand);
1415     setOperationAction(ISD::ADDC, MVT::i64, Expand);
1416     setOperationAction(ISD::SUBC, MVT::i8, Expand);
1417     setOperationAction(ISD::SUBC, MVT::i16, Expand);
1418     setOperationAction(ISD::SUBC, MVT::i32, Expand);
1419     setOperationAction(ISD::SUBC, MVT::i64, Expand);
1420
1421     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1422     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
1423     setOperationAction(ISD::CTTZ , MVT::i32, Expand);
1424     setOperationAction(ISD::CTTZ , MVT::i64, Expand);
1425     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
1426     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
1427     setOperationAction(ISD::CTLZ , MVT::i32, Expand);
1428     setOperationAction(ISD::CTLZ , MVT::i64, Expand);
1429     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
1430     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
1431     setOperationAction(ISD::ROTL , MVT::i32, Expand);
1432     setOperationAction(ISD::ROTR , MVT::i32, Expand);
1433     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1434     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1435     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
1436     setOperationAction(ISD::FPOW , MVT::f64, Expand);
1437     setOperationAction(ISD::FPOW , MVT::f32, Expand);
1438
1439     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1440     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1441     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1442
1443     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1444     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1445
1446     setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
1447     setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
1448
1449     setOperationAction(ISD::EH_RETURN,     MVT::Other, Custom);
1450
1451     if (TM.getSubtargetImpl()->isSubtargetV2()) {
1452       setExceptionPointerRegister(Hexagon::R20);
1453       setExceptionSelectorRegister(Hexagon::R21);
1454     } else {
1455       setExceptionPointerRegister(Hexagon::R0);
1456       setExceptionSelectorRegister(Hexagon::R1);
1457     }
1458
1459     // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1460     setOperationAction(ISD::VASTART           , MVT::Other, Custom);
1461
1462     // Use the default implementation.
1463     setOperationAction(ISD::VAARG             , MVT::Other, Expand);
1464     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
1465     setOperationAction(ISD::VAEND             , MVT::Other, Expand);
1466     setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
1467     setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
1468
1469
1470     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
1471     setOperationAction(ISD::INLINEASM         , MVT::Other, Custom);
1472
1473     setMinFunctionAlignment(2);
1474
1475     // Needed for DYNAMIC_STACKALLOC expansion.
1476     unsigned StackRegister = TM.getRegisterInfo()->getStackRegister();
1477     setStackPointerRegisterToSaveRestore(StackRegister);
1478     setSchedulingPreference(Sched::VLIW);
1479 }
1480
1481
1482 const char*
1483 HexagonTargetLowering::getTargetNodeName(unsigned Opcode) const {
1484   switch (Opcode) {
1485     default: return nullptr;
1486     case HexagonISD::CONST32:     return "HexagonISD::CONST32";
1487     case HexagonISD::CONST32_GP: return "HexagonISD::CONST32_GP";
1488     case HexagonISD::CONST32_Int_Real: return "HexagonISD::CONST32_Int_Real";
1489     case HexagonISD::ADJDYNALLOC: return "HexagonISD::ADJDYNALLOC";
1490     case HexagonISD::CMPICC:      return "HexagonISD::CMPICC";
1491     case HexagonISD::CMPFCC:      return "HexagonISD::CMPFCC";
1492     case HexagonISD::BRICC:       return "HexagonISD::BRICC";
1493     case HexagonISD::BRFCC:       return "HexagonISD::BRFCC";
1494     case HexagonISD::SELECT_ICC:  return "HexagonISD::SELECT_ICC";
1495     case HexagonISD::SELECT_FCC:  return "HexagonISD::SELECT_FCC";
1496     case HexagonISD::Hi:          return "HexagonISD::Hi";
1497     case HexagonISD::Lo:          return "HexagonISD::Lo";
1498     case HexagonISD::FTOI:        return "HexagonISD::FTOI";
1499     case HexagonISD::ITOF:        return "HexagonISD::ITOF";
1500     case HexagonISD::CALL:        return "HexagonISD::CALL";
1501     case HexagonISD::RET_FLAG:    return "HexagonISD::RET_FLAG";
1502     case HexagonISD::BR_JT:       return "HexagonISD::BR_JT";
1503     case HexagonISD::TC_RETURN:   return "HexagonISD::TC_RETURN";
1504   case HexagonISD::EH_RETURN: return "HexagonISD::EH_RETURN";
1505   }
1506 }
1507
1508 bool
1509 HexagonTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
1510   EVT MTy1 = EVT::getEVT(Ty1);
1511   EVT MTy2 = EVT::getEVT(Ty2);
1512   if (!MTy1.isSimple() || !MTy2.isSimple()) {
1513     return false;
1514   }
1515   return ((MTy1.getSimpleVT() == MVT::i64) && (MTy2.getSimpleVT() == MVT::i32));
1516 }
1517
1518 bool HexagonTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1519   if (!VT1.isSimple() || !VT2.isSimple()) {
1520     return false;
1521   }
1522   return ((VT1.getSimpleVT() == MVT::i64) && (VT2.getSimpleVT() == MVT::i32));
1523 }
1524
1525 bool
1526 HexagonTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
1527   // Assuming the caller does not have either a signext or zeroext modifier, and
1528   // only one value is accepted, any reasonable truncation is allowed.
1529   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
1530     return false;
1531
1532   // FIXME: in principle up to 64-bit could be made safe, but it would be very
1533   // fragile at the moment: any support for multiple value returns would be
1534   // liable to disallow tail calls involving i64 -> iN truncation in many cases.
1535   return Ty1->getPrimitiveSizeInBits() <= 32;
1536 }
1537
1538 SDValue
1539 HexagonTargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
1540   SDValue Chain     = Op.getOperand(0);
1541   SDValue Offset    = Op.getOperand(1);
1542   SDValue Handler   = Op.getOperand(2);
1543   SDLoc dl(Op);
1544
1545   // Mark function as containing a call to EH_RETURN.
1546   HexagonMachineFunctionInfo *FuncInfo =
1547     DAG.getMachineFunction().getInfo<HexagonMachineFunctionInfo>();
1548   FuncInfo->setHasEHReturn();
1549
1550   unsigned OffsetReg = Hexagon::R28;
1551
1552   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(),
1553                                   DAG.getRegister(Hexagon::R30, getPointerTy()),
1554                                   DAG.getIntPtrConstant(4));
1555   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
1556                        false, false, 0);
1557   Chain = DAG.getCopyToReg(Chain, dl, OffsetReg, Offset);
1558
1559   // Not needed we already use it as explict input to EH_RETURN.
1560   // MF.getRegInfo().addLiveOut(OffsetReg);
1561
1562   return DAG.getNode(HexagonISD::EH_RETURN, dl, MVT::Other, Chain);
1563 }
1564
1565 SDValue
1566 HexagonTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1567   switch (Op.getOpcode()) {
1568     default: llvm_unreachable("Should not custom lower this!");
1569     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1570     case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
1571       // Frame & Return address.  Currently unimplemented.
1572     case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
1573     case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
1574     case ISD::GlobalTLSAddress:
1575                           llvm_unreachable("TLS not implemented for Hexagon.");
1576     case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
1577     case ISD::GlobalAddress:      return LowerGLOBALADDRESS(Op, DAG);
1578     case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
1579     case ISD::VASTART:            return LowerVASTART(Op, DAG);
1580     case ISD::BR_JT:              return LowerBR_JT(Op, DAG);
1581
1582     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1583     case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
1584     case ISD::SELECT:             return Op;
1585     case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1586     case ISD::INLINEASM:          return LowerINLINEASM(Op, DAG);
1587
1588   }
1589 }
1590
1591
1592
1593 //===----------------------------------------------------------------------===//
1594 //                           Hexagon Scheduler Hooks
1595 //===----------------------------------------------------------------------===//
1596 MachineBasicBlock *
1597 HexagonTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1598                                                    MachineBasicBlock *BB)
1599 const {
1600   switch (MI->getOpcode()) {
1601     case Hexagon::ADJDYNALLOC: {
1602       MachineFunction *MF = BB->getParent();
1603       HexagonMachineFunctionInfo *FuncInfo =
1604         MF->getInfo<HexagonMachineFunctionInfo>();
1605       FuncInfo->addAllocaAdjustInst(MI);
1606       return BB;
1607     }
1608     default: llvm_unreachable("Unexpected instr type to insert");
1609   } // switch
1610 }
1611
1612 //===----------------------------------------------------------------------===//
1613 // Inline Assembly Support
1614 //===----------------------------------------------------------------------===//
1615
1616 std::pair<unsigned, const TargetRegisterClass*>
1617 HexagonTargetLowering::getRegForInlineAsmConstraint(const
1618                                                     std::string &Constraint,
1619                                                     MVT VT) const {
1620   if (Constraint.size() == 1) {
1621     switch (Constraint[0]) {
1622     case 'r':   // R0-R31
1623        switch (VT.SimpleTy) {
1624        default:
1625          llvm_unreachable("getRegForInlineAsmConstraint Unhandled data type");
1626        case MVT::i32:
1627        case MVT::i16:
1628        case MVT::i8:
1629        case MVT::f32:
1630          return std::make_pair(0U, &Hexagon::IntRegsRegClass);
1631        case MVT::i64:
1632        case MVT::f64:
1633          return std::make_pair(0U, &Hexagon::DoubleRegsRegClass);
1634       }
1635     default:
1636       llvm_unreachable("Unknown asm register class");
1637     }
1638   }
1639
1640   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1641 }
1642
1643 /// isFPImmLegal - Returns true if the target can instruction select the
1644 /// specified FP immediate natively. If false, the legalizer will
1645 /// materialize the FP immediate as a load from a constant pool.
1646 bool HexagonTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1647   const HexagonRegisterInfo* QRI = TM.getRegisterInfo();
1648   return QRI->Subtarget.hasV5TOps();
1649 }
1650
1651 /// isLegalAddressingMode - Return true if the addressing mode represented by
1652 /// AM is legal for this target, for a load/store of the specified type.
1653 bool HexagonTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1654                                                   Type *Ty) const {
1655   // Allows a signed-extended 11-bit immediate field.
1656   if (AM.BaseOffs <= -(1LL << 13) || AM.BaseOffs >= (1LL << 13)-1) {
1657     return false;
1658   }
1659
1660   // No global is ever allowed as a base.
1661   if (AM.BaseGV) {
1662     return false;
1663   }
1664
1665   int Scale = AM.Scale;
1666   if (Scale < 0) Scale = -Scale;
1667   switch (Scale) {
1668   case 0:  // No scale reg, "r+i", "r", or just "i".
1669     break;
1670   default: // No scaled addressing mode.
1671     return false;
1672   }
1673   return true;
1674 }
1675
1676 /// isLegalICmpImmediate - Return true if the specified immediate is legal
1677 /// icmp immediate, that is the target has icmp instructions which can compare
1678 /// a register against the immediate without having to materialize the
1679 /// immediate into a register.
1680 bool HexagonTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1681   return Imm >= -512 && Imm <= 511;
1682 }
1683
1684 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1685 /// for tail call optimization. Targets which want to do tail call
1686 /// optimization should implement this function.
1687 bool HexagonTargetLowering::IsEligibleForTailCallOptimization(
1688                                  SDValue Callee,
1689                                  CallingConv::ID CalleeCC,
1690                                  bool isVarArg,
1691                                  bool isCalleeStructRet,
1692                                  bool isCallerStructRet,
1693                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1694                                  const SmallVectorImpl<SDValue> &OutVals,
1695                                  const SmallVectorImpl<ISD::InputArg> &Ins,
1696                                  SelectionDAG& DAG) const {
1697   const Function *CallerF = DAG.getMachineFunction().getFunction();
1698   CallingConv::ID CallerCC = CallerF->getCallingConv();
1699   bool CCMatch = CallerCC == CalleeCC;
1700
1701   // ***************************************************************************
1702   //  Look for obvious safe cases to perform tail call optimization that do not
1703   //  require ABI changes.
1704   // ***************************************************************************
1705
1706   // If this is a tail call via a function pointer, then don't do it!
1707   if (!(dyn_cast<GlobalAddressSDNode>(Callee))
1708       && !(dyn_cast<ExternalSymbolSDNode>(Callee))) {
1709     return false;
1710   }
1711
1712   // Do not optimize if the calling conventions do not match.
1713   if (!CCMatch)
1714     return false;
1715
1716   // Do not tail call optimize vararg calls.
1717   if (isVarArg)
1718     return false;
1719
1720   // Also avoid tail call optimization if either caller or callee uses struct
1721   // return semantics.
1722   if (isCalleeStructRet || isCallerStructRet)
1723     return false;
1724
1725   // In addition to the cases above, we also disable Tail Call Optimization if
1726   // the calling convention code that at least one outgoing argument needs to
1727   // go on the stack. We cannot check that here because at this point that
1728   // information is not available.
1729   return true;
1730 }