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