blob: 009c590cad48db87da9cd349c81958b2317514be [file] [log] [blame]
Dan Gohman2048b852009-11-23 18:04:58 +00001//===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002//
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 implements routines for translating from LLVM IR into SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Dan Gohman2048b852009-11-23 18:04:58 +000015#include "SelectionDAGBuilder.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "SDNodeDbgValue.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000017#include "llvm/ADT/BitVector.h"
David Blaikie6d9dbd52013-06-16 20:34:15 +000018#include "llvm/ADT/Optional.h"
Dan Gohman5b229802008-09-04 20:49:27 +000019#include "llvm/ADT/SmallSet.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000020#include "llvm/Analysis/AliasAnalysis.h"
Jakub Staszak81bfd712013-01-10 22:13:13 +000021#include "llvm/Analysis/BranchProbabilityInfo.h"
Chris Lattner8047d9a2009-12-24 00:37:38 +000022#include "llvm/Analysis/ConstantFolding.h"
Nadav Rotemc05d3062012-09-06 09:17:37 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000024#include "llvm/CodeGen/Analysis.h"
25#include "llvm/CodeGen/FastISel.h"
26#include "llvm/CodeGen/FunctionLoweringInfo.h"
27#include "llvm/CodeGen/GCMetadata.h"
28#include "llvm/CodeGen/GCStrategy.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
32#include "llvm/CodeGen/MachineJumpTableInfo.h"
33#include "llvm/CodeGen/MachineModuleInfo.h"
34#include "llvm/CodeGen/MachineRegisterInfo.h"
35#include "llvm/CodeGen/SelectionDAG.h"
Andrew Trick3d74dea2013-10-31 22:11:56 +000036#include "llvm/CodeGen/StackMaps.h"
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000037#include "llvm/DebugInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000038#include "llvm/IR/CallingConv.h"
39#include "llvm/IR/Constants.h"
40#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/DerivedTypes.h"
42#include "llvm/IR/Function.h"
43#include "llvm/IR/GlobalVariable.h"
44#include "llvm/IR/InlineAsm.h"
45#include "llvm/IR/Instructions.h"
46#include "llvm/IR/IntrinsicInst.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/IR/LLVMContext.h"
49#include "llvm/IR/Module.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000050#include "llvm/Support/CommandLine.h"
51#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000053#include "llvm/Support/MathExtras.h"
54#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000055#include "llvm/Target/TargetFrameLowering.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000056#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesen49de9822009-02-05 01:49:45 +000057#include "llvm/Target/TargetIntrinsicInfo.h"
Owen Anderson243eb9e2011-12-08 22:15:21 +000058#include "llvm/Target/TargetLibraryInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000059#include "llvm/Target/TargetLowering.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000060#include "llvm/Target/TargetOptions.h"
Richard Sandifordac168b82013-08-12 10:28:10 +000061#include "llvm/Target/TargetSelectionDAGInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000062#include <algorithm>
63using namespace llvm;
64
Dale Johannesen601d3c02008-09-05 01:48:15 +000065/// LimitFloatPrecision - Generate low-precision inline sequences for
66/// some float libcalls (6, 8 or 12 bits).
67static unsigned LimitFloatPrecision;
68
69static cl::opt<unsigned, true>
70LimitFPPrecision("limit-float-precision",
71 cl::desc("Generate low-precision inline sequences "
72 "for some float libcalls"),
73 cl::location(LimitFloatPrecision),
74 cl::init(0));
75
Andrew Trickde91f3c2010-11-12 17:50:46 +000076// Limit the width of DAG chains. This is important in general to prevent
77// prevent DAG-based analysis from blowing up. For example, alias analysis and
78// load clustering may not complete in reasonable time. It is difficult to
79// recognize and avoid this situation within each individual analysis, and
80// future analyses are likely to have the same behavior. Limiting DAG width is
Andrew Trickb9e6fe12010-11-20 07:26:51 +000081// the safe approach, and will be especially important with global DAGs.
Andrew Trickde91f3c2010-11-12 17:50:46 +000082//
83// MaxParallelChains default is arbitrarily high to avoid affecting
84// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
Andrew Trickb9e6fe12010-11-20 07:26:51 +000085// sequence over this should have been converted to llvm.memcpy by the
86// frontend. It easy to induce this behavior with .ll code such as:
87// %buffer = alloca [4096 x i8]
88// %data = load [4096 x i8]* %argPtr
89// store [4096 x i8] %data, [4096 x i8]* %buffer
Andrew Trick778583a2011-03-11 17:46:59 +000090static const unsigned MaxParallelChains = 64;
Andrew Trickde91f3c2010-11-12 17:50:46 +000091
Andrew Trickac6d9be2013-05-25 02:42:55 +000092static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner3ac18842010-08-24 23:20:40 +000093 const SDValue *Parts, unsigned NumParts,
Patrik Hagglundb9e12e52012-12-19 12:33:30 +000094 MVT PartVT, EVT ValueVT, const Value *V);
Michael J. Spencere70c5262010-10-16 08:25:21 +000095
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000096/// getCopyFromParts - Create a value that contains the specified legal parts
97/// combined into the value they represent. If the parts combine to a type
98/// larger then ValueVT then AssertOp can be used to specify whether the extra
99/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
100/// (ISD::AssertSext).
Andrew Trickac6d9be2013-05-25 02:42:55 +0000101static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000102 const SDValue *Parts,
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000103 unsigned NumParts, MVT PartVT, EVT ValueVT,
Bill Wendling12931302012-09-26 04:04:19 +0000104 const Value *V,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000105 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Chris Lattner3ac18842010-08-24 23:20:40 +0000106 if (ValueVT.isVector())
Bill Wendling12931302012-09-26 04:04:19 +0000107 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
108 PartVT, ValueVT, V);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000109
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000110 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000111 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000112 SDValue Val = Parts[0];
113
114 if (NumParts > 1) {
115 // Assemble the value from multiple parts.
Chris Lattner3ac18842010-08-24 23:20:40 +0000116 if (ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000117 unsigned PartBits = PartVT.getSizeInBits();
118 unsigned ValueBits = ValueVT.getSizeInBits();
119
120 // Assemble the power of 2 part.
121 unsigned RoundParts = NumParts & (NumParts - 1) ?
122 1 << Log2_32(NumParts) : NumParts;
123 unsigned RoundBits = PartBits * RoundParts;
Owen Andersone50ed302009-08-10 22:56:29 +0000124 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson23b9b192009-08-12 00:36:31 +0000125 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000126 SDValue Lo, Hi;
127
Owen Anderson23b9b192009-08-12 00:36:31 +0000128 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000129
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000130 if (RoundParts > 2) {
Chris Lattner3ac18842010-08-24 23:20:40 +0000131 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
Bill Wendling12931302012-09-26 04:04:19 +0000132 PartVT, HalfVT, V);
Chris Lattner3ac18842010-08-24 23:20:40 +0000133 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
Bill Wendling12931302012-09-26 04:04:19 +0000134 RoundParts / 2, PartVT, HalfVT, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000135 } else {
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000136 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
137 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000138 }
Bill Wendling3ea3c242009-12-22 02:10:19 +0000139
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000140 if (TLI.isBigEndian())
141 std::swap(Lo, Hi);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000142
Chris Lattner3ac18842010-08-24 23:20:40 +0000143 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000144
145 if (RoundParts < NumParts) {
146 // Assemble the trailing non-power-of-2 part.
147 unsigned OddParts = NumParts - RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000148 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Chris Lattner3ac18842010-08-24 23:20:40 +0000149 Hi = getCopyFromParts(DAG, DL,
Bill Wendling12931302012-09-26 04:04:19 +0000150 Parts + RoundParts, OddParts, PartVT, OddVT, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000151
152 // Combine the round and odd parts.
153 Lo = Val;
154 if (TLI.isBigEndian())
155 std::swap(Lo, Hi);
Owen Anderson23b9b192009-08-12 00:36:31 +0000156 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Chris Lattner3ac18842010-08-24 23:20:40 +0000157 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
158 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000159 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000160 TLI.getPointerTy()));
Chris Lattner3ac18842010-08-24 23:20:40 +0000161 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
162 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000163 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000164 } else if (PartVT.isFloatingPoint()) {
165 // FP split into multiple FP parts (for ppcf128)
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000166 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
Eli Friedman2ac8b322009-05-20 06:02:09 +0000167 "Unexpected split");
168 SDValue Lo, Hi;
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000169 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
170 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000171 if (TLI.isBigEndian())
172 std::swap(Lo, Hi);
Chris Lattner3ac18842010-08-24 23:20:40 +0000173 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000174 } else {
175 // FP split into integer parts (soft fp)
176 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
177 !PartVT.isVector() && "Unexpected split");
Owen Anderson23b9b192009-08-12 00:36:31 +0000178 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Bill Wendling12931302012-09-26 04:04:19 +0000179 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000180 }
181 }
182
183 // There is now one part, held in Val. Correct it to match ValueVT.
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000184 EVT PartEVT = Val.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000185
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000186 if (PartEVT == ValueVT)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000187 return Val;
188
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000189 if (PartEVT.isInteger() && ValueVT.isInteger()) {
190 if (ValueVT.bitsLT(PartEVT)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000191 // For a truncate, see if we have any information to
192 // indicate whether the truncated bits will always be
193 // zero or sign-extension.
194 if (AssertOp != ISD::DELETED_NODE)
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000195 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000196 DAG.getValueType(ValueVT));
Chris Lattner3ac18842010-08-24 23:20:40 +0000197 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000198 }
Chris Lattner3ac18842010-08-24 23:20:40 +0000199 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000200 }
201
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000202 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Chris Lattner3ac18842010-08-24 23:20:40 +0000203 // FP_ROUND's are always exact here.
204 if (ValueVT.bitsLT(Val.getValueType()))
205 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
Pete Cooperf57e1c22012-01-17 01:54:07 +0000206 DAG.getTargetConstant(1, TLI.getPointerTy()));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000207
Chris Lattner3ac18842010-08-24 23:20:40 +0000208 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000209 }
210
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000211 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000212 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000213
Torok Edwinc23197a2009-07-14 16:55:14 +0000214 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000215}
216
Bill Wendling12931302012-09-26 04:04:19 +0000217/// getCopyFromPartsVector - Create a value that contains the specified legal
218/// parts combined into the value they represent. If the parts combine to a
219/// type larger then ValueVT then AssertOp can be used to specify whether the
220/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
221/// ValueVT (ISD::AssertSext).
Andrew Trickac6d9be2013-05-25 02:42:55 +0000222static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner3ac18842010-08-24 23:20:40 +0000223 const SDValue *Parts, unsigned NumParts,
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000224 MVT PartVT, EVT ValueVT, const Value *V) {
Chris Lattner3ac18842010-08-24 23:20:40 +0000225 assert(ValueVT.isVector() && "Not a vector value");
226 assert(NumParts > 0 && "No parts to assemble!");
227 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
228 SDValue Val = Parts[0];
Michael J. Spencere70c5262010-10-16 08:25:21 +0000229
Chris Lattner3ac18842010-08-24 23:20:40 +0000230 // Handle a multi-element vector.
231 if (NumParts > 1) {
Patrik Hagglundee211d22012-12-19 11:53:21 +0000232 EVT IntermediateVT;
233 MVT RegisterVT;
Chris Lattner3ac18842010-08-24 23:20:40 +0000234 unsigned NumIntermediates;
235 unsigned NumRegs =
236 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
237 NumIntermediates, RegisterVT);
238 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
239 NumParts = NumRegs; // Silence a compiler warning.
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000240 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Patrik Hagglundee211d22012-12-19 11:53:21 +0000241 assert(RegisterVT == Parts[0].getSimpleValueType() &&
Chris Lattner3ac18842010-08-24 23:20:40 +0000242 "Part type doesn't match part!");
Michael J. Spencere70c5262010-10-16 08:25:21 +0000243
Chris Lattner3ac18842010-08-24 23:20:40 +0000244 // Assemble the parts into intermediate operands.
245 SmallVector<SDValue, 8> Ops(NumIntermediates);
246 if (NumIntermediates == NumParts) {
247 // If the register was not expanded, truncate or copy the value,
248 // as appropriate.
249 for (unsigned i = 0; i != NumParts; ++i)
250 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
Bill Wendling12931302012-09-26 04:04:19 +0000251 PartVT, IntermediateVT, V);
Chris Lattner3ac18842010-08-24 23:20:40 +0000252 } else if (NumParts > 0) {
253 // If the intermediate type was expanded, build the intermediate
254 // operands from the parts.
255 assert(NumParts % NumIntermediates == 0 &&
256 "Must expand into a divisible number of parts!");
257 unsigned Factor = NumParts / NumIntermediates;
258 for (unsigned i = 0; i != NumIntermediates; ++i)
259 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
Bill Wendling12931302012-09-26 04:04:19 +0000260 PartVT, IntermediateVT, V);
Chris Lattner3ac18842010-08-24 23:20:40 +0000261 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000262
Chris Lattner3ac18842010-08-24 23:20:40 +0000263 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
264 // intermediate operands.
265 Val = DAG.getNode(IntermediateVT.isVector() ?
266 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
267 ValueVT, &Ops[0], NumIntermediates);
268 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000269
Chris Lattner3ac18842010-08-24 23:20:40 +0000270 // There is now one part, held in Val. Correct it to match ValueVT.
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000271 EVT PartEVT = Val.getValueType();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000272
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000273 if (PartEVT == ValueVT)
Chris Lattner3ac18842010-08-24 23:20:40 +0000274 return Val;
Michael J. Spencere70c5262010-10-16 08:25:21 +0000275
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000276 if (PartEVT.isVector()) {
Chris Lattnere6f7c262010-08-25 22:49:25 +0000277 // If the element type of the source/dest vectors are the same, but the
278 // parts vector has more elements than the value vector, then we have a
279 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
280 // elements we want.
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000281 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
282 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
Chris Lattnere6f7c262010-08-25 22:49:25 +0000283 "Cannot narrow, it would be a lossy transformation");
284 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
Tom Stellard425b76c2013-08-05 22:22:01 +0000285 DAG.getConstant(0, TLI.getVectorIdxTy()));
Michael J. Spencere70c5262010-10-16 08:25:21 +0000286 }
287
Chris Lattnere6f7c262010-08-25 22:49:25 +0000288 // Vector/Vector bitcast.
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000289 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
Nadav Rotem0b666362011-06-04 20:58:08 +0000290 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
291
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000292 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
Nadav Rotem0b666362011-06-04 20:58:08 +0000293 "Cannot handle this kind of promotion");
294 // Promoted vector extract
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000295 bool Smaller = ValueVT.bitsLE(PartEVT);
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000296 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
297 DL, ValueVT, Val);
Nadav Rotem0b666362011-06-04 20:58:08 +0000298
Chris Lattnere6f7c262010-08-25 22:49:25 +0000299 }
Eric Christopher471e4222011-06-08 23:55:35 +0000300
Eric Christopher9aaa02a2011-06-01 19:55:10 +0000301 // Trivial bitcast if the types are the same size and the destination
302 // vector type is legal.
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000303 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
Eric Christopher9aaa02a2011-06-01 19:55:10 +0000304 TLI.isTypeLegal(ValueVT))
305 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000306
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000307 // Handle cases such as i8 -> <1 x i1>
Bill Wendling12931302012-09-26 04:04:19 +0000308 if (ValueVT.getVectorNumElements() != 1) {
309 LLVMContext &Ctx = *DAG.getContext();
310 Twine ErrMsg("non-trivial scalar-to-vector conversion");
311 if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) {
312 if (const CallInst *CI = dyn_cast<CallInst>(I))
313 if (isa<InlineAsm>(CI->getCalledValue()))
314 ErrMsg = ErrMsg + ", possible invalid constraint for vector type";
315 Ctx.emitError(I, ErrMsg);
316 } else {
317 Ctx.emitError(ErrMsg);
318 }
Chad Rosierf0b07552013-05-01 19:49:26 +0000319 return DAG.getUNDEF(ValueVT);
Bill Wendling12931302012-09-26 04:04:19 +0000320 }
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000321
322 if (ValueVT.getVectorNumElements() == 1 &&
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000323 ValueVT.getVectorElementType() != PartEVT) {
324 bool Smaller = ValueVT.bitsLE(PartEVT);
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000325 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
326 DL, ValueVT.getScalarType(), Val);
327 }
328
Chris Lattner3ac18842010-08-24 23:20:40 +0000329 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
330}
331
Andrew Trickac6d9be2013-05-25 02:42:55 +0000332static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
Chris Lattnera13b8602010-08-24 23:10:06 +0000333 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000334 MVT PartVT, const Value *V);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000335
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000336/// getCopyToParts - Create a series of nodes that contain the specified value
337/// split into legal parts. If the parts contain more bits than Val, then, for
338/// integers, ExtendKind can be used to specify how to generate the extra bits.
Andrew Trickac6d9be2013-05-25 02:42:55 +0000339static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
Bill Wendling3ea3c242009-12-22 02:10:19 +0000340 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000341 MVT PartVT, const Value *V,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000342 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Owen Andersone50ed302009-08-10 22:56:29 +0000343 EVT ValueVT = Val.getValueType();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000344
Chris Lattnera13b8602010-08-24 23:10:06 +0000345 // Handle the vector case separately.
346 if (ValueVT.isVector())
Bill Wendlingf18eb582012-09-26 06:16:18 +0000347 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000348
Chris Lattnera13b8602010-08-24 23:10:06 +0000349 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000350 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000351 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000352 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
353
Chris Lattnera13b8602010-08-24 23:10:06 +0000354 if (NumParts == 0)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000355 return;
356
Chris Lattnera13b8602010-08-24 23:10:06 +0000357 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000358 EVT PartEVT = PartVT;
359 if (PartEVT == ValueVT) {
Chris Lattnera13b8602010-08-24 23:10:06 +0000360 assert(NumParts == 1 && "No-op copy with multiple parts!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000361 Parts[0] = Val;
362 return;
363 }
364
Chris Lattnera13b8602010-08-24 23:10:06 +0000365 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
366 // If the parts cover more bits than the value has, promote the value.
367 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
368 assert(NumParts == 1 && "Do not know what to promote to!");
369 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
370 } else {
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000371 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
372 ValueVT.isInteger() &&
Michael J. Spencere70c5262010-10-16 08:25:21 +0000373 "Unknown mismatch!");
Chris Lattnera13b8602010-08-24 23:10:06 +0000374 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
375 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000376 if (PartVT == MVT::x86mmx)
377 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000378 }
379 } else if (PartBits == ValueVT.getSizeInBits()) {
380 // Different types of the same size.
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000381 assert(NumParts == 1 && PartEVT != ValueVT);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000382 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000383 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
384 // If the parts cover less bits than value has, truncate the value.
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000385 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
386 ValueVT.isInteger() &&
Chris Lattnera13b8602010-08-24 23:10:06 +0000387 "Unknown mismatch!");
388 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
389 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000390 if (PartVT == MVT::x86mmx)
391 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000392 }
393
394 // The value may have changed - recompute ValueVT.
395 ValueVT = Val.getValueType();
396 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
397 "Failed to tile the value with PartVT!");
398
399 if (NumParts == 1) {
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000400 if (PartEVT != ValueVT) {
Bill Wendlingf18eb582012-09-26 06:16:18 +0000401 LLVMContext &Ctx = *DAG.getContext();
402 Twine ErrMsg("scalar-to-vector conversion failed");
403 if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) {
404 if (const CallInst *CI = dyn_cast<CallInst>(I))
405 if (isa<InlineAsm>(CI->getCalledValue()))
406 ErrMsg = ErrMsg + ", possible invalid constraint for vector type";
407 Ctx.emitError(I, ErrMsg);
408 } else {
409 Ctx.emitError(ErrMsg);
410 }
411 }
412
Chris Lattnera13b8602010-08-24 23:10:06 +0000413 Parts[0] = Val;
414 return;
415 }
416
417 // Expand the value into multiple parts.
418 if (NumParts & (NumParts - 1)) {
419 // The number of parts is not a power of 2. Split off and copy the tail.
420 assert(PartVT.isInteger() && ValueVT.isInteger() &&
421 "Do not know what to expand to!");
422 unsigned RoundParts = 1 << Log2_32(NumParts);
423 unsigned RoundBits = RoundParts * PartBits;
424 unsigned OddParts = NumParts - RoundParts;
425 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
426 DAG.getIntPtrConstant(RoundBits));
Bill Wendlingf18eb582012-09-26 06:16:18 +0000427 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
Chris Lattnera13b8602010-08-24 23:10:06 +0000428
429 if (TLI.isBigEndian())
430 // The odd parts were reversed by getCopyToParts - unreverse them.
431 std::reverse(Parts + RoundParts, Parts + NumParts);
432
433 NumParts = RoundParts;
434 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
435 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
436 }
437
438 // The number of parts is a power of 2. Repeatedly bisect the value using
439 // EXTRACT_ELEMENT.
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000440 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
Chris Lattnera13b8602010-08-24 23:10:06 +0000441 EVT::getIntegerVT(*DAG.getContext(),
442 ValueVT.getSizeInBits()),
443 Val);
444
445 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
446 for (unsigned i = 0; i < NumParts; i += StepSize) {
447 unsigned ThisBits = StepSize * PartBits / 2;
448 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
449 SDValue &Part0 = Parts[i];
450 SDValue &Part1 = Parts[i+StepSize/2];
451
452 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
453 ThisVT, Part0, DAG.getIntPtrConstant(1));
454 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
455 ThisVT, Part0, DAG.getIntPtrConstant(0));
456
457 if (ThisBits == PartBits && ThisVT != PartVT) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000458 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
459 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
Chris Lattnera13b8602010-08-24 23:10:06 +0000460 }
461 }
462 }
463
464 if (TLI.isBigEndian())
465 std::reverse(Parts, Parts + OrigNumParts);
466}
467
468
469/// getCopyToPartsVector - Create a series of nodes that contain the specified
470/// value split into legal parts.
Andrew Trickac6d9be2013-05-25 02:42:55 +0000471static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattnera13b8602010-08-24 23:10:06 +0000472 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000473 MVT PartVT, const Value *V) {
Chris Lattnera13b8602010-08-24 23:10:06 +0000474 EVT ValueVT = Val.getValueType();
475 assert(ValueVT.isVector() && "Not a vector");
476 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000477
Chris Lattnera13b8602010-08-24 23:10:06 +0000478 if (NumParts == 1) {
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000479 EVT PartEVT = PartVT;
480 if (PartEVT == ValueVT) {
Chris Lattnere6f7c262010-08-25 22:49:25 +0000481 // Nothing to do.
482 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
483 // Bitconvert vector->vector case.
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000484 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnere6f7c262010-08-25 22:49:25 +0000485 } else if (PartVT.isVector() &&
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000486 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
487 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
Chris Lattnere6f7c262010-08-25 22:49:25 +0000488 EVT ElementVT = PartVT.getVectorElementType();
489 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
490 // undef elements.
491 SmallVector<SDValue, 16> Ops;
492 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
493 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellard425b76c2013-08-05 22:22:01 +0000494 ElementVT, Val, DAG.getConstant(i,
495 TLI.getVectorIdxTy())));
Michael J. Spencere70c5262010-10-16 08:25:21 +0000496
Chris Lattnere6f7c262010-08-25 22:49:25 +0000497 for (unsigned i = ValueVT.getVectorNumElements(),
498 e = PartVT.getVectorNumElements(); i != e; ++i)
499 Ops.push_back(DAG.getUNDEF(ElementVT));
500
501 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
502
503 // FIXME: Use CONCAT for 2x -> 4x.
Michael J. Spencere70c5262010-10-16 08:25:21 +0000504
Chris Lattnere6f7c262010-08-25 22:49:25 +0000505 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
506 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
Nadav Rotem0b666362011-06-04 20:58:08 +0000507 } else if (PartVT.isVector() &&
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000508 PartEVT.getVectorElementType().bitsGE(
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000509 ValueVT.getVectorElementType()) &&
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000510 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
Nadav Rotem0b666362011-06-04 20:58:08 +0000511
512 // Promoted vector extract
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000513 bool Smaller = PartEVT.bitsLE(ValueVT);
Nadav Rotemc6341e62011-06-19 08:49:38 +0000514 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
515 DL, PartVT, Val);
Nadav Rotem0b666362011-06-04 20:58:08 +0000516 } else{
Chris Lattnere6f7c262010-08-25 22:49:25 +0000517 // Vector -> scalar conversion.
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000518 assert(ValueVT.getVectorNumElements() == 1 &&
Chris Lattnere6f7c262010-08-25 22:49:25 +0000519 "Only trivial vector-to-scalar conversions should get here!");
520 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellard425b76c2013-08-05 22:22:01 +0000521 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000522
523 bool Smaller = ValueVT.bitsLE(PartVT);
524 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
525 DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000526 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000527
Chris Lattnera13b8602010-08-24 23:10:06 +0000528 Parts[0] = Val;
529 return;
530 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000531
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000532 // Handle a multi-element vector.
Patrik Hagglundee211d22012-12-19 11:53:21 +0000533 EVT IntermediateVT;
534 MVT RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000535 unsigned NumIntermediates;
Owen Anderson23b9b192009-08-12 00:36:31 +0000536 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
Devang Patel8f09bea2010-08-26 20:32:32 +0000537 IntermediateVT,
538 NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000539 unsigned NumElements = ValueVT.getVectorNumElements();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000540
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000541 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
542 NumParts = NumRegs; // Silence a compiler warning.
Patrik Hagglundb9e12e52012-12-19 12:33:30 +0000543 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Michael J. Spencere70c5262010-10-16 08:25:21 +0000544
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000545 // Split the vector into intermediate operands.
546 SmallVector<SDValue, 8> Ops(NumIntermediates);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000547 for (unsigned i = 0; i != NumIntermediates; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000548 if (IntermediateVT.isVector())
Chris Lattnera13b8602010-08-24 23:10:06 +0000549 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000550 IntermediateVT, Val,
Tom Stellard425b76c2013-08-05 22:22:01 +0000551 DAG.getConstant(i * (NumElements / NumIntermediates),
552 TLI.getVectorIdxTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000553 else
Chris Lattnera13b8602010-08-24 23:10:06 +0000554 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellard425b76c2013-08-05 22:22:01 +0000555 IntermediateVT, Val,
556 DAG.getConstant(i, TLI.getVectorIdxTy()));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000557 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000558
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000559 // Split the intermediate operands into legal parts.
560 if (NumParts == NumIntermediates) {
561 // If the register was not expanded, promote or copy the value,
562 // as appropriate.
563 for (unsigned i = 0; i != NumParts; ++i)
Bill Wendlingf18eb582012-09-26 06:16:18 +0000564 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000565 } else if (NumParts > 0) {
566 // If the intermediate type was expanded, split each the value into
567 // legal parts.
568 assert(NumParts % NumIntermediates == 0 &&
569 "Must expand into a divisible number of parts!");
570 unsigned Factor = NumParts / NumIntermediates;
571 for (unsigned i = 0; i != NumIntermediates; ++i)
Bill Wendlingf18eb582012-09-26 06:16:18 +0000572 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000573 }
574}
575
Dan Gohman462f6b52010-05-29 17:53:24 +0000576namespace {
577 /// RegsForValue - This struct represents the registers (physical or virtual)
578 /// that a particular set of values is assigned, and the type information
579 /// about the value. The most common situation is to represent one value at a
580 /// time, but struct or array values are handled element-wise as multiple
581 /// values. The splitting of aggregates is performed recursively, so that we
582 /// never have aggregate-typed registers. The values at this point do not
583 /// necessarily have legal types, so each value may require one or more
584 /// registers of some legal type.
585 ///
586 struct RegsForValue {
587 /// ValueVTs - The value types of the values, which may not be legal, and
588 /// may need be promoted or synthesized from one or more registers.
589 ///
590 SmallVector<EVT, 4> ValueVTs;
591
592 /// RegVTs - The value types of the registers. This is the same size as
593 /// ValueVTs and it records, for each value, what the type of the assigned
594 /// register or registers are. (Individual values are never synthesized
595 /// from more than one type of register.)
596 ///
597 /// With virtual registers, the contents of RegVTs is redundant with TLI's
598 /// getRegisterType member function, however when with physical registers
599 /// it is necessary to have a separate record of the types.
600 ///
Patrik Hagglund8963fec2012-12-19 12:23:01 +0000601 SmallVector<MVT, 4> RegVTs;
Dan Gohman462f6b52010-05-29 17:53:24 +0000602
603 /// Regs - This list holds the registers assigned to the values.
604 /// Each legal or promoted value requires one register, and each
605 /// expanded value requires multiple registers.
606 ///
607 SmallVector<unsigned, 4> Regs;
608
609 RegsForValue() {}
610
611 RegsForValue(const SmallVector<unsigned, 4> &regs,
Patrik Hagglund8963fec2012-12-19 12:23:01 +0000612 MVT regvt, EVT valuevt)
Dan Gohman462f6b52010-05-29 17:53:24 +0000613 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
614
Dan Gohman462f6b52010-05-29 17:53:24 +0000615 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000616 unsigned Reg, Type *Ty) {
Dan Gohman462f6b52010-05-29 17:53:24 +0000617 ComputeValueVTs(tli, Ty, ValueVTs);
618
619 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
620 EVT ValueVT = ValueVTs[Value];
621 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
Patrik Hagglunddfcf33a2012-12-19 11:48:16 +0000622 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
Dan Gohman462f6b52010-05-29 17:53:24 +0000623 for (unsigned i = 0; i != NumRegs; ++i)
624 Regs.push_back(Reg + i);
625 RegVTs.push_back(RegisterVT);
626 Reg += NumRegs;
627 }
628 }
629
630 /// areValueTypesLegal - Return true if types of all the values are legal.
631 bool areValueTypesLegal(const TargetLowering &TLI) {
632 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Patrik Hagglund8963fec2012-12-19 12:23:01 +0000633 MVT RegisterVT = RegVTs[Value];
Dan Gohman462f6b52010-05-29 17:53:24 +0000634 if (!TLI.isTypeLegal(RegisterVT))
635 return false;
636 }
637 return true;
638 }
639
640 /// append - Add the specified values to this one.
641 void append(const RegsForValue &RHS) {
642 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
643 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
644 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
645 }
646
647 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
648 /// this value and returns the result as a ValueVTs value. This uses
649 /// Chain/Flag as the input and updates them for the output Chain/Flag.
650 /// If the Flag pointer is NULL, no flag is used.
651 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
Andrew Trickac6d9be2013-05-25 02:42:55 +0000652 SDLoc dl,
Bill Wendling12931302012-09-26 04:04:19 +0000653 SDValue &Chain, SDValue *Flag,
654 const Value *V = 0) const;
Dan Gohman462f6b52010-05-29 17:53:24 +0000655
656 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
657 /// specified value into the registers specified by this object. This uses
658 /// Chain/Flag as the input and updates them for the output Chain/Flag.
659 /// If the Flag pointer is NULL, no flag is used.
Andrew Trickac6d9be2013-05-25 02:42:55 +0000660 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
Bill Wendlingf18eb582012-09-26 06:16:18 +0000661 SDValue &Chain, SDValue *Flag, const Value *V) const;
Dan Gohman462f6b52010-05-29 17:53:24 +0000662
663 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
664 /// operand list. This adds the code marker, matching input operand index
665 /// (if applicable), and includes the number of values added into it.
666 void AddInlineAsmOperands(unsigned Kind,
667 bool HasMatching, unsigned MatchingIdx,
668 SelectionDAG &DAG,
669 std::vector<SDValue> &Ops) const;
670 };
671}
672
673/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
674/// this value and returns the result as a ValueVT value. This uses
675/// Chain/Flag as the input and updates them for the output Chain/Flag.
676/// If the Flag pointer is NULL, no flag is used.
677SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
678 FunctionLoweringInfo &FuncInfo,
Andrew Trickac6d9be2013-05-25 02:42:55 +0000679 SDLoc dl,
Bill Wendling12931302012-09-26 04:04:19 +0000680 SDValue &Chain, SDValue *Flag,
681 const Value *V) const {
Dan Gohman7da5d3f2010-07-26 18:15:41 +0000682 // A Value with type {} or [0 x %t] needs no registers.
683 if (ValueVTs.empty())
684 return SDValue();
685
Dan Gohman462f6b52010-05-29 17:53:24 +0000686 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
687
688 // Assemble the legal parts into the final values.
689 SmallVector<SDValue, 4> Values(ValueVTs.size());
690 SmallVector<SDValue, 8> Parts;
691 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
692 // Copy the legal parts from the registers.
693 EVT ValueVT = ValueVTs[Value];
694 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
Patrik Hagglund8963fec2012-12-19 12:23:01 +0000695 MVT RegisterVT = RegVTs[Value];
Dan Gohman462f6b52010-05-29 17:53:24 +0000696
697 Parts.resize(NumRegs);
698 for (unsigned i = 0; i != NumRegs; ++i) {
699 SDValue P;
700 if (Flag == 0) {
701 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
702 } else {
703 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
704 *Flag = P.getValue(2);
705 }
706
707 Chain = P.getValue(1);
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000708 Parts[i] = P;
Dan Gohman462f6b52010-05-29 17:53:24 +0000709
710 // If the source register was virtual and if we know something about it,
711 // add an assert node.
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000712 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
Cameron Zwariche1497b92011-02-24 10:00:08 +0000713 !RegisterVT.isInteger() || RegisterVT.isVector())
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000714 continue;
Cameron Zwariche1497b92011-02-24 10:00:08 +0000715
716 const FunctionLoweringInfo::LiveOutInfo *LOI =
717 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
718 if (!LOI)
719 continue;
Dan Gohman462f6b52010-05-29 17:53:24 +0000720
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000721 unsigned RegSize = RegisterVT.getSizeInBits();
Cameron Zwariche1497b92011-02-24 10:00:08 +0000722 unsigned NumSignBits = LOI->NumSignBits;
723 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
Dan Gohman462f6b52010-05-29 17:53:24 +0000724
Quentin Colombeta3fb49c2013-06-18 20:14:39 +0000725 if (NumZeroBits == RegSize) {
726 // The current value is a zero.
727 // Explicitly express that as it would be easier for
728 // optimizations to kick in.
729 Parts[i] = DAG.getConstant(0, RegisterVT);
730 continue;
731 }
732
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000733 // FIXME: We capture more information than the dag can represent. For
734 // now, just use the tightest assertzext/assertsext possible.
735 bool isSExt = true;
736 EVT FromVT(MVT::Other);
737 if (NumSignBits == RegSize)
738 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
739 else if (NumZeroBits >= RegSize-1)
740 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
741 else if (NumSignBits > RegSize-8)
742 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
743 else if (NumZeroBits >= RegSize-8)
744 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
745 else if (NumSignBits > RegSize-16)
746 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
747 else if (NumZeroBits >= RegSize-16)
748 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
749 else if (NumSignBits > RegSize-32)
750 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
751 else if (NumZeroBits >= RegSize-32)
752 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
753 else
754 continue;
Dan Gohman462f6b52010-05-29 17:53:24 +0000755
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000756 // Add an assertion node.
757 assert(FromVT != MVT::Other);
758 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
759 RegisterVT, P, DAG.getValueType(FromVT));
Dan Gohman462f6b52010-05-29 17:53:24 +0000760 }
761
762 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Bill Wendling12931302012-09-26 04:04:19 +0000763 NumRegs, RegisterVT, ValueVT, V);
Dan Gohman462f6b52010-05-29 17:53:24 +0000764 Part += NumRegs;
765 Parts.clear();
766 }
767
768 return DAG.getNode(ISD::MERGE_VALUES, dl,
769 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
770 &Values[0], ValueVTs.size());
771}
772
773/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
774/// specified value into the registers specified by this object. This uses
775/// Chain/Flag as the input and updates them for the output Chain/Flag.
776/// If the Flag pointer is NULL, no flag is used.
Andrew Trickac6d9be2013-05-25 02:42:55 +0000777void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
Bill Wendlingf18eb582012-09-26 06:16:18 +0000778 SDValue &Chain, SDValue *Flag,
779 const Value *V) const {
Dan Gohman462f6b52010-05-29 17:53:24 +0000780 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
781
782 // Get the list of the values's legal parts.
783 unsigned NumRegs = Regs.size();
784 SmallVector<SDValue, 8> Parts(NumRegs);
785 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
786 EVT ValueVT = ValueVTs[Value];
787 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
Patrik Hagglund8963fec2012-12-19 12:23:01 +0000788 MVT RegisterVT = RegVTs[Value];
Evan Cheng2766a472012-12-06 19:13:27 +0000789 ISD::NodeType ExtendKind =
790 TLI.isZExtFree(Val, RegisterVT)? ISD::ZERO_EXTEND: ISD::ANY_EXTEND;
Dan Gohman462f6b52010-05-29 17:53:24 +0000791
Chris Lattner3ac18842010-08-24 23:20:40 +0000792 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Evan Cheng2766a472012-12-06 19:13:27 +0000793 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
Dan Gohman462f6b52010-05-29 17:53:24 +0000794 Part += NumParts;
795 }
796
797 // Copy the parts into the registers.
798 SmallVector<SDValue, 8> Chains(NumRegs);
799 for (unsigned i = 0; i != NumRegs; ++i) {
800 SDValue Part;
801 if (Flag == 0) {
802 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
803 } else {
804 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
805 *Flag = Part.getValue(1);
806 }
807
808 Chains[i] = Part.getValue(0);
809 }
810
811 if (NumRegs == 1 || Flag)
812 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
813 // flagged to it. That is the CopyToReg nodes and the user are considered
814 // a single scheduling unit. If we create a TokenFactor and return it as
815 // chain, then the TokenFactor is both a predecessor (operand) of the
816 // user as well as a successor (the TF operands are flagged to the user).
817 // c1, f1 = CopyToReg
818 // c2, f2 = CopyToReg
819 // c3 = TokenFactor c1, c2
820 // ...
821 // = op c3, ..., f2
822 Chain = Chains[NumRegs-1];
823 else
824 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
825}
826
827/// AddInlineAsmOperands - Add this value to the specified inlineasm node
828/// operand list. This adds the code marker and includes the number of
829/// values added into it.
830void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
831 unsigned MatchingIdx,
832 SelectionDAG &DAG,
833 std::vector<SDValue> &Ops) const {
834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
835
836 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
837 if (HasMatching)
838 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
Jakob Stoklund Olesen459b74b2011-10-12 23:37:29 +0000839 else if (!Regs.empty() &&
840 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
841 // Put the register class of the virtual registers in the flag word. That
842 // way, later passes can recompute register class constraints for inline
843 // assembly as well as normal instructions.
844 // Don't do this for tied operands that can use the regclass information
845 // from the def.
846 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
847 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
848 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
849 }
850
Dan Gohman462f6b52010-05-29 17:53:24 +0000851 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
852 Ops.push_back(Res);
853
854 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
855 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Patrik Hagglund8963fec2012-12-19 12:23:01 +0000856 MVT RegisterVT = RegVTs[Value];
Dan Gohman462f6b52010-05-29 17:53:24 +0000857 for (unsigned i = 0; i != NumRegs; ++i) {
858 assert(Reg < Regs.size() && "Mismatch in # registers expected");
859 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
860 }
861 }
862}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000863
Owen Anderson243eb9e2011-12-08 22:15:21 +0000864void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
865 const TargetLibraryInfo *li) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000866 AA = &aa;
867 GFI = gfi;
Owen Anderson243eb9e2011-12-08 22:15:21 +0000868 LibInfo = li;
Micah Villmow3574eca2012-10-08 16:38:25 +0000869 TD = DAG.getTarget().getDataLayout();
Richard Smithcb1f68d2012-08-22 00:42:39 +0000870 Context = DAG.getContext();
Bill Wendling4ed1fb02011-10-15 01:00:26 +0000871 LPadToCallSiteMap.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000872}
873
Dan Gohmanb02b62a2010-04-14 18:24:06 +0000874/// clear - Clear out the current SelectionDAG and the associated
Dan Gohman2048b852009-11-23 18:04:58 +0000875/// state and prepare this SelectionDAGBuilder object to be used
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000876/// for a new block. This doesn't clear out information about
877/// additional blocks that are needed to complete switch lowering
878/// or PHI node updating; that information is cleared out as it is
879/// consumed.
Dan Gohman2048b852009-11-23 18:04:58 +0000880void SelectionDAGBuilder::clear() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000881 NodeMap.clear();
Devang Patel9126c0d2010-06-01 19:59:01 +0000882 UnusedArgNodeMap.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000883 PendingLoads.clear();
884 PendingExports.clear();
Andrew Trickea5db0c2013-05-25 02:20:36 +0000885 CurInst = NULL;
Dan Gohman98ca4f22009-08-05 01:29:28 +0000886 HasTailCall = false;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000887}
888
Devang Patel23385752011-05-23 17:44:13 +0000889/// clearDanglingDebugInfo - Clear the dangling debug information
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000890/// map. This function is separated from the clear so that debug
Devang Patel23385752011-05-23 17:44:13 +0000891/// information that is dangling in a basic block can be properly
892/// resolved in a different basic block. This allows the
893/// SelectionDAG to resolve dangling debug information attached
894/// to PHI nodes.
895void SelectionDAGBuilder::clearDanglingDebugInfo() {
896 DanglingDebugInfoMap.clear();
897}
898
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000899/// getRoot - Return the current virtual root of the Selection DAG,
900/// flushing any PendingLoad items. This must be done before emitting
901/// a store or any other node that may need to be ordered after any
902/// prior load instructions.
903///
Dan Gohman2048b852009-11-23 18:04:58 +0000904SDValue SelectionDAGBuilder::getRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000905 if (PendingLoads.empty())
906 return DAG.getRoot();
907
908 if (PendingLoads.size() == 1) {
909 SDValue Root = PendingLoads[0];
910 DAG.setRoot(Root);
911 PendingLoads.clear();
912 return Root;
913 }
914
915 // Otherwise, we have to make a token factor node.
Andrew Trickac6d9be2013-05-25 02:42:55 +0000916 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000917 &PendingLoads[0], PendingLoads.size());
918 PendingLoads.clear();
919 DAG.setRoot(Root);
920 return Root;
921}
922
923/// getControlRoot - Similar to getRoot, but instead of flushing all the
924/// PendingLoad items, flush all the PendingExports items. It is necessary
925/// to do this before emitting a terminator instruction.
926///
Dan Gohman2048b852009-11-23 18:04:58 +0000927SDValue SelectionDAGBuilder::getControlRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000928 SDValue Root = DAG.getRoot();
929
930 if (PendingExports.empty())
931 return Root;
932
933 // Turn all of the CopyToReg chains into one factored node.
934 if (Root.getOpcode() != ISD::EntryToken) {
935 unsigned i = 0, e = PendingExports.size();
936 for (; i != e; ++i) {
937 assert(PendingExports[i].getNode()->getNumOperands() > 1);
938 if (PendingExports[i].getNode()->getOperand(0) == Root)
939 break; // Don't add the root if we already indirectly depend on it.
940 }
941
942 if (i == e)
943 PendingExports.push_back(Root);
944 }
945
Andrew Trickac6d9be2013-05-25 02:42:55 +0000946 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000947 &PendingExports[0],
948 PendingExports.size());
949 PendingExports.clear();
950 DAG.setRoot(Root);
951 return Root;
952}
953
Dan Gohman46510a72010-04-15 01:51:59 +0000954void SelectionDAGBuilder::visit(const Instruction &I) {
Dan Gohmanc105a2b2010-04-22 20:55:53 +0000955 // Set up outgoing PHI node register values before emitting the terminator.
956 if (isa<TerminatorInst>(&I))
957 HandlePHINodesInSuccessorBlocks(I.getParent());
958
Andrew Trickdd0fb012013-05-25 03:08:10 +0000959 ++SDNodeOrder;
960
Andrew Trickea5db0c2013-05-25 02:20:36 +0000961 CurInst = &I;
Dan Gohman8ba3aa72010-04-20 00:48:35 +0000962
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000963 visit(I.getOpcode(), I);
Dan Gohman8ba3aa72010-04-20 00:48:35 +0000964
Dan Gohman92884f72010-04-20 15:03:56 +0000965 if (!isa<TerminatorInst>(&I) && !HasTailCall)
966 CopyToExportRegsIfNeeded(&I);
967
Andrew Trickea5db0c2013-05-25 02:20:36 +0000968 CurInst = NULL;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000969}
970
Dan Gohmanba5be5c2010-04-20 15:00:41 +0000971void SelectionDAGBuilder::visitPHI(const PHINode &) {
972 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
973}
974
Dan Gohman46510a72010-04-15 01:51:59 +0000975void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000976 // Note: this doesn't use InstVisitor, because it has to work with
977 // ConstantExpr's in addition to instructions.
978 switch (Opcode) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000979 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000980 // Build the switch statement using the Instruction.def file.
981#define HANDLE_INST(NUM, OPCODE, CLASS) \
Galina Kistanova72ea0c92012-07-19 04:50:12 +0000982 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000983#include "llvm/IR/Instruction.def"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000984 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000985}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000986
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000987// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
988// generate the debug data structures now that we've seen its definition.
989void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
990 SDValue Val) {
991 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
Devang Patel4cf81c42010-08-26 23:35:15 +0000992 if (DDI.getDI()) {
993 const DbgValueInst *DI = DDI.getDI();
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000994 DebugLoc dl = DDI.getdl();
995 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
Devang Patel4cf81c42010-08-26 23:35:15 +0000996 MDNode *Variable = DI->getVariable();
997 uint64_t Offset = DI->getOffset();
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000998 SDDbgValue *SDV;
999 if (Val.getNode()) {
Devang Patel78a06e52010-08-25 20:39:26 +00001000 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001001 SDV = DAG.getDbgValue(Variable, Val.getNode(),
1002 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
1003 DAG.AddDbgValue(SDV, Val.getNode(), false);
1004 }
Owen Anderson95771af2011-02-25 21:41:48 +00001005 } else
Adrian Prantl5da4e4f2013-05-22 18:02:19 +00001006 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001007 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1008 }
1009}
1010
Nick Lewycky8de34002011-09-30 22:19:53 +00001011/// getValue - Return an SDValue for the given Value.
Dan Gohman2048b852009-11-23 18:04:58 +00001012SDValue SelectionDAGBuilder::getValue(const Value *V) {
Dan Gohman28a17352010-07-01 01:59:43 +00001013 // If we already have an SDValue for this value, use it. It's important
1014 // to do this first, so that we don't create a CopyFromReg if we already
1015 // have a regular SDValue.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001016 SDValue &N = NodeMap[V];
1017 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001018
Dan Gohman28a17352010-07-01 01:59:43 +00001019 // If there's a virtual register allocated and initialized for this
1020 // value, use it.
1021 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1022 if (It != FuncInfo.ValueMap.end()) {
1023 unsigned InReg = It->second;
Bill Wendlingba54bca2013-06-19 21:36:55 +00001024 RegsForValue RFV(*DAG.getContext(), *TM.getTargetLowering(),
1025 InReg, V->getType());
Dan Gohman28a17352010-07-01 01:59:43 +00001026 SDValue Chain = DAG.getEntryNode();
Andrew Trickac6d9be2013-05-25 02:42:55 +00001027 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
Devang Patel8f314282011-01-25 18:09:58 +00001028 resolveDanglingDebugInfo(V, N);
1029 return N;
Dan Gohman28a17352010-07-01 01:59:43 +00001030 }
1031
1032 // Otherwise create a new SDValue and remember it.
1033 SDValue Val = getValueImpl(V);
1034 NodeMap[V] = Val;
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001035 resolveDanglingDebugInfo(V, Val);
Dan Gohman28a17352010-07-01 01:59:43 +00001036 return Val;
1037}
1038
1039/// getNonRegisterValue - Return an SDValue for the given Value, but
1040/// don't look in FuncInfo.ValueMap for a virtual register.
1041SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1042 // If we already have an SDValue for this value, use it.
1043 SDValue &N = NodeMap[V];
1044 if (N.getNode()) return N;
1045
1046 // Otherwise create a new SDValue and remember it.
1047 SDValue Val = getValueImpl(V);
1048 NodeMap[V] = Val;
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001049 resolveDanglingDebugInfo(V, Val);
Dan Gohman28a17352010-07-01 01:59:43 +00001050 return Val;
1051}
1052
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001053/// getValueImpl - Helper function for getValue and getNonRegisterValue.
Dan Gohman28a17352010-07-01 01:59:43 +00001054/// Create an SDValue for the given value.
1055SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00001056 const TargetLowering *TLI = TM.getTargetLowering();
1057
Dan Gohman383b5f62010-04-17 15:32:28 +00001058 if (const Constant *C = dyn_cast<Constant>(V)) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00001059 EVT VT = TLI->getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001060
Dan Gohman383b5f62010-04-17 15:32:28 +00001061 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman28a17352010-07-01 01:59:43 +00001062 return DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001063
Dan Gohman383b5f62010-04-17 15:32:28 +00001064 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001065 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001066
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001067 if (isa<ConstantPointerNull>(C))
Bill Wendlingba54bca2013-06-19 21:36:55 +00001068 return DAG.getConstant(0, TLI->getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001069
Dan Gohman383b5f62010-04-17 15:32:28 +00001070 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman28a17352010-07-01 01:59:43 +00001071 return DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001072
Nate Begeman9008ca62009-04-27 18:41:29 +00001073 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dan Gohman28a17352010-07-01 01:59:43 +00001074 return DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001075
Dan Gohman383b5f62010-04-17 15:32:28 +00001076 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001077 visit(CE->getOpcode(), *CE);
1078 SDValue N1 = NodeMap[V];
Dan Gohmanac7d05c2010-04-16 16:55:18 +00001079 assert(N1.getNode() && "visit didn't populate the NodeMap!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001080 return N1;
1081 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001082
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001083 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1084 SmallVector<SDValue, 4> Constants;
1085 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1086 OI != OE; ++OI) {
1087 SDNode *Val = getValue(*OI).getNode();
Dan Gohmaned48caf2009-09-08 01:44:02 +00001088 // If the operand is an empty aggregate, there are no values.
1089 if (!Val) continue;
1090 // Add each leaf value from the operand to the Constants list
1091 // to form a flattened list of all the values.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001092 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1093 Constants.push_back(SDValue(Val, i));
1094 }
Bill Wendling87710f02009-12-21 23:47:40 +00001095
Bill Wendling4533cac2010-01-28 21:51:40 +00001096 return DAG.getMergeValues(&Constants[0], Constants.size(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00001097 getCurSDLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001098 }
Stephen Lin155615d2013-07-08 00:37:03 +00001099
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001100 if (const ConstantDataSequential *CDS =
1101 dyn_cast<ConstantDataSequential>(C)) {
1102 SmallVector<SDValue, 4> Ops;
Chris Lattner0f193b82012-01-25 01:27:20 +00001103 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001104 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1105 // Add each leaf value from the operand to the Constants list
1106 // to form a flattened list of all the values.
1107 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1108 Ops.push_back(SDValue(Val, i));
1109 }
1110
1111 if (isa<ArrayType>(CDS->getType()))
Andrew Trickac6d9be2013-05-25 02:42:55 +00001112 return DAG.getMergeValues(&Ops[0], Ops.size(), getCurSDLoc());
1113 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001114 VT, &Ops[0], Ops.size());
1115 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001116
Duncan Sands1df98592010-02-16 11:11:14 +00001117 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001118 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1119 "Unknown struct or array constant!");
1120
Owen Andersone50ed302009-08-10 22:56:29 +00001121 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00001122 ComputeValueVTs(*TLI, C->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001123 unsigned NumElts = ValueVTs.size();
1124 if (NumElts == 0)
1125 return SDValue(); // empty struct
1126 SmallVector<SDValue, 4> Constants(NumElts);
1127 for (unsigned i = 0; i != NumElts; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00001128 EVT EltVT = ValueVTs[i];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001129 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +00001130 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001131 else if (EltVT.isFloatingPoint())
1132 Constants[i] = DAG.getConstantFP(0, EltVT);
1133 else
1134 Constants[i] = DAG.getConstant(0, EltVT);
1135 }
Bill Wendling87710f02009-12-21 23:47:40 +00001136
Bill Wendling4533cac2010-01-28 21:51:40 +00001137 return DAG.getMergeValues(&Constants[0], NumElts,
Andrew Trickac6d9be2013-05-25 02:42:55 +00001138 getCurSDLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001139 }
1140
Dan Gohman383b5f62010-04-17 15:32:28 +00001141 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
Dan Gohman29cbade2009-11-20 23:18:13 +00001142 return DAG.getBlockAddress(BA, VT);
Dan Gohman8c2b5252009-10-30 01:27:03 +00001143
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001144 VectorType *VecTy = cast<VectorType>(V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001145 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001146
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001147 // Now that we know the number and type of the elements, get that number of
1148 // elements into the Ops array based on what kind of constant it is.
1149 SmallVector<SDValue, 16> Ops;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001150 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001151 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001152 Ops.push_back(getValue(CV->getOperand(i)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001153 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00001154 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Bill Wendlingba54bca2013-06-19 21:36:55 +00001155 EVT EltVT = TLI->getValueType(VecTy->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001156
1157 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +00001158 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001159 Op = DAG.getConstantFP(0, EltVT);
1160 else
1161 Op = DAG.getConstant(0, EltVT);
1162 Ops.assign(NumElements, Op);
1163 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001164
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001165 // Create a BUILD_VECTOR node.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001166 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00001167 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001168 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001169
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001170 // If this is a static alloca, generate it as the frameindex instead of
1171 // computation.
1172 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1173 DenseMap<const AllocaInst*, int>::iterator SI =
1174 FuncInfo.StaticAllocaMap.find(AI);
1175 if (SI != FuncInfo.StaticAllocaMap.end())
Bill Wendlingba54bca2013-06-19 21:36:55 +00001176 return DAG.getFrameIndex(SI->second, TLI->getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001177 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001178
Dan Gohman28a17352010-07-01 01:59:43 +00001179 // If this is an instruction which fast-isel has deferred, select it now.
1180 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
Dan Gohman84023e02010-07-10 09:00:22 +00001181 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
Bill Wendlingba54bca2013-06-19 21:36:55 +00001182 RegsForValue RFV(*DAG.getContext(), *TLI, InReg, Inst->getType());
Dan Gohman84023e02010-07-10 09:00:22 +00001183 SDValue Chain = DAG.getEntryNode();
Andrew Trickac6d9be2013-05-25 02:42:55 +00001184 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
Dan Gohman28a17352010-07-01 01:59:43 +00001185 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001186
Dan Gohman28a17352010-07-01 01:59:43 +00001187 llvm_unreachable("Can't get register for value!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001188}
1189
Dan Gohman46510a72010-04-15 01:51:59 +00001190void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00001191 const TargetLowering *TLI = TM.getTargetLowering();
Dan Gohman98ca4f22009-08-05 01:29:28 +00001192 SDValue Chain = getControlRoot();
1193 SmallVector<ISD::OutputArg, 8> Outs;
Dan Gohmanc9403652010-07-07 15:54:55 +00001194 SmallVector<SDValue, 8> OutVals;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001195
Dan Gohman7451d3e2010-05-29 17:03:36 +00001196 if (!FuncInfo.CanLowerReturn) {
1197 unsigned DemoteReg = FuncInfo.DemoteRegister;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001198 const Function *F = I.getParent()->getParent();
1199
1200 // Emit a store of the return value through the virtual register.
1201 // Leave Outs empty so that LowerReturn won't try to load return
1202 // registers the usual way.
1203 SmallVector<EVT, 1> PtrValueVTs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00001204 ComputeValueVTs(*TLI, PointerType::getUnqual(F->getReturnType()),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001205 PtrValueVTs);
1206
1207 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1208 SDValue RetOp = getValue(I.getOperand(0));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001209
Owen Andersone50ed302009-08-10 22:56:29 +00001210 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001211 SmallVector<uint64_t, 4> Offsets;
Bill Wendlingba54bca2013-06-19 21:36:55 +00001212 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman7ea1ca62008-10-21 20:00:42 +00001213 unsigned NumValues = ValueVTs.size();
Dan Gohman7ea1ca62008-10-21 20:00:42 +00001214
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001215 SmallVector<SDValue, 4> Chains(NumValues);
Bill Wendling87710f02009-12-21 23:47:40 +00001216 for (unsigned i = 0; i != NumValues; ++i) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00001217 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
Chris Lattnera13b8602010-08-24 23:10:06 +00001218 RetPtr.getValueType(), RetPtr,
1219 DAG.getIntPtrConstant(Offsets[i]));
Bill Wendling87710f02009-12-21 23:47:40 +00001220 Chains[i] =
Andrew Trickac6d9be2013-05-25 02:42:55 +00001221 DAG.getStore(Chain, getCurSDLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001222 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
Chris Lattner84bd98a2010-09-21 18:58:22 +00001223 // FIXME: better loc info would be nice.
1224 Add, MachinePointerInfo(), false, false, 0);
Bill Wendling87710f02009-12-21 23:47:40 +00001225 }
1226
Andrew Trickac6d9be2013-05-25 02:42:55 +00001227 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001228 MVT::Other, &Chains[0], NumValues);
Chris Lattner25d58372010-02-28 18:53:13 +00001229 } else if (I.getNumOperands() != 0) {
1230 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00001231 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs);
Chris Lattner25d58372010-02-28 18:53:13 +00001232 unsigned NumValues = ValueVTs.size();
1233 if (NumValues) {
1234 SDValue RetOp = getValue(I.getOperand(0));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001235 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1236 EVT VT = ValueVTs[j];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001237
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001238 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001239
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001240 const Function *F = I.getParent()->getParent();
Bill Wendling8b62abd2012-12-30 13:01:51 +00001241 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1242 Attribute::SExt))
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001243 ExtendKind = ISD::SIGN_EXTEND;
Bill Wendling8b62abd2012-12-30 13:01:51 +00001244 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1245 Attribute::ZExt))
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001246 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001247
Cameron Zwarich7bbf0ee2011-03-17 14:53:37 +00001248 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
Bill Wendlingba54bca2013-06-19 21:36:55 +00001249 VT = TLI->getTypeForExtArgOrReturn(VT.getSimpleVT(), ExtendKind);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001250
Bill Wendlingba54bca2013-06-19 21:36:55 +00001251 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), VT);
1252 MVT PartVT = TLI->getRegisterType(*DAG.getContext(), VT);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001253 SmallVector<SDValue, 4> Parts(NumParts);
Andrew Trickac6d9be2013-05-25 02:42:55 +00001254 getCopyToParts(DAG, getCurSDLoc(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001255 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Bill Wendlingf18eb582012-09-26 06:16:18 +00001256 &Parts[0], NumParts, PartVT, &I, ExtendKind);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001257
1258 // 'inreg' on function refers to return value
1259 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Bill Wendling8b62abd2012-12-30 13:01:51 +00001260 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1261 Attribute::InReg))
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001262 Flags.setInReg();
1263
1264 // Propagate extension type if any
Cameron Zwarich8df6bf52011-03-16 22:20:07 +00001265 if (ExtendKind == ISD::SIGN_EXTEND)
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001266 Flags.setSExt();
Cameron Zwarich8df6bf52011-03-16 22:20:07 +00001267 else if (ExtendKind == ISD::ZERO_EXTEND)
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001268 Flags.setZExt();
1269
Dan Gohmanc9403652010-07-07 15:54:55 +00001270 for (unsigned i = 0; i < NumParts; ++i) {
1271 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
Tom Stellardd0716b02013-10-23 00:44:24 +00001272 VT, /*isfixed=*/true, 0, 0));
Dan Gohmanc9403652010-07-07 15:54:55 +00001273 OutVals.push_back(Parts[i]);
1274 }
Evan Cheng3927f432009-03-25 20:20:11 +00001275 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001276 }
1277 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00001278
1279 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001280 CallingConv::ID CallConv =
1281 DAG.getMachineFunction().getFunction()->getCallingConv();
Bill Wendlingba54bca2013-06-19 21:36:55 +00001282 Chain = TM.getTargetLowering()->LowerReturn(Chain, CallConv, isVarArg,
1283 Outs, OutVals, getCurSDLoc(),
1284 DAG);
Dan Gohman5e866062009-08-06 15:37:27 +00001285
1286 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00001287 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00001288 "LowerReturn didn't return a valid chain!");
1289
1290 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00001291 DAG.setRoot(Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001292}
1293
Dan Gohmanad62f532009-04-23 23:13:24 +00001294/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1295/// created for it, emit nodes to copy the value into the virtual
1296/// registers.
Dan Gohman46510a72010-04-15 01:51:59 +00001297void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
Rafael Espindola3fa82832011-05-13 15:18:06 +00001298 // Skip empty types
1299 if (V->getType()->isEmptyTy())
1300 return;
1301
Dan Gohman33b7a292010-04-16 17:15:02 +00001302 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1303 if (VMI != FuncInfo.ValueMap.end()) {
1304 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1305 CopyValueToVirtualRegister(V, VMI->second);
Dan Gohmanad62f532009-04-23 23:13:24 +00001306 }
1307}
1308
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001309/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1310/// the current basic block, add it to ValueMap now so that we'll get a
1311/// CopyTo/FromReg.
Dan Gohman46510a72010-04-15 01:51:59 +00001312void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001313 // No need to export constants.
1314 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001315
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001316 // Already exported?
1317 if (FuncInfo.isExportedInst(V)) return;
1318
1319 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1320 CopyValueToVirtualRegister(V, Reg);
1321}
1322
Dan Gohman46510a72010-04-15 01:51:59 +00001323bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
Dan Gohman2048b852009-11-23 18:04:58 +00001324 const BasicBlock *FromBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001325 // The operands of the setcc have to be in this block. We don't know
1326 // how to export them from some other block.
Dan Gohman46510a72010-04-15 01:51:59 +00001327 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001328 // Can export from current BB.
1329 if (VI->getParent() == FromBB)
1330 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001331
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001332 // Is already exported, noop.
1333 return FuncInfo.isExportedInst(V);
1334 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001335
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001336 // If this is an argument, we can export it if the BB is the entry block or
1337 // if it is already exported.
1338 if (isa<Argument>(V)) {
1339 if (FromBB == &FromBB->getParent()->getEntryBlock())
1340 return true;
1341
1342 // Otherwise, can only export this if it is already exported.
1343 return FuncInfo.isExportedInst(V);
1344 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001345
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001346 // Otherwise, constants can always be exported.
1347 return true;
1348}
1349
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001350/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
Jakub Staszak25101bb2011-12-20 20:03:10 +00001351uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1352 const MachineBasicBlock *Dst) const {
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001353 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1354 if (!BPI)
1355 return 0;
Jakub Staszak95ece8e2011-07-29 20:05:36 +00001356 const BasicBlock *SrcBB = Src->getBasicBlock();
1357 const BasicBlock *DstBB = Dst->getBasicBlock();
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001358 return BPI->getEdgeWeight(SrcBB, DstBB);
1359}
1360
Jakub Staszakc8f34de2011-07-29 22:25:21 +00001361void SelectionDAGBuilder::
1362addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1363 uint32_t Weight /* = 0 */) {
1364 if (!Weight)
1365 Weight = getEdgeWeight(Src, Dst);
1366 Src->addSuccessor(Dst, Weight);
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001367}
1368
1369
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001370static bool InBlock(const Value *V, const BasicBlock *BB) {
1371 if (const Instruction *I = dyn_cast<Instruction>(V))
1372 return I->getParent() == BB;
1373 return true;
1374}
1375
Dan Gohmanc2277342008-10-17 21:16:08 +00001376/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1377/// This function emits a branch and is used at the leaves of an OR or an
1378/// AND operator tree.
1379///
1380void
Dan Gohman46510a72010-04-15 01:51:59 +00001381SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
Dan Gohman2048b852009-11-23 18:04:58 +00001382 MachineBasicBlock *TBB,
1383 MachineBasicBlock *FBB,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001384 MachineBasicBlock *CurBB,
1385 MachineBasicBlock *SwitchBB) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001386 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001387
Dan Gohmanc2277342008-10-17 21:16:08 +00001388 // If the leaf of the tree is a comparison, merge the condition into
1389 // the caseblock.
Dan Gohman46510a72010-04-15 01:51:59 +00001390 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001391 // The operands of the cmp have to be in this block. We don't know
1392 // how to export them from some other block. If this is the first block
1393 // of the sequence, no exporting is needed.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001394 if (CurBB == SwitchBB ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001395 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1396 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001397 ISD::CondCode Condition;
Dan Gohman46510a72010-04-15 01:51:59 +00001398 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001399 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohman46510a72010-04-15 01:51:59 +00001400 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001401 Condition = getFCmpCondCode(FC->getPredicate());
Nick Lewycky8a8d4792011-12-02 22:16:29 +00001402 if (TM.Options.NoNaNsFPMath)
1403 Condition = getFCmpCodeWithoutNaN(Condition);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001404 } else {
1405 Condition = ISD::SETEQ; // silence warning.
Torok Edwinc23197a2009-07-14 16:55:14 +00001406 llvm_unreachable("Unknown compare instruction");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001407 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001408
1409 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001410 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1411 SwitchCases.push_back(CB);
1412 return;
1413 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001414 }
1415
1416 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001417 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanc2277342008-10-17 21:16:08 +00001418 NULL, TBB, FBB, CurBB);
1419 SwitchCases.push_back(CB);
1420}
1421
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001422/// FindMergedConditions - If Cond is an expression like
Dan Gohman46510a72010-04-15 01:51:59 +00001423void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
Dan Gohman2048b852009-11-23 18:04:58 +00001424 MachineBasicBlock *TBB,
1425 MachineBasicBlock *FBB,
1426 MachineBasicBlock *CurBB,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001427 MachineBasicBlock *SwitchBB,
Dan Gohman2048b852009-11-23 18:04:58 +00001428 unsigned Opc) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001429 // If this node is not part of the or/and tree, emit it as a branch.
Dan Gohman46510a72010-04-15 01:51:59 +00001430 const Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001431 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001432 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1433 BOp->getParent() != CurBB->getBasicBlock() ||
1434 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1435 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Dan Gohman99be8ae2010-04-19 22:41:47 +00001436 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001437 return;
1438 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001439
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001440 // Create TmpBB after CurBB.
1441 MachineFunction::iterator BBI = CurBB;
1442 MachineFunction &MF = DAG.getMachineFunction();
1443 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1444 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001445
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001446 if (Opc == Instruction::Or) {
1447 // Codegen X | Y as:
1448 // jmp_if_X TBB
1449 // jmp TmpBB
1450 // TmpBB:
1451 // jmp_if_Y TBB
1452 // jmp FBB
1453 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001454
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001455 // Emit the LHS condition.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001456 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001457
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001458 // Emit the RHS condition into TmpBB.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001459 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001460 } else {
1461 assert(Opc == Instruction::And && "Unknown merge op!");
1462 // Codegen X & Y as:
1463 // jmp_if_X TmpBB
1464 // jmp FBB
1465 // TmpBB:
1466 // jmp_if_Y TBB
1467 // jmp FBB
1468 //
1469 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001470
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001471 // Emit the LHS condition.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001472 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001473
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001474 // Emit the RHS condition into TmpBB.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001475 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001476 }
1477}
1478
1479/// If the set of cases should be emitted as a series of branches, return true.
1480/// If we should emit this as a bunch of and/or'd together conditions, return
1481/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001482bool
Stephen Lin09f8ca32013-07-06 21:44:25 +00001483SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001484 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001485
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001486 // If this is two comparisons of the same values or'd or and'd together, they
1487 // will get folded into a single comparison, so don't emit two blocks.
1488 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1489 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1490 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1491 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1492 return false;
1493 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001494
Chris Lattner133ce872010-01-02 00:00:03 +00001495 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1496 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1497 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1498 Cases[0].CC == Cases[1].CC &&
1499 isa<Constant>(Cases[0].CmpRHS) &&
1500 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1501 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1502 return false;
1503 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1504 return false;
1505 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00001506
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001507 return true;
1508}
1509
Dan Gohman46510a72010-04-15 01:51:59 +00001510void SelectionDAGBuilder::visitBr(const BranchInst &I) {
Dan Gohman84023e02010-07-10 09:00:22 +00001511 MachineBasicBlock *BrMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001512
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001513 // Update machine-CFG edges.
1514 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1515
1516 // Figure out which block is immediately after the current one.
1517 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001518 MachineFunction::iterator BBI = BrMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001519 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001520 NextBlock = BBI;
1521
1522 if (I.isUnconditional()) {
1523 // Update machine-CFG edges.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001524 BrMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001525
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001526 // If this is not a fall-through branch, emit the branch.
Bill Wendling4533cac2010-01-28 21:51:40 +00001527 if (Succ0MBB != NextBlock)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001528 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001529 MVT::Other, getControlRoot(),
Bill Wendling4533cac2010-01-28 21:51:40 +00001530 DAG.getBasicBlock(Succ0MBB)));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001531
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001532 return;
1533 }
1534
1535 // If this condition is one of the special cases we handle, do special stuff
1536 // now.
Dan Gohman46510a72010-04-15 01:51:59 +00001537 const Value *CondVal = I.getCondition();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001538 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1539
1540 // If this is a series of conditions that are or'd or and'd together, emit
1541 // this as a sequence of branches instead of setcc's with and/or operations.
Chris Lattnerde189be2010-11-30 18:12:52 +00001542 // As long as jumps are not expensive, this should improve performance.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001543 // For example, instead of something like:
1544 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001545 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001546 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001547 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001548 // or C, F
1549 // jnz foo
1550 // Emit:
1551 // cmp A, B
1552 // je foo
1553 // cmp D, E
1554 // jle foo
1555 //
Dan Gohman46510a72010-04-15 01:51:59 +00001556 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00001557 if (!TM.getTargetLowering()->isJumpExpensive() &&
Chris Lattnerde189be2010-11-30 18:12:52 +00001558 BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001559 (BOp->getOpcode() == Instruction::And ||
1560 BOp->getOpcode() == Instruction::Or)) {
Dan Gohman99be8ae2010-04-19 22:41:47 +00001561 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1562 BOp->getOpcode());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001563 // If the compares in later blocks need to use values not currently
1564 // exported from this block, export them now. This block should always
1565 // be the first entry.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001566 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001567
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001568 // Allow some cases to be rejected.
1569 if (ShouldEmitAsBranches(SwitchCases)) {
1570 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1571 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1572 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1573 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001574
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001575 // Emit the branch for this block.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001576 visitSwitchCase(SwitchCases[0], BrMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001577 SwitchCases.erase(SwitchCases.begin());
1578 return;
1579 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001580
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001581 // Okay, we decided not to do this, remove any inserted MBB's and clear
1582 // SwitchCases.
1583 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001584 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001585
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001586 SwitchCases.clear();
1587 }
1588 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001589
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001590 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001591 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohman99be8ae2010-04-19 22:41:47 +00001592 NULL, Succ0MBB, Succ1MBB, BrMBB);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001593
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001594 // Use visitSwitchCase to actually insert the fast branch sequence for this
1595 // cond branch.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001596 visitSwitchCase(CB, BrMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001597}
1598
1599/// visitSwitchCase - Emits the necessary code to represent a single node in
1600/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001601void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1602 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001603 SDValue Cond;
1604 SDValue CondLHS = getValue(CB.CmpLHS);
Andrew Trickac6d9be2013-05-25 02:42:55 +00001605 SDLoc dl = getCurSDLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001606
1607 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001608 if (CB.CmpMHS == NULL) {
1609 // Fold "(X == true)" to X and "(X == false)" to !X to
1610 // handle common cases produced by branch lowering.
Owen Anderson5defacc2009-07-31 17:39:07 +00001611 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001612 CB.CC == ISD::SETEQ)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001613 Cond = CondLHS;
Owen Anderson5defacc2009-07-31 17:39:07 +00001614 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001615 CB.CC == ISD::SETEQ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001616 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001617 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001618 } else
Owen Anderson825b72b2009-08-11 20:47:22 +00001619 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001620 } else {
Bob Wilsondb3a9e62013-09-09 19:14:35 +00001621 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001622
Anton Korobeynikov23218582008-12-23 22:25:27 +00001623 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1624 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001625
1626 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Andersone50ed302009-08-10 22:56:29 +00001627 EVT VT = CmpOp.getValueType();
Stephen Lin155615d2013-07-08 00:37:03 +00001628
Bob Wilsondb3a9e62013-09-09 19:14:35 +00001629 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001630 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Bob Wilsondb3a9e62013-09-09 19:14:35 +00001631 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001632 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001633 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001634 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson825b72b2009-08-11 20:47:22 +00001635 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001636 DAG.getConstant(High-Low, VT), ISD::SETULE);
1637 }
1638 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001639
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001640 // Update successor info
Jakub Staszakc8f34de2011-07-29 22:25:21 +00001641 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
Jakob Stoklund Olesene7fdef42012-08-20 21:39:52 +00001642 // TrueBB and FalseBB are always different unless the incoming IR is
1643 // degenerate. This only happens when running llc on weird IR.
1644 if (CB.TrueBB != CB.FalseBB)
1645 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001646
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001647 // Set NextBlock to be the MBB immediately after the current one, if any.
1648 // This is used to avoid emitting unnecessary branches to the next block.
1649 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001650 MachineFunction::iterator BBI = SwitchBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001651 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001652 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001653
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001654 // If the lhs block is the next block, invert the condition so that we can
1655 // fall through to the lhs instead of the rhs block.
1656 if (CB.TrueBB == NextBlock) {
1657 std::swap(CB.TrueBB, CB.FalseBB);
1658 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001659 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001660 }
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001661
Dale Johannesenf5d97892009-02-04 01:48:28 +00001662 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00001663 MVT::Other, getControlRoot(), Cond,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001664 DAG.getBasicBlock(CB.TrueBB));
Bill Wendling87710f02009-12-21 23:47:40 +00001665
Evan Cheng266a99d2010-09-23 06:51:55 +00001666 // Insert the false branch. Do this even if it's a fall through branch,
1667 // this makes it easier to do DAG optimizations which require inverting
1668 // the branch condition.
1669 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1670 DAG.getBasicBlock(CB.FalseBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001671
1672 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001673}
1674
1675/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman2048b852009-11-23 18:04:58 +00001676void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001677 // Emit the code for the jump table
1678 assert(JT.Reg != -1U && "Should lower JT Header first!");
Bill Wendlingba54bca2013-06-19 21:36:55 +00001679 EVT PTy = TM.getTargetLowering()->getPointerTy();
Andrew Trickac6d9be2013-05-25 02:42:55 +00001680 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
Dale Johannesena04b7572009-02-03 23:04:43 +00001681 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001682 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Andrew Trickac6d9be2013-05-25 02:42:55 +00001683 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001684 MVT::Other, Index.getValue(1),
1685 Table, Index);
1686 DAG.setRoot(BrJumpTable);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001687}
1688
1689/// visitJumpTableHeader - This function emits necessary code to produce index
1690/// in the JumpTable from switch case.
Dan Gohman2048b852009-11-23 18:04:58 +00001691void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001692 JumpTableHeader &JTH,
1693 MachineBasicBlock *SwitchBB) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001694 // Subtract the lowest switch case value from the value being switched on and
1695 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001696 // difference between smallest and largest cases.
1697 SDValue SwitchOp = getValue(JTH.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001698 EVT VT = SwitchOp.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +00001699 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001700 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001701
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001702 // The SDNode we just created, which holds the value being switched on minus
Dan Gohmanf451cb82010-02-10 16:03:48 +00001703 // the smallest case value, needs to be copied to a virtual register so it
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001704 // can be used as an index into the jump table in a subsequent basic block.
1705 // This value may be smaller or larger than the target's pointer type, and
1706 // therefore require extension or truncating.
Bill Wendlingba54bca2013-06-19 21:36:55 +00001707 const TargetLowering *TLI = TM.getTargetLowering();
1708 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI->getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001709
Bill Wendlingba54bca2013-06-19 21:36:55 +00001710 unsigned JumpTableReg = FuncInfo.CreateReg(TLI->getPointerTy());
Andrew Trickac6d9be2013-05-25 02:42:55 +00001711 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
Dale Johannesena04b7572009-02-03 23:04:43 +00001712 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001713 JT.Reg = JumpTableReg;
1714
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001715 // Emit the range check for the jump table, and branch to the default block
1716 // for the switch statement if the value being switched on exceeds the largest
1717 // case in the switch.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001718 SDValue CMP = DAG.getSetCC(getCurSDLoc(),
Bill Wendlingba54bca2013-06-19 21:36:55 +00001719 TLI->getSetCCResultType(*DAG.getContext(),
1720 Sub.getValueType()),
Matt Arsenault225ed702013-05-18 00:21:46 +00001721 Sub,
1722 DAG.getConstant(JTH.Last - JTH.First,VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001723 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001724
1725 // Set NextBlock to be the MBB immediately after the current one, if any.
1726 // This is used to avoid emitting unnecessary branches to the next block.
1727 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001728 MachineFunction::iterator BBI = SwitchBB;
Bill Wendling87710f02009-12-21 23:47:40 +00001729
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001730 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001731 NextBlock = BBI;
1732
Andrew Trickac6d9be2013-05-25 02:42:55 +00001733 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001734 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001735 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001736
Bill Wendling4533cac2010-01-28 21:51:40 +00001737 if (JT.MBB != NextBlock)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001738 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001739 DAG.getBasicBlock(JT.MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001740
Bill Wendling87710f02009-12-21 23:47:40 +00001741 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001742}
1743
Michael Gottesman657484f2013-08-20 07:00:16 +00001744/// Codegen a new tail for a stack protector check ParentMBB which has had its
1745/// tail spliced into a stack protector check success bb.
1746///
1747/// For a high level explanation of how this fits into the stack protector
1748/// generation see the comment on the declaration of class
1749/// StackProtectorDescriptor.
1750void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1751 MachineBasicBlock *ParentBB) {
1752
1753 // First create the loads to the guard/stack slot for the comparison.
1754 const TargetLowering *TLI = TM.getTargetLowering();
1755 EVT PtrTy = TLI->getPointerTy();
1756
1757 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1758 int FI = MFI->getStackProtectorIndex();
1759
1760 const Value *IRGuard = SPD.getGuard();
1761 SDValue GuardPtr = getValue(IRGuard);
1762 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1763
1764 unsigned Align =
1765 TLI->getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1766 SDValue Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1767 GuardPtr, MachinePointerInfo(IRGuard, 0),
1768 true, false, false, Align);
1769
1770 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1771 StackSlotPtr,
1772 MachinePointerInfo::getFixedStack(FI),
1773 true, false, false, Align);
1774
1775 // Perform the comparison via a subtract/getsetcc.
1776 EVT VT = Guard.getValueType();
1777 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1778
1779 SDValue Cmp = DAG.getSetCC(getCurSDLoc(),
1780 TLI->getSetCCResultType(*DAG.getContext(),
1781 Sub.getValueType()),
1782 Sub, DAG.getConstant(0, VT),
1783 ISD::SETNE);
1784
1785 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1786 // branch to failure MBB.
1787 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1788 MVT::Other, StackSlot.getOperand(0),
1789 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1790 // Otherwise branch to success MBB.
1791 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1792 MVT::Other, BrCond,
1793 DAG.getBasicBlock(SPD.getSuccessMBB()));
1794
1795 DAG.setRoot(Br);
1796}
1797
1798/// Codegen the failure basic block for a stack protector check.
1799///
1800/// A failure stack protector machine basic block consists simply of a call to
1801/// __stack_chk_fail().
1802///
1803/// For a high level explanation of how this fits into the stack protector
1804/// generation see the comment on the declaration of class
1805/// StackProtectorDescriptor.
1806void
1807SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1808 const TargetLowering *TLI = TM.getTargetLowering();
1809 SDValue Chain = TLI->makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
1810 MVT::isVoid, 0, 0, false, getCurSDLoc(),
Michael Gottesman58a9b432013-08-22 23:45:24 +00001811 false, false).second;
Michael Gottesman657484f2013-08-20 07:00:16 +00001812 DAG.setRoot(Chain);
1813}
1814
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001815/// visitBitTestHeader - This function emits necessary code to produce value
1816/// suitable for "bit tests"
Dan Gohman99be8ae2010-04-19 22:41:47 +00001817void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1818 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001819 // Subtract the minimum value
1820 SDValue SwitchOp = getValue(B.SValue);
Patrik Hagglund34525f92012-12-11 11:14:33 +00001821 EVT VT = SwitchOp.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +00001822 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001823 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001824
1825 // Check range
Bill Wendlingba54bca2013-06-19 21:36:55 +00001826 const TargetLowering *TLI = TM.getTargetLowering();
Andrew Trickac6d9be2013-05-25 02:42:55 +00001827 SDValue RangeCmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlingba54bca2013-06-19 21:36:55 +00001828 TLI->getSetCCResultType(*DAG.getContext(),
Matt Arsenault225ed702013-05-18 00:21:46 +00001829 Sub.getValueType()),
Bill Wendling87710f02009-12-21 23:47:40 +00001830 Sub, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001831 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001832
Evan Chengd08e5b42011-01-06 01:02:44 +00001833 // Determine the type of the test operands.
1834 bool UsePtrType = false;
Bill Wendlingba54bca2013-06-19 21:36:55 +00001835 if (!TLI->isTypeLegal(VT))
Evan Chengd08e5b42011-01-06 01:02:44 +00001836 UsePtrType = true;
1837 else {
1838 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
Eli Friedman5c75af62011-10-12 22:46:45 +00001839 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
Evan Chengd08e5b42011-01-06 01:02:44 +00001840 // Switch table case range are encoded into series of masks.
1841 // Just use pointer type, it's guaranteed to fit.
1842 UsePtrType = true;
1843 break;
1844 }
1845 }
1846 if (UsePtrType) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00001847 VT = TLI->getPointerTy();
Andrew Trickac6d9be2013-05-25 02:42:55 +00001848 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
Evan Chengd08e5b42011-01-06 01:02:44 +00001849 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001850
Patrik Hagglunda61b17c2012-12-13 06:34:11 +00001851 B.RegVT = VT.getSimpleVT();
Patrik Hagglund8963fec2012-12-19 12:23:01 +00001852 B.Reg = FuncInfo.CreateReg(B.RegVT);
Andrew Trickac6d9be2013-05-25 02:42:55 +00001853 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
Evan Chengd08e5b42011-01-06 01:02:44 +00001854 B.Reg, Sub);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001855
1856 // Set NextBlock to be the MBB immediately after the current one, if any.
1857 // This is used to avoid emitting unnecessary branches to the next block.
1858 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001859 MachineFunction::iterator BBI = SwitchBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001860 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001861 NextBlock = BBI;
1862
1863 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1864
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001865 addSuccessorWithWeight(SwitchBB, B.Default);
1866 addSuccessorWithWeight(SwitchBB, MBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001867
Andrew Trickac6d9be2013-05-25 02:42:55 +00001868 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001869 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001870 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001871
Evan Cheng8c1f4322010-09-23 18:32:19 +00001872 if (MBB != NextBlock)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001873 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
Evan Cheng8c1f4322010-09-23 18:32:19 +00001874 DAG.getBasicBlock(MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001875
Bill Wendling87710f02009-12-21 23:47:40 +00001876 DAG.setRoot(BrRange);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001877}
1878
1879/// visitBitTestCase - this function produces one "bit test"
Evan Chengd08e5b42011-01-06 01:02:44 +00001880void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1881 MachineBasicBlock* NextMBB,
Manman Ren1a710fd2012-08-24 18:14:27 +00001882 uint32_t BranchWeightToNext,
Dan Gohman2048b852009-11-23 18:04:58 +00001883 unsigned Reg,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001884 BitTestCase &B,
1885 MachineBasicBlock *SwitchBB) {
Patrik Hagglund8963fec2012-12-19 12:23:01 +00001886 MVT VT = BB.RegVT;
Andrew Trickac6d9be2013-05-25 02:42:55 +00001887 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
Evan Chengd08e5b42011-01-06 01:02:44 +00001888 Reg, VT);
Dan Gohman8e0163a2010-06-24 02:06:24 +00001889 SDValue Cmp;
Benjamin Kramer3ff25512011-07-14 01:38:42 +00001890 unsigned PopCount = CountPopulation_64(B.Mask);
Bill Wendlingba54bca2013-06-19 21:36:55 +00001891 const TargetLowering *TLI = TM.getTargetLowering();
Benjamin Kramer3ff25512011-07-14 01:38:42 +00001892 if (PopCount == 1) {
Dan Gohman8e0163a2010-06-24 02:06:24 +00001893 // Testing for a single bit; just compare the shift count with what it
1894 // would need to be to shift a 1 bit in that position.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001895 Cmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlingba54bca2013-06-19 21:36:55 +00001896 TLI->getSetCCResultType(*DAG.getContext(), VT),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001897 ShiftOp,
Michael J. Spencerc6af2432013-05-24 22:23:49 +00001898 DAG.getConstant(countTrailingZeros(B.Mask), VT),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001899 ISD::SETEQ);
Benjamin Kramer3ff25512011-07-14 01:38:42 +00001900 } else if (PopCount == BB.Range) {
1901 // There is only one zero bit in the range, test for it directly.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001902 Cmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlingba54bca2013-06-19 21:36:55 +00001903 TLI->getSetCCResultType(*DAG.getContext(), VT),
Benjamin Kramer3ff25512011-07-14 01:38:42 +00001904 ShiftOp,
1905 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1906 ISD::SETNE);
Dan Gohman8e0163a2010-06-24 02:06:24 +00001907 } else {
1908 // Make desired shift
Andrew Trickac6d9be2013-05-25 02:42:55 +00001909 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
Evan Chengd08e5b42011-01-06 01:02:44 +00001910 DAG.getConstant(1, VT), ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001911
Dan Gohman8e0163a2010-06-24 02:06:24 +00001912 // Emit bit tests and jumps
Andrew Trickac6d9be2013-05-25 02:42:55 +00001913 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
Evan Chengd08e5b42011-01-06 01:02:44 +00001914 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00001915 Cmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlingba54bca2013-06-19 21:36:55 +00001916 TLI->getSetCCResultType(*DAG.getContext(), VT),
Evan Chengd08e5b42011-01-06 01:02:44 +00001917 AndOp, DAG.getConstant(0, VT),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001918 ISD::SETNE);
1919 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001920
Manman Ren1a710fd2012-08-24 18:14:27 +00001921 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1922 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1923 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1924 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001925
Andrew Trickac6d9be2013-05-25 02:42:55 +00001926 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001927 MVT::Other, getControlRoot(),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001928 Cmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001929
1930 // Set NextBlock to be the MBB immediately after the current one, if any.
1931 // This is used to avoid emitting unnecessary branches to the next block.
1932 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001933 MachineFunction::iterator BBI = SwitchBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001934 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001935 NextBlock = BBI;
1936
Evan Cheng8c1f4322010-09-23 18:32:19 +00001937 if (NextMBB != NextBlock)
Andrew Trickac6d9be2013-05-25 02:42:55 +00001938 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
Evan Cheng8c1f4322010-09-23 18:32:19 +00001939 DAG.getBasicBlock(NextMBB));
Bill Wendling0777e922009-12-21 21:59:52 +00001940
Bill Wendling87710f02009-12-21 23:47:40 +00001941 DAG.setRoot(BrAnd);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001942}
1943
Dan Gohman46510a72010-04-15 01:51:59 +00001944void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
Dan Gohman84023e02010-07-10 09:00:22 +00001945 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001946
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001947 // Retrieve successors.
1948 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1949 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1950
Gabor Greifb67e6b32009-01-15 11:10:44 +00001951 const Value *Callee(I.getCalledValue());
Nuno Lopes85b40892012-06-28 22:30:12 +00001952 const Function *Fn = dyn_cast<Function>(Callee);
Gabor Greifb67e6b32009-01-15 11:10:44 +00001953 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001954 visitInlineAsm(&I);
Nuno Lopes85b40892012-06-28 22:30:12 +00001955 else if (Fn && Fn->isIntrinsic()) {
1956 assert(Fn->getIntrinsicID() == Intrinsic::donothing);
Nuno Lopes4532bf62012-07-18 00:07:17 +00001957 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
Nuno Lopes85b40892012-06-28 22:30:12 +00001958 } else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001959 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001960
1961 // If the value of the invoke is used outside of its defining block, make it
1962 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001963 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001964
1965 // Update successor info
Chandler Carruthf2645682011-11-22 11:37:46 +00001966 addSuccessorWithWeight(InvokeMBB, Return);
1967 addSuccessorWithWeight(InvokeMBB, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001968
1969 // Drop into normal successor.
Andrew Trickac6d9be2013-05-25 02:42:55 +00001970 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00001971 MVT::Other, getControlRoot(),
1972 DAG.getBasicBlock(Return)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001973}
1974
Bill Wendlingdccc03b2011-07-31 06:30:59 +00001975void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
1976 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
1977}
1978
Bill Wendling2ac0e6b2011-08-17 21:56:44 +00001979void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
1980 assert(FuncInfo.MBB->isLandingPad() &&
1981 "Call to landingpad not in landing pad!");
1982
1983 MachineBasicBlock *MBB = FuncInfo.MBB;
1984 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
1985 AddLandingPadInfo(LP, MMI, MBB);
1986
Bill Wendlingbdf9db62012-02-13 23:47:16 +00001987 // If there aren't registers to copy the values into (e.g., during SjLj
1988 // exceptions), then don't bother to create these DAG nodes.
Bill Wendlingba54bca2013-06-19 21:36:55 +00001989 const TargetLowering *TLI = TM.getTargetLowering();
1990 if (TLI->getExceptionPointerRegister() == 0 &&
1991 TLI->getExceptionSelectorRegister() == 0)
Bill Wendlingbdf9db62012-02-13 23:47:16 +00001992 return;
1993
Bill Wendling2ac0e6b2011-08-17 21:56:44 +00001994 SmallVector<EVT, 2> ValueVTs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00001995 ComputeValueVTs(*TLI, LP.getType(), ValueVTs);
Jakob Stoklund Olesen918b7c82013-07-04 04:53:45 +00001996 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
Bill Wendling2ac0e6b2011-08-17 21:56:44 +00001997
Jakob Stoklund Olesen918b7c82013-07-04 04:53:45 +00001998 // Get the two live-in registers as SDValues. The physregs have already been
1999 // copied into virtual registers.
Bill Wendling2ac0e6b2011-08-17 21:56:44 +00002000 SDValue Ops[2];
Jakob Stoklund Olesen918b7c82013-07-04 04:53:45 +00002001 Ops[0] = DAG.getZExtOrTrunc(
2002 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2003 FuncInfo.ExceptionPointerVirtReg, TLI->getPointerTy()),
2004 getCurSDLoc(), ValueVTs[0]);
2005 Ops[1] = DAG.getZExtOrTrunc(
2006 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2007 FuncInfo.ExceptionSelectorVirtReg, TLI->getPointerTy()),
2008 getCurSDLoc(), ValueVTs[1]);
Bill Wendling2ac0e6b2011-08-17 21:56:44 +00002009
Jakob Stoklund Olesen918b7c82013-07-04 04:53:45 +00002010 // Merge into one.
Andrew Trickac6d9be2013-05-25 02:42:55 +00002011 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling2ac0e6b2011-08-17 21:56:44 +00002012 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
2013 &Ops[0], 2);
Jakob Stoklund Olesen918b7c82013-07-04 04:53:45 +00002014 setValue(&LP, Res);
Bill Wendling2ac0e6b2011-08-17 21:56:44 +00002015}
2016
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002017/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2018/// small case ranges).
Dan Gohman2048b852009-11-23 18:04:58 +00002019bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2020 CaseRecVector& WorkList,
Dan Gohman46510a72010-04-15 01:51:59 +00002021 const Value* SV,
Dan Gohman99be8ae2010-04-19 22:41:47 +00002022 MachineBasicBlock *Default,
2023 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002024 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002025 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002026 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00002027 return false;
2028
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002029 // Get the MachineFunction which holds the current MBB. This is used when
2030 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002031 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002032
2033 // Figure out which block is immediately after the current one.
2034 MachineBasicBlock *NextBlock = 0;
2035 MachineFunction::iterator BBI = CR.CaseBB;
2036
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002037 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002038 NextBlock = BBI;
2039
Manman Ren1a710fd2012-08-24 18:14:27 +00002040 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Benjamin Kramerce750f02010-11-22 09:45:38 +00002041 // If any two of the cases has the same destination, and if one value
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002042 // is the same as the other, but has one bit unset that the other has set,
2043 // use bit manipulation to do two compares at once. For example:
2044 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Benjamin Kramerce750f02010-11-22 09:45:38 +00002045 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2046 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2047 if (Size == 2 && CR.CaseBB == SwitchBB) {
2048 Case &Small = *CR.Range.first;
2049 Case &Big = *(CR.Range.second-1);
2050
2051 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2052 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2053 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2054
2055 // Check that there is only one bit different.
2056 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2057 (SmallValue | BigValue) == BigValue) {
2058 // Isolate the common bit.
2059 APInt CommonBit = BigValue & ~SmallValue;
2060 assert((SmallValue | CommonBit) == BigValue &&
2061 CommonBit.countPopulation() == 1 && "Not a common bit?");
2062
2063 SDValue CondLHS = getValue(SV);
2064 EVT VT = CondLHS.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +00002065 SDLoc DL = getCurSDLoc();
Benjamin Kramerce750f02010-11-22 09:45:38 +00002066
2067 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2068 DAG.getConstant(CommonBit, VT));
2069 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2070 Or, DAG.getConstant(BigValue, VT),
2071 ISD::SETEQ);
2072
2073 // Update successor info.
Manman Ren1a710fd2012-08-24 18:14:27 +00002074 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2075 addSuccessorWithWeight(SwitchBB, Small.BB,
2076 Small.ExtraWeight + Big.ExtraWeight);
2077 addSuccessorWithWeight(SwitchBB, Default,
2078 // The default destination is the first successor in IR.
2079 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
Benjamin Kramerce750f02010-11-22 09:45:38 +00002080
2081 // Insert the true branch.
2082 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2083 getControlRoot(), Cond,
2084 DAG.getBasicBlock(Small.BB));
2085
2086 // Insert the false branch.
2087 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2088 DAG.getBasicBlock(Default));
2089
2090 DAG.setRoot(BrCond);
2091 return true;
2092 }
2093 }
2094 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002095
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002096 // Order cases by weight so the most likely case will be checked first.
Manman Ren1a710fd2012-08-24 18:14:27 +00002097 uint32_t UnhandledWeights = 0;
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002098 if (BPI) {
2099 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
Manman Ren1a710fd2012-08-24 18:14:27 +00002100 uint32_t IWeight = I->ExtraWeight;
2101 UnhandledWeights += IWeight;
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002102 for (CaseItr J = CR.Range.first; J < I; ++J) {
Manman Ren1a710fd2012-08-24 18:14:27 +00002103 uint32_t JWeight = J->ExtraWeight;
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002104 if (IWeight > JWeight)
2105 std::swap(*I, *J);
2106 }
2107 }
2108 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002109 // Rearrange the case blocks so that the last one falls through if possible.
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002110 Case &BackCase = *(CR.Range.second-1);
Benjamin Kramer5db954d2012-05-26 21:19:12 +00002111 if (Size > 1 &&
2112 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002113 // The last case block won't fall through into 'NextBlock' if we emit the
2114 // branches in this order. See if rearranging a case value would help.
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002115 // We start at the bottom as it's the case with the least weight.
Stephen Lin09f8ca32013-07-06 21:44:25 +00002116 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002117 if (I->BB == NextBlock) {
2118 std::swap(*I, BackCase);
2119 break;
2120 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002121 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002122
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002123 // Create a CaseBlock record representing a conditional branch to
2124 // the Case's target mbb if the value being switched on SV is equal
2125 // to C.
2126 MachineBasicBlock *CurBlock = CR.CaseBB;
2127 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2128 MachineBasicBlock *FallThrough;
2129 if (I != E-1) {
2130 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2131 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002132
2133 // Put SV in a virtual register to make it available from the new blocks.
2134 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002135 } else {
2136 // If the last case doesn't match, go to the default block.
2137 FallThrough = Default;
2138 }
2139
Dan Gohman46510a72010-04-15 01:51:59 +00002140 const Value *RHS, *LHS, *MHS;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002141 ISD::CondCode CC;
2142 if (I->High == I->Low) {
2143 // This is just small small case range :) containing exactly 1 case
2144 CC = ISD::SETEQ;
2145 LHS = SV; RHS = I->High; MHS = NULL;
2146 } else {
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002147 CC = ISD::SETLE;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002148 LHS = I->Low; MHS = SV; RHS = I->High;
2149 }
Jakub Staszakc8f34de2011-07-29 22:25:21 +00002150
Manman Ren1a710fd2012-08-24 18:14:27 +00002151 // The false weight should be sum of all un-handled cases.
2152 UnhandledWeights -= I->ExtraWeight;
Jakub Staszakc8f34de2011-07-29 22:25:21 +00002153 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2154 /* me */ CurBlock,
Manman Ren1a710fd2012-08-24 18:14:27 +00002155 /* trueweight */ I->ExtraWeight,
2156 /* falseweight */ UnhandledWeights);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002157
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002158 // If emitting the first comparison, just call visitSwitchCase to emit the
2159 // code into the current block. Otherwise, push the CaseBlock onto the
2160 // vector to be later processed by SDISel, and insert the node's MBB
2161 // before the next MBB.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002162 if (CurBlock == SwitchBB)
2163 visitSwitchCase(CB, SwitchBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002164 else
2165 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002166
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002167 CurBlock = FallThrough;
2168 }
2169
2170 return true;
2171}
2172
2173static inline bool areJTsAllowed(const TargetLowering &TLI) {
Evan Cheng769951f2012-07-02 22:39:56 +00002174 return TLI.supportJumpTables() &&
Owen Anderson825b72b2009-08-11 20:47:22 +00002175 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2176 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002177}
Anton Korobeynikov23218582008-12-23 22:25:27 +00002178
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002179static APInt ComputeRange(const APInt &First, const APInt &Last) {
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002180 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002181 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002182 return (LastExt - FirstExt + 1ULL);
2183}
2184
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002185/// handleJTSwitchCase - Emit jumptable for current switch case range
Chris Lattnerc3ab3882011-09-09 22:06:59 +00002186bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2187 CaseRecVector &WorkList,
2188 const Value *SV,
2189 MachineBasicBlock *Default,
Dan Gohman99be8ae2010-04-19 22:41:47 +00002190 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002191 Case& FrontCase = *CR.Range.first;
2192 Case& BackCase = *(CR.Range.second-1);
2193
Chris Lattnere880efe2009-11-07 07:50:34 +00002194 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2195 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002196
Chris Lattnere880efe2009-11-07 07:50:34 +00002197 APInt TSize(First.getBitWidth(), 0);
Chris Lattnerc3ab3882011-09-09 22:06:59 +00002198 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002199 TSize += I->size();
2200
Bill Wendlingba54bca2013-06-19 21:36:55 +00002201 const TargetLowering *TLI = TM.getTargetLowering();
2202 if (!areJTsAllowed(*TLI) || TSize.ult(TLI->getMinimumJumpTableEntries()))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002203 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002204
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002205 APInt Range = ComputeRange(First, Last);
Jakob Stoklund Olesen79443912011-10-26 01:47:48 +00002206 // The density is TSize / Range. Require at least 40%.
2207 // It should not be possible for IntTSize to saturate for sane code, but make
2208 // sure we handle Range saturation correctly.
2209 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2210 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2211 if (IntTSize * 10 < IntRange * 4)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002212 return false;
2213
David Greene4b69d992010-01-05 01:24:57 +00002214 DEBUG(dbgs() << "Lowering jump table\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002215 << "First entry: " << First << ". Last entry: " << Last << '\n'
Jakob Stoklund Olesen79443912011-10-26 01:47:48 +00002216 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002217
2218 // Get the MachineFunction which holds the current MBB. This is used when
2219 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002220 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002221
2222 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002223 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00002224 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002225
2226 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2227
2228 // Create a new basic block to hold the code for loading the address
2229 // of the jump table, and jumping to it. Update successor information;
2230 // we will either branch to the default case for the switch, or the jump
2231 // table.
2232 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2233 CurMF->insert(BBI, JumpTableBB);
Jakub Staszak7cc2b072011-06-16 20:22:37 +00002234
2235 addSuccessorWithWeight(CR.CaseBB, Default);
2236 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002237
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002238 // Build a vector of destination BBs, corresponding to each target
2239 // of the jump table. If the value of the jump table slot corresponds to
2240 // a case statement, push the case's BB onto the vector, otherwise, push
2241 // the default BB.
2242 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002243 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002244 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Chris Lattner071c62f2010-01-25 23:26:13 +00002245 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2246 const APInt &High = cast<ConstantInt>(I->High)->getValue();
Anton Korobeynikov23218582008-12-23 22:25:27 +00002247
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002248 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002249 DestBBs.push_back(I->BB);
2250 if (TEI==High)
2251 ++I;
2252 } else {
2253 DestBBs.push_back(Default);
2254 }
2255 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002256
Manman Ren1a710fd2012-08-24 18:14:27 +00002257 // Calculate weight for each unique destination in CR.
2258 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2259 if (FuncInfo.BPI)
2260 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2261 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2262 DestWeights.find(I->BB);
Stephen Lin155615d2013-07-08 00:37:03 +00002263 if (Itr != DestWeights.end())
Manman Ren1a710fd2012-08-24 18:14:27 +00002264 Itr->second += I->ExtraWeight;
2265 else
2266 DestWeights[I->BB] = I->ExtraWeight;
2267 }
2268
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002269 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002270 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2271 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002272 E = DestBBs.end(); I != E; ++I) {
2273 if (!SuccsHandled[(*I)->getNumber()]) {
2274 SuccsHandled[(*I)->getNumber()] = true;
Manman Ren1a710fd2012-08-24 18:14:27 +00002275 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2276 DestWeights.find(*I);
2277 addSuccessorWithWeight(JumpTableBB, *I,
2278 Itr != DestWeights.end() ? Itr->second : 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002279 }
2280 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002281
Bob Wilsond1ec31d2010-03-18 18:42:41 +00002282 // Create a jump table index for this jump table.
Bill Wendlingba54bca2013-06-19 21:36:55 +00002283 unsigned JTEncoding = TLI->getJumpTableEncoding();
Chris Lattner071c62f2010-01-25 23:26:13 +00002284 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
Bob Wilsond1ec31d2010-03-18 18:42:41 +00002285 ->createJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002286
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002287 // Set the jump table information so that we can codegen it as a second
2288 // MachineBasicBlock
2289 JumpTable JT(-1U, JTI, JumpTableBB, Default);
Dan Gohman99be8ae2010-04-19 22:41:47 +00002290 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2291 if (CR.CaseBB == SwitchBB)
2292 visitJumpTableHeader(JT, JTH, SwitchBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002293
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002294 JTCases.push_back(JumpTableBlock(JTH, JT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002295 return true;
2296}
2297
2298/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2299/// 2 subtrees.
Dan Gohman2048b852009-11-23 18:04:58 +00002300bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2301 CaseRecVector& WorkList,
Dan Gohman46510a72010-04-15 01:51:59 +00002302 const Value* SV,
Stephen Lin09f8ca32013-07-06 21:44:25 +00002303 MachineBasicBlock* Default,
2304 MachineBasicBlock* SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002305 // Get the MachineFunction which holds the current MBB. This is used when
2306 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002307 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002308
2309 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002310 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00002311 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002312
2313 Case& FrontCase = *CR.Range.first;
2314 Case& BackCase = *(CR.Range.second-1);
2315 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2316
2317 // Size is the number of Cases represented by this range.
2318 unsigned Size = CR.Range.second - CR.Range.first;
2319
Chris Lattnere880efe2009-11-07 07:50:34 +00002320 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2321 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002322 double FMetric = 0;
2323 CaseItr Pivot = CR.Range.first + Size/2;
2324
2325 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2326 // (heuristically) allow us to emit JumpTable's later.
Chris Lattnere880efe2009-11-07 07:50:34 +00002327 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002328 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2329 I!=E; ++I)
2330 TSize += I->size();
2331
Chris Lattnere880efe2009-11-07 07:50:34 +00002332 APInt LSize = FrontCase.size();
2333 APInt RSize = TSize-LSize;
David Greene4b69d992010-01-05 01:24:57 +00002334 DEBUG(dbgs() << "Selecting best pivot: \n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002335 << "First: " << First << ", Last: " << Last <<'\n'
2336 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002337 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2338 J!=E; ++I, ++J) {
Chris Lattnere880efe2009-11-07 07:50:34 +00002339 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2340 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002341 APInt Range = ComputeRange(LEnd, RBegin);
Stepan Dyatkovskiyc2c52a62012-05-15 06:50:18 +00002342 assert((Range - 2ULL).isNonNegative() &&
2343 "Invalid case distance");
Chris Lattnerc3e4e592011-04-09 06:57:13 +00002344 // Use volatile double here to avoid excess precision issues on some hosts,
2345 // e.g. that use 80-bit X87 registers.
2346 volatile double LDensity =
2347 (double)LSize.roundToDouble() /
Chris Lattnere880efe2009-11-07 07:50:34 +00002348 (LEnd - First + 1ULL).roundToDouble();
Chris Lattnerc3e4e592011-04-09 06:57:13 +00002349 volatile double RDensity =
2350 (double)RSize.roundToDouble() /
Chris Lattnere880efe2009-11-07 07:50:34 +00002351 (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002352 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002353 // Should always split in some non-trivial place
David Greene4b69d992010-01-05 01:24:57 +00002354 DEBUG(dbgs() <<"=>Step\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002355 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2356 << "LDensity: " << LDensity
2357 << ", RDensity: " << RDensity << '\n'
2358 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002359 if (FMetric < Metric) {
2360 Pivot = J;
2361 FMetric = Metric;
David Greene4b69d992010-01-05 01:24:57 +00002362 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002363 }
2364
2365 LSize += J->size();
2366 RSize -= J->size();
2367 }
Bill Wendlingba54bca2013-06-19 21:36:55 +00002368
2369 const TargetLowering *TLI = TM.getTargetLowering();
2370 if (areJTsAllowed(*TLI)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002371 // If our case is dense we *really* should handle it earlier!
2372 assert((FMetric > 0) && "Should handle dense range earlier!");
2373 } else {
2374 Pivot = CR.Range.first + Size/2;
2375 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002376
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002377 CaseRange LHSR(CR.Range.first, Pivot);
2378 CaseRange RHSR(Pivot, CR.Range.second);
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002379 const Constant *C = Pivot->Low;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002380 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002381
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002382 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002383 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002384 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002385 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002386 // Pivot's Value, then we can branch directly to the LHS's Target,
2387 // rather than creating a leaf node for it.
2388 if ((LHSR.second - LHSR.first) == 1 &&
2389 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00002390 cast<ConstantInt>(C)->getValue() ==
2391 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002392 TrueBB = LHSR.first->BB;
2393 } else {
2394 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2395 CurMF->insert(BBI, TrueBB);
2396 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002397
2398 // Put SV in a virtual register to make it available from the new blocks.
2399 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002400 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002401
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002402 // Similar to the optimization above, if the Value being switched on is
2403 // known to be less than the Constant CR.LT, and the current Case Value
2404 // is CR.LT - 1, then we can branch directly to the target block for
2405 // the current Case Value, rather than emitting a RHS leaf node for it.
2406 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00002407 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2408 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002409 FalseBB = RHSR.first->BB;
2410 } else {
2411 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2412 CurMF->insert(BBI, FalseBB);
2413 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002414
2415 // Put SV in a virtual register to make it available from the new blocks.
2416 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002417 }
2418
2419 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002420 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002421 // Otherwise, branch to LHS.
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002422 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002423
Dan Gohman99be8ae2010-04-19 22:41:47 +00002424 if (CR.CaseBB == SwitchBB)
2425 visitSwitchCase(CB, SwitchBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002426 else
2427 SwitchCases.push_back(CB);
2428
2429 return true;
2430}
2431
2432/// handleBitTestsSwitchCase - if current case range has few destination and
2433/// range span less, than machine word bitwidth, encode case range into series
2434/// of masks and emit bit tests with these masks.
Dan Gohman2048b852009-11-23 18:04:58 +00002435bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2436 CaseRecVector& WorkList,
Dan Gohman46510a72010-04-15 01:51:59 +00002437 const Value* SV,
Dan Gohman99be8ae2010-04-19 22:41:47 +00002438 MachineBasicBlock* Default,
Stephen Lin09f8ca32013-07-06 21:44:25 +00002439 MachineBasicBlock* SwitchBB) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00002440 const TargetLowering *TLI = TM.getTargetLowering();
2441 EVT PTy = TLI->getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002442 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002443
2444 Case& FrontCase = *CR.Range.first;
2445 Case& BackCase = *(CR.Range.second-1);
2446
2447 // Get the MachineFunction which holds the current MBB. This is used when
2448 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002449 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002450
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00002451 // If target does not have legal shift left, do not emit bit tests at all.
Matt Arsenault599c0af2013-10-21 19:24:15 +00002452 if (!TLI->isOperationLegal(ISD::SHL, PTy))
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00002453 return false;
2454
Anton Korobeynikov23218582008-12-23 22:25:27 +00002455 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002456 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2457 I!=E; ++I) {
2458 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002459 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002460 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002461
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002462 // Count unique destinations
2463 SmallSet<MachineBasicBlock*, 4> Dests;
2464 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2465 Dests.insert(I->BB);
2466 if (Dests.size() > 3)
2467 // Don't bother the code below, if there are too much unique destinations
2468 return false;
2469 }
David Greene4b69d992010-01-05 01:24:57 +00002470 DEBUG(dbgs() << "Total number of unique destinations: "
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002471 << Dests.size() << '\n'
2472 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00002473
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002474 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002475 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2476 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002477 APInt cmpRange = maxValue - minValue;
2478
David Greene4b69d992010-01-05 01:24:57 +00002479 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002480 << "Low bound: " << minValue << '\n'
2481 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00002482
Dan Gohmane0567812010-04-08 23:03:40 +00002483 if (cmpRange.uge(IntPtrBits) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002484 (!(Dests.size() == 1 && numCmps >= 3) &&
2485 !(Dests.size() == 2 && numCmps >= 5) &&
2486 !(Dests.size() >= 3 && numCmps >= 6)))
2487 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002488
David Greene4b69d992010-01-05 01:24:57 +00002489 DEBUG(dbgs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00002490 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2491
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002492 // Optimize the case where all the case values fit in a
2493 // word without having to subtract minValue. In this case,
2494 // we can optimize away the subtraction.
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002495 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002496 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002497 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002498 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002499 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002500
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002501 CaseBitsVector CasesBits;
2502 unsigned i, count = 0;
2503
2504 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2505 MachineBasicBlock* Dest = I->BB;
2506 for (i = 0; i < count; ++i)
2507 if (Dest == CasesBits[i].BB)
2508 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002509
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002510 if (i == count) {
2511 assert((count < 3) && "Too much destinations to test!");
Manman Ren1a710fd2012-08-24 18:14:27 +00002512 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002513 count++;
2514 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002515
2516 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2517 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2518
2519 uint64_t lo = (lowValue - lowBound).getZExtValue();
2520 uint64_t hi = (highValue - lowBound).getZExtValue();
Manman Ren1a710fd2012-08-24 18:14:27 +00002521 CasesBits[i].ExtraWeight += I->ExtraWeight;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002522
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002523 for (uint64_t j = lo; j <= hi; j++) {
2524 CasesBits[i].Mask |= 1ULL << j;
2525 CasesBits[i].Bits++;
2526 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002527
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002528 }
2529 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00002530
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002531 BitTestInfo BTC;
2532
2533 // Figure out which block is immediately after the current one.
2534 MachineFunction::iterator BBI = CR.CaseBB;
2535 ++BBI;
2536
2537 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2538
David Greene4b69d992010-01-05 01:24:57 +00002539 DEBUG(dbgs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002540 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
David Greene4b69d992010-01-05 01:24:57 +00002541 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002542 << ", Bits: " << CasesBits[i].Bits
2543 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002544
2545 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2546 CurMF->insert(BBI, CaseBB);
2547 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2548 CaseBB,
Manman Ren1a710fd2012-08-24 18:14:27 +00002549 CasesBits[i].BB, CasesBits[i].ExtraWeight));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002550
2551 // Put SV in a virtual register to make it available from the new blocks.
2552 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002553 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002554
2555 BitTestBlock BTB(lowBound, cmpRange, SV,
Evan Chengd08e5b42011-01-06 01:02:44 +00002556 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002557 CR.CaseBB, Default, BTC);
2558
Dan Gohman99be8ae2010-04-19 22:41:47 +00002559 if (CR.CaseBB == SwitchBB)
2560 visitBitTestHeader(BTB, SwitchBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002561
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002562 BitTestCases.push_back(BTB);
2563
2564 return true;
2565}
2566
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002567/// Clusterify - Transform simple list of Cases into list of CaseRange's
Dan Gohman2048b852009-11-23 18:04:58 +00002568size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2569 const SwitchInst& SI) {
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002570 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002571
Manman Ren1a710fd2012-08-24 18:14:27 +00002572 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002573 // Start with "simple" cases
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002574 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002575 i != e; ++i) {
2576 const BasicBlock *SuccBB = i.getCaseSuccessor();
Jakub Staszakc8f34de2011-07-29 22:25:21 +00002577 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2578
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002579 uint32_t ExtraWeight =
2580 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2581
2582 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2583 SMBB, ExtraWeight));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002584 }
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002585 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Stephen Lin155615d2013-07-08 00:37:03 +00002586
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002587 // Merge case into clusters
2588 if (Cases.size() >= 2)
2589 // Must recompute end() each iteration because it may be
2590 // invalidated by erase if we hold on to it
2591 for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
2592 J != Cases.end(); ) {
2593 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2594 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2595 MachineBasicBlock* nextBB = J->BB;
2596 MachineBasicBlock* currentBB = I->BB;
Stephen Lin155615d2013-07-08 00:37:03 +00002597
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002598 // If the two neighboring cases go to the same destination, merge them
2599 // into a single case.
2600 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2601 I->High = J->High;
2602 I->ExtraWeight += J->ExtraWeight;
2603 J = Cases.erase(J);
2604 } else {
2605 I = J++;
2606 }
2607 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002608
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002609 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2610 if (I->Low != I->High)
2611 // A range counts double, since it requires two compares.
2612 ++numCmps;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002613 }
2614
2615 return numCmps;
2616}
2617
Jakob Stoklund Olesen2622f462010-09-30 19:44:31 +00002618void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2619 MachineBasicBlock *Last) {
2620 // Update JTCases.
2621 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2622 if (JTCases[i].first.HeaderBB == First)
2623 JTCases[i].first.HeaderBB = Last;
2624
2625 // Update BitTestCases.
2626 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2627 if (BitTestCases[i].Parent == First)
2628 BitTestCases[i].Parent = Last;
2629}
2630
Dan Gohman46510a72010-04-15 01:51:59 +00002631void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
Dan Gohman84023e02010-07-10 09:00:22 +00002632 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00002633
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002634 // Figure out which block is immediately after the current one.
2635 MachineBasicBlock *NextBlock = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002636 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2637
2638 // If there is only the default destination, branch to it if it is not the
2639 // next basic block. Otherwise, just fall through.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002640 if (!SI.getNumCases()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002641 // Update machine-CFG edges.
2642
2643 // If this is not a fall-through branch, emit the branch.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002644 SwitchMBB->addSuccessor(Default);
Bill Wendling4533cac2010-01-28 21:51:40 +00002645 if (Default != NextBlock)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002646 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00002647 MVT::Other, getControlRoot(),
2648 DAG.getBasicBlock(Default)));
Bill Wendling49fcff82009-12-21 22:30:11 +00002649
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002650 return;
2651 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002652
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002653 // If there are any non-default case statements, create a vector of Cases
2654 // representing each one, and sort the vector so that we can efficiently
2655 // create a binary search tree from them.
2656 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002657 size_t numCmps = Clusterify(Cases, SI);
David Greene4b69d992010-01-05 01:24:57 +00002658 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002659 << ". Total compares: " << numCmps << '\n');
Duncan Sands17001ce2011-10-18 12:44:00 +00002660 (void)numCmps;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002661
2662 // Get the Value to be switched on and default basic blocks, which will be
2663 // inserted into CaseBlock records, representing basic blocks in the binary
2664 // search tree.
Eli Friedmanbb5a7442011-09-29 20:21:17 +00002665 const Value *SV = SI.getCondition();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002666
2667 // Push the initial CaseRec onto the worklist
2668 CaseRecVector WorkList;
Dan Gohman99be8ae2010-04-19 22:41:47 +00002669 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2670 CaseRange(Cases.begin(),Cases.end())));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002671
2672 while (!WorkList.empty()) {
2673 // Grab a record representing a case range to process off the worklist
2674 CaseRec CR = WorkList.back();
2675 WorkList.pop_back();
2676
Dan Gohman99be8ae2010-04-19 22:41:47 +00002677 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002678 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002679
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002680 // If the range has few cases (two or less) emit a series of specific
2681 // tests.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002682 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002683 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002684
Sebastian Pop1a37d7e2012-09-25 20:35:36 +00002685 // If the switch has more than N blocks, and is at least 40% dense, and the
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002686 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002687 // lowering the switch to a binary tree of conditional branches.
Sebastian Pop1a37d7e2012-09-25 20:35:36 +00002688 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
Dan Gohman99be8ae2010-04-19 22:41:47 +00002689 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002690 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002691
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002692 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2693 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002694 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002695 }
2696}
2697
Dan Gohman46510a72010-04-15 01:51:59 +00002698void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
Dan Gohman84023e02010-07-10 09:00:22 +00002699 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00002700
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002701 // Update machine-CFG edges with unique successors.
Nadav Rotemee0ce152012-10-23 21:05:33 +00002702 SmallSet<BasicBlock*, 32> Done;
2703 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2704 BasicBlock *BB = I.getSuccessor(i);
2705 bool Inserted = Done.insert(BB);
2706 if (!Inserted)
2707 continue;
2708
2709 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
Jakub Staszak7cc2b072011-06-16 20:22:37 +00002710 addSuccessorWithWeight(IndirectBrMBB, Succ);
2711 }
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002712
Andrew Trickac6d9be2013-05-25 02:42:55 +00002713 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00002714 MVT::Other, getControlRoot(),
2715 getValue(I.getAddress())));
Bill Wendling49fcff82009-12-21 22:30:11 +00002716}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002717
Dan Gohman46510a72010-04-15 01:51:59 +00002718void SelectionDAGBuilder::visitFSub(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002719 // -0.0 - X --> fneg
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002720 Type *Ty = I.getType();
Chris Lattner2ca5c862011-02-15 00:14:00 +00002721 if (isa<Constant>(I.getOperand(0)) &&
2722 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2723 SDValue Op2 = getValue(I.getOperand(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00002724 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
Chris Lattner2ca5c862011-02-15 00:14:00 +00002725 Op2.getValueType(), Op2));
2726 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002727 }
Bill Wendling49fcff82009-12-21 22:30:11 +00002728
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002729 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002730}
2731
Dan Gohman46510a72010-04-15 01:51:59 +00002732void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002733 SDValue Op1 = getValue(I.getOperand(0));
2734 SDValue Op2 = getValue(I.getOperand(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00002735 setValue(&I, DAG.getNode(OpCode, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00002736 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002737}
2738
Dan Gohman46510a72010-04-15 01:51:59 +00002739void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002740 SDValue Op1 = getValue(I.getOperand(0));
2741 SDValue Op2 = getValue(I.getOperand(1));
Owen Anderson95771af2011-02-25 21:41:48 +00002742
Bill Wendlingba54bca2013-06-19 21:36:55 +00002743 EVT ShiftTy = TM.getTargetLowering()->getShiftAmountTy(Op2.getValueType());
Owen Anderson95771af2011-02-25 21:41:48 +00002744
Chris Lattnerd3027732011-02-13 09:02:52 +00002745 // Coerce the shift amount to the right type if we can.
2746 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
Chris Lattner915eeb42011-02-13 09:10:56 +00002747 unsigned ShiftSize = ShiftTy.getSizeInBits();
2748 unsigned Op2Size = Op2.getValueType().getSizeInBits();
Andrew Trickac6d9be2013-05-25 02:42:55 +00002749 SDLoc DL = getCurSDLoc();
Owen Anderson95771af2011-02-25 21:41:48 +00002750
Dan Gohman57fc82d2009-04-09 03:51:29 +00002751 // If the operand is smaller than the shift count type, promote it.
Chris Lattnerd3027732011-02-13 09:02:52 +00002752 if (ShiftSize > Op2Size)
2753 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
Owen Anderson95771af2011-02-25 21:41:48 +00002754
Dan Gohman57fc82d2009-04-09 03:51:29 +00002755 // If the operand is larger than the shift count type but the shift
2756 // count type has enough bits to represent any shift value, truncate
2757 // it now. This is a common case and it exposes the truncate to
2758 // optimization early.
Chris Lattnerd3027732011-02-13 09:02:52 +00002759 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2760 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2761 // Otherwise we'll need to temporarily settle for some other convenient
Chris Lattnere0751182011-02-13 19:09:16 +00002762 // type. Type legalization will make adjustments once the shiftee is split.
Chris Lattnerd3027732011-02-13 09:02:52 +00002763 else
Chris Lattnere0751182011-02-13 19:09:16 +00002764 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002765 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002766
Andrew Trickac6d9be2013-05-25 02:42:55 +00002767 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00002768 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002769}
2770
Benjamin Kramer9c640302011-07-08 10:31:30 +00002771void SelectionDAGBuilder::visitSDiv(const User &I) {
Benjamin Kramer9c640302011-07-08 10:31:30 +00002772 SDValue Op1 = getValue(I.getOperand(0));
2773 SDValue Op2 = getValue(I.getOperand(1));
2774
2775 // Turn exact SDivs into multiplications.
2776 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2777 // exact bit.
Benjamin Kramer3492a4a2011-07-08 12:08:24 +00002778 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2779 !isa<ConstantSDNode>(Op1) &&
Benjamin Kramer9c640302011-07-08 10:31:30 +00002780 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
Bill Wendlingba54bca2013-06-19 21:36:55 +00002781 setValue(&I, TM.getTargetLowering()->BuildExactSDIV(Op1, Op2,
2782 getCurSDLoc(), DAG));
Benjamin Kramer9c640302011-07-08 10:31:30 +00002783 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00002784 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
Benjamin Kramer9c640302011-07-08 10:31:30 +00002785 Op1, Op2));
2786}
2787
Dan Gohman46510a72010-04-15 01:51:59 +00002788void SelectionDAGBuilder::visitICmp(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002789 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
Dan Gohman46510a72010-04-15 01:51:59 +00002790 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002791 predicate = IC->getPredicate();
Dan Gohman46510a72010-04-15 01:51:59 +00002792 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002793 predicate = ICmpInst::Predicate(IC->getPredicate());
2794 SDValue Op1 = getValue(I.getOperand(0));
2795 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002796 ISD::CondCode Opcode = getICmpCondCode(predicate);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002797
Bill Wendlingba54bca2013-06-19 21:36:55 +00002798 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002799 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002800}
2801
Dan Gohman46510a72010-04-15 01:51:59 +00002802void SelectionDAGBuilder::visitFCmp(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002803 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
Dan Gohman46510a72010-04-15 01:51:59 +00002804 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002805 predicate = FC->getPredicate();
Dan Gohman46510a72010-04-15 01:51:59 +00002806 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002807 predicate = FCmpInst::Predicate(FC->getPredicate());
2808 SDValue Op1 = getValue(I.getOperand(0));
2809 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002810 ISD::CondCode Condition = getFCmpCondCode(predicate);
Nick Lewycky8a8d4792011-12-02 22:16:29 +00002811 if (TM.Options.NoNaNsFPMath)
2812 Condition = getFCmpCodeWithoutNaN(Condition);
Bill Wendlingba54bca2013-06-19 21:36:55 +00002813 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002814 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002815}
2816
Dan Gohman46510a72010-04-15 01:51:59 +00002817void SelectionDAGBuilder::visitSelect(const User &I) {
Owen Andersone50ed302009-08-10 22:56:29 +00002818 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00002819 ComputeValueVTs(*TM.getTargetLowering(), I.getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002820 unsigned NumValues = ValueVTs.size();
Bill Wendling49fcff82009-12-21 22:30:11 +00002821 if (NumValues == 0) return;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002822
Bill Wendling49fcff82009-12-21 22:30:11 +00002823 SmallVector<SDValue, 4> Values(NumValues);
2824 SDValue Cond = getValue(I.getOperand(0));
2825 SDValue TrueVal = getValue(I.getOperand(1));
2826 SDValue FalseVal = getValue(I.getOperand(2));
Duncan Sands28b77e92011-09-06 19:07:46 +00002827 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2828 ISD::VSELECT : ISD::SELECT;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002829
Bill Wendling4533cac2010-01-28 21:51:40 +00002830 for (unsigned i = 0; i != NumValues; ++i)
Andrew Trickac6d9be2013-05-25 02:42:55 +00002831 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
Duncan Sands28b77e92011-09-06 19:07:46 +00002832 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
Chris Lattnerb3e87b22010-03-12 07:15:36 +00002833 Cond,
Bill Wendling49fcff82009-12-21 22:30:11 +00002834 SDValue(TrueVal.getNode(),
2835 TrueVal.getResNo() + i),
2836 SDValue(FalseVal.getNode(),
2837 FalseVal.getResNo() + i));
2838
Andrew Trickac6d9be2013-05-25 02:42:55 +00002839 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00002840 DAG.getVTList(&ValueVTs[0], NumValues),
2841 &Values[0], NumValues));
Bill Wendling49fcff82009-12-21 22:30:11 +00002842}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002843
Dan Gohman46510a72010-04-15 01:51:59 +00002844void SelectionDAGBuilder::visitTrunc(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002845 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2846 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002847 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002848 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002849}
2850
Dan Gohman46510a72010-04-15 01:51:59 +00002851void SelectionDAGBuilder::visitZExt(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002852 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2853 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2854 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002855 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002856 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002857}
2858
Dan Gohman46510a72010-04-15 01:51:59 +00002859void SelectionDAGBuilder::visitSExt(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002860 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2861 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2862 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002863 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002864 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002865}
2866
Dan Gohman46510a72010-04-15 01:51:59 +00002867void SelectionDAGBuilder::visitFPTrunc(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002868 // FPTrunc is never a no-op cast, no need to check
2869 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002870 const TargetLowering *TLI = TM.getTargetLowering();
2871 EVT DestVT = TLI->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002872 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(),
Pete Cooperf57e1c22012-01-17 01:54:07 +00002873 DestVT, N,
Bill Wendlingba54bca2013-06-19 21:36:55 +00002874 DAG.getTargetConstant(0, TLI->getPointerTy())));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002875}
2876
Stephen Lin09f8ca32013-07-06 21:44:25 +00002877void SelectionDAGBuilder::visitFPExt(const User &I) {
Hal Finkel46bb70c2011-10-18 03:51:57 +00002878 // FPExt is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002879 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002880 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002881 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002882}
2883
Dan Gohman46510a72010-04-15 01:51:59 +00002884void SelectionDAGBuilder::visitFPToUI(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002885 // FPToUI is never a no-op cast, no need to check
2886 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002887 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002888 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002889}
2890
Dan Gohman46510a72010-04-15 01:51:59 +00002891void SelectionDAGBuilder::visitFPToSI(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002892 // FPToSI is never a no-op cast, no need to check
2893 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002894 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002895 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002896}
2897
Dan Gohman46510a72010-04-15 01:51:59 +00002898void SelectionDAGBuilder::visitUIToFP(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002899 // UIToFP is never a no-op cast, no need to check
2900 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002901 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002902 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002903}
2904
Stephen Lin09f8ca32013-07-06 21:44:25 +00002905void SelectionDAGBuilder::visitSIToFP(const User &I) {
Bill Wendling181b6272008-10-19 20:34:04 +00002906 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002907 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002908 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002909 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002910}
2911
Dan Gohman46510a72010-04-15 01:51:59 +00002912void SelectionDAGBuilder::visitPtrToInt(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002913 // What to do depends on the size of the integer and the size of the pointer.
2914 // We can either truncate, zero extend, or no-op, accordingly.
2915 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002916 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002917 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002918}
2919
Dan Gohman46510a72010-04-15 01:51:59 +00002920void SelectionDAGBuilder::visitIntToPtr(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002921 // What to do depends on the size of the integer and the size of the pointer.
2922 // We can either truncate, zero extend, or no-op, accordingly.
2923 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002924 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002925 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002926}
2927
Dan Gohman46510a72010-04-15 01:51:59 +00002928void SelectionDAGBuilder::visitBitCast(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002929 SDValue N = getValue(I.getOperand(0));
Bill Wendlingba54bca2013-06-19 21:36:55 +00002930 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002931
Bill Wendling49fcff82009-12-21 22:30:11 +00002932 // BitCast assures us that source and destination are the same size so this is
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002933 // either a BITCAST or a no-op.
Bill Wendling4533cac2010-01-28 21:51:40 +00002934 if (DestVT != N.getValueType())
Andrew Trickac6d9be2013-05-25 02:42:55 +00002935 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00002936 DestVT, N)); // convert types.
2937 else
Bill Wendling49fcff82009-12-21 22:30:11 +00002938 setValue(&I, N); // noop cast.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002939}
2940
Matt Arsenault59d3ae62013-11-15 01:34:59 +00002941void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
2942 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2943 const Value *SV = I.getOperand(0);
2944 SDValue N = getValue(SV);
2945 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2946
2947 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
2948 unsigned DestAS = I.getType()->getPointerAddressSpace();
2949
2950 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2951 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
2952
2953 setValue(&I, N);
2954}
2955
Dan Gohman46510a72010-04-15 01:51:59 +00002956void SelectionDAGBuilder::visitInsertElement(const User &I) {
Tom Stellard425b76c2013-08-05 22:22:01 +00002957 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002958 SDValue InVec = getValue(I.getOperand(0));
2959 SDValue InVal = getValue(I.getOperand(1));
Tom Stellard425b76c2013-08-05 22:22:01 +00002960 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
2961 getCurSDLoc(), TLI.getVectorIdxTy());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002962 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
Bill Wendlingba54bca2013-06-19 21:36:55 +00002963 TM.getTargetLowering()->getValueType(I.getType()),
Bill Wendling4533cac2010-01-28 21:51:40 +00002964 InVec, InVal, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002965}
2966
Dan Gohman46510a72010-04-15 01:51:59 +00002967void SelectionDAGBuilder::visitExtractElement(const User &I) {
Tom Stellard425b76c2013-08-05 22:22:01 +00002968 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002969 SDValue InVec = getValue(I.getOperand(0));
Tom Stellard425b76c2013-08-05 22:22:01 +00002970 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
2971 getCurSDLoc(), TLI.getVectorIdxTy());
Andrew Trickac6d9be2013-05-25 02:42:55 +00002972 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
Bill Wendlingba54bca2013-06-19 21:36:55 +00002973 TM.getTargetLowering()->getValueType(I.getType()),
2974 InVec, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002975}
2976
Craig Topper51578342012-01-04 09:23:09 +00002977// Utility for visitShuffleVector - Return true if every element in Mask,
Benjamin Kramerd9b0b022012-06-02 10:20:22 +00002978// beginning from position Pos and ending in Pos+Size, falls within the
Craig Topper51578342012-01-04 09:23:09 +00002979// specified sequential range [L, L+Pos). or is undef.
2980static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
Craig Topper23de31b2012-04-11 03:06:35 +00002981 unsigned Pos, unsigned Size, int Low) {
2982 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
Craig Topper51578342012-01-04 09:23:09 +00002983 if (Mask[i] >= 0 && Mask[i] != Low)
Nate Begeman9008ca62009-04-27 18:41:29 +00002984 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002985 return true;
2986}
2987
Dan Gohman46510a72010-04-15 01:51:59 +00002988void SelectionDAGBuilder::visitShuffleVector(const User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002989 SDValue Src1 = getValue(I.getOperand(0));
2990 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002991
Chris Lattner56243b82012-01-26 02:51:13 +00002992 SmallVector<int, 8> Mask;
2993 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2994 unsigned MaskNumElts = Mask.size();
Bill Wendlingba54bca2013-06-19 21:36:55 +00002995
2996 const TargetLowering *TLI = TM.getTargetLowering();
2997 EVT VT = TLI->getValueType(I.getType());
Owen Andersone50ed302009-08-10 22:56:29 +00002998 EVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002999 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00003000
Mon P Wangc7849c22008-11-16 05:06:27 +00003001 if (SrcNumElts == MaskNumElts) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003002 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling4533cac2010-01-28 21:51:40 +00003003 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00003004 return;
3005 }
3006
3007 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00003008 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3009 // Mask is longer than the source vectors and is a multiple of the source
3010 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00003011 // lengths match.
Craig Topper51578342012-01-04 09:23:09 +00003012 if (SrcNumElts*2 == MaskNumElts) {
3013 // First check for Src1 in low and Src2 in high
3014 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3015 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3016 // The shuffle is concatenating two vectors together.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003017 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
Craig Topper51578342012-01-04 09:23:09 +00003018 VT, Src1, Src2));
3019 return;
3020 }
3021 // Then check for Src2 in low and Src1 in high
3022 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3023 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3024 // The shuffle is concatenating two vectors together.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003025 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
Craig Topper51578342012-01-04 09:23:09 +00003026 VT, Src2, Src1));
3027 return;
3028 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00003029 }
3030
Mon P Wangc7849c22008-11-16 05:06:27 +00003031 // Pad both vectors with undefs to make them the same length as the mask.
3032 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00003033 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3034 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00003035 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00003036
Nate Begeman9008ca62009-04-27 18:41:29 +00003037 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3038 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00003039 MOps1[0] = Src1;
3040 MOps2[0] = Src2;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003041
3042 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Andrew Trickac6d9be2013-05-25 02:42:55 +00003043 getCurSDLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00003044 &MOps1[0], NumConcat);
3045 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Andrew Trickac6d9be2013-05-25 02:42:55 +00003046 getCurSDLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00003047 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00003048
Mon P Wangaeb06d22008-11-10 04:46:22 +00003049 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00003050 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00003051 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00003052 int Idx = Mask[i];
Craig Topper23de31b2012-04-11 03:06:35 +00003053 if (Idx >= (int)SrcNumElts)
3054 Idx -= SrcNumElts - MaskNumElts;
3055 MappedOps.push_back(Idx);
Mon P Wangaeb06d22008-11-10 04:46:22 +00003056 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003057
Andrew Trickac6d9be2013-05-25 02:42:55 +00003058 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling4533cac2010-01-28 21:51:40 +00003059 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00003060 return;
3061 }
3062
Mon P Wangc7849c22008-11-16 05:06:27 +00003063 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00003064 // Analyze the access pattern of the vector to see if we can extract
3065 // two subvectors and do the shuffle. The analysis is done by calculating
3066 // the range of elements the mask access on both vectors.
Craig Topper10612dc2012-04-08 23:15:04 +00003067 int MinRange[2] = { static_cast<int>(SrcNumElts),
3068 static_cast<int>(SrcNumElts)};
Mon P Wangc7849c22008-11-16 05:06:27 +00003069 int MaxRange[2] = {-1, -1};
3070
Nate Begeman5a5ca152009-04-29 05:20:52 +00003071 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00003072 int Idx = Mask[i];
Craig Topper10612dc2012-04-08 23:15:04 +00003073 unsigned Input = 0;
Nate Begeman9008ca62009-04-27 18:41:29 +00003074 if (Idx < 0)
3075 continue;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003076
Nate Begeman5a5ca152009-04-29 05:20:52 +00003077 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00003078 Input = 1;
3079 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00003080 }
Nate Begeman9008ca62009-04-27 18:41:29 +00003081 if (Idx > MaxRange[Input])
3082 MaxRange[Input] = Idx;
3083 if (Idx < MinRange[Input])
3084 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00003085 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00003086
Mon P Wangc7849c22008-11-16 05:06:27 +00003087 // Check if the access is smaller than the vector size and can we find
3088 // a reasonable extract index.
Craig Topper10612dc2012-04-08 23:15:04 +00003089 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3090 // Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00003091 int StartIdx[2]; // StartIdx to extract from
Craig Topper10612dc2012-04-08 23:15:04 +00003092 for (unsigned Input = 0; Input < 2; ++Input) {
3093 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
Mon P Wangc7849c22008-11-16 05:06:27 +00003094 RangeUse[Input] = 0; // Unused
3095 StartIdx[Input] = 0;
Craig Topperf873dde2012-04-08 17:53:33 +00003096 continue;
Mon P Wang230e4fa2008-11-21 04:25:21 +00003097 }
Craig Topperf873dde2012-04-08 17:53:33 +00003098
3099 // Find a good start index that is a multiple of the mask length. Then
3100 // see if the rest of the elements are in range.
3101 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3102 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3103 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3104 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00003105 }
3106
Bill Wendling636e2582009-08-21 18:16:06 +00003107 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Bill Wendling4533cac2010-01-28 21:51:40 +00003108 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00003109 return;
3110 }
Craig Topper10612dc2012-04-08 23:15:04 +00003111 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
Mon P Wangc7849c22008-11-16 05:06:27 +00003112 // Extract appropriate subvector and generate a vector shuffle
Craig Topper10612dc2012-04-08 23:15:04 +00003113 for (unsigned Input = 0; Input < 2; ++Input) {
Bill Wendling87710f02009-12-21 23:47:40 +00003114 SDValue &Src = Input == 0 ? Src1 : Src2;
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003115 if (RangeUse[Input] == 0)
Dale Johannesene8d72302009-02-06 23:05:02 +00003116 Src = DAG.getUNDEF(VT);
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003117 else
Andrew Trickac6d9be2013-05-25 02:42:55 +00003118 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT,
Tom Stellard425b76c2013-08-05 22:22:01 +00003119 Src, DAG.getConstant(StartIdx[Input],
3120 TLI->getVectorIdxTy()));
Mon P Wangaeb06d22008-11-10 04:46:22 +00003121 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003122
Mon P Wangc7849c22008-11-16 05:06:27 +00003123 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00003124 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00003125 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00003126 int Idx = Mask[i];
Craig Topper23de31b2012-04-11 03:06:35 +00003127 if (Idx >= 0) {
3128 if (Idx < (int)SrcNumElts)
3129 Idx -= StartIdx[0];
3130 else
3131 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3132 }
3133 MappedOps.push_back(Idx);
Mon P Wangc7849c22008-11-16 05:06:27 +00003134 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003135
Andrew Trickac6d9be2013-05-25 02:42:55 +00003136 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling4533cac2010-01-28 21:51:40 +00003137 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00003138 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00003139 }
3140 }
3141
Mon P Wangc7849c22008-11-16 05:06:27 +00003142 // We can't use either concat vectors or extract subvectors so fall back to
3143 // replacing the shuffle with extract and build vector.
3144 // to insert and build vector.
Owen Andersone50ed302009-08-10 22:56:29 +00003145 EVT EltVT = VT.getVectorElementType();
Tom Stellard425b76c2013-08-05 22:22:01 +00003146 EVT IdxVT = TLI->getVectorIdxTy();
Mon P Wangaeb06d22008-11-10 04:46:22 +00003147 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00003148 for (unsigned i = 0; i != MaskNumElts; ++i) {
Craig Topper23de31b2012-04-11 03:06:35 +00003149 int Idx = Mask[i];
3150 SDValue Res;
3151
3152 if (Idx < 0) {
3153 Res = DAG.getUNDEF(EltVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00003154 } else {
Craig Topper23de31b2012-04-11 03:06:35 +00003155 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3156 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003157
Andrew Trickac6d9be2013-05-25 02:42:55 +00003158 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
Tom Stellard425b76c2013-08-05 22:22:01 +00003159 EltVT, Src, DAG.getConstant(Idx, IdxVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00003160 }
Craig Topper23de31b2012-04-11 03:06:35 +00003161
3162 Ops.push_back(Res);
Mon P Wangaeb06d22008-11-10 04:46:22 +00003163 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003164
Andrew Trickac6d9be2013-05-25 02:42:55 +00003165 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00003166 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003167}
3168
Dan Gohman46510a72010-04-15 01:51:59 +00003169void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003170 const Value *Op0 = I.getOperand(0);
3171 const Value *Op1 = I.getOperand(1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003172 Type *AggTy = I.getType();
3173 Type *ValTy = Op1->getType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003174 bool IntoUndef = isa<UndefValue>(Op0);
3175 bool FromUndef = isa<UndefValue>(Op1);
3176
Jay Foadfc6d3a42011-07-13 10:26:04 +00003177 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003178
Bill Wendlingba54bca2013-06-19 21:36:55 +00003179 const TargetLowering *TLI = TM.getTargetLowering();
Owen Andersone50ed302009-08-10 22:56:29 +00003180 SmallVector<EVT, 4> AggValueVTs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00003181 ComputeValueVTs(*TLI, AggTy, AggValueVTs);
Owen Andersone50ed302009-08-10 22:56:29 +00003182 SmallVector<EVT, 4> ValValueVTs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00003183 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003184
3185 unsigned NumAggValues = AggValueVTs.size();
3186 unsigned NumValValues = ValValueVTs.size();
3187 SmallVector<SDValue, 4> Values(NumAggValues);
3188
3189 SDValue Agg = getValue(Op0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003190 unsigned i = 0;
3191 // Copy the beginning value(s) from the original aggregate.
3192 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00003193 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003194 SDValue(Agg.getNode(), Agg.getResNo() + i);
3195 // Copy values from the inserted value(s).
Rafael Espindola3fa82832011-05-13 15:18:06 +00003196 if (NumValValues) {
3197 SDValue Val = getValue(Op1);
3198 for (; i != LinearIndex + NumValValues; ++i)
3199 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3200 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3201 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003202 // Copy remaining value(s) from the original aggregate.
3203 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00003204 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003205 SDValue(Agg.getNode(), Agg.getResNo() + i);
3206
Andrew Trickac6d9be2013-05-25 02:42:55 +00003207 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00003208 DAG.getVTList(&AggValueVTs[0], NumAggValues),
3209 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003210}
3211
Dan Gohman46510a72010-04-15 01:51:59 +00003212void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003213 const Value *Op0 = I.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003214 Type *AggTy = Op0->getType();
3215 Type *ValTy = I.getType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003216 bool OutOfUndef = isa<UndefValue>(Op0);
3217
Jay Foadfc6d3a42011-07-13 10:26:04 +00003218 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003219
Bill Wendlingba54bca2013-06-19 21:36:55 +00003220 const TargetLowering *TLI = TM.getTargetLowering();
Owen Andersone50ed302009-08-10 22:56:29 +00003221 SmallVector<EVT, 4> ValValueVTs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00003222 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003223
3224 unsigned NumValValues = ValValueVTs.size();
Rafael Espindola3fa82832011-05-13 15:18:06 +00003225
3226 // Ignore a extractvalue that produces an empty object
3227 if (!NumValValues) {
3228 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3229 return;
3230 }
3231
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003232 SmallVector<SDValue, 4> Values(NumValValues);
3233
3234 SDValue Agg = getValue(Op0);
3235 // Copy out the selected value(s).
3236 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3237 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00003238 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00003239 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00003240 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003241
Andrew Trickac6d9be2013-05-25 02:42:55 +00003242 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00003243 DAG.getVTList(&ValValueVTs[0], NumValValues),
3244 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003245}
3246
Dan Gohman46510a72010-04-15 01:51:59 +00003247void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
Matt Arsenaultff718122013-10-21 20:03:54 +00003248 Value *Op0 = I.getOperand(0);
Nadav Rotem1c239202012-02-28 14:13:19 +00003249 // Note that the pointer operand may be a vector of pointers. Take the scalar
3250 // element which holds a pointer.
Matt Arsenaultff718122013-10-21 20:03:54 +00003251 Type *Ty = Op0->getType()->getScalarType();
3252 unsigned AS = Ty->getPointerAddressSpace();
3253 SDValue N = getValue(Op0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003254
Dan Gohman46510a72010-04-15 01:51:59 +00003255 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003256 OI != E; ++OI) {
Dan Gohman46510a72010-04-15 01:51:59 +00003257 const Value *Idx = *OI;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003258 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
Duncan Sandsb2df01a2012-11-13 13:01:58 +00003259 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003260 if (Field) {
3261 // N = N + Offset
3262 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003263 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
Duncan Sandsb2df01a2012-11-13 13:01:58 +00003264 DAG.getConstant(Offset, N.getValueType()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003265 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00003266
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003267 Ty = StTy->getElementType(Field);
3268 } else {
3269 Ty = cast<SequentialType>(Ty)->getElementType();
3270
3271 // If this is a constant subscript, handle it quickly.
Bill Wendlingba54bca2013-06-19 21:36:55 +00003272 const TargetLowering *TLI = TM.getTargetLowering();
Dan Gohman46510a72010-04-15 01:51:59 +00003273 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Dan Gohmane368b462010-06-18 14:22:04 +00003274 if (CI->isZero()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003275 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00003276 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00003277 SDValue OffsVal;
Tom Stellardda25cd32013-08-26 15:05:36 +00003278 EVT PTy = TLI->getPointerTy(AS);
Owen Anderson77547be2009-08-10 18:56:59 +00003279 unsigned PtrBits = PTy.getSizeInBits();
Bill Wendlinge1a90422009-12-21 23:10:19 +00003280 if (PtrBits < 64)
Tom Stellardda25cd32013-08-26 15:05:36 +00003281 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
Owen Anderson825b72b2009-08-11 20:47:22 +00003282 DAG.getConstant(Offs, MVT::i64));
Bill Wendlinge1a90422009-12-21 23:10:19 +00003283 else
Tom Stellardda25cd32013-08-26 15:05:36 +00003284 OffsVal = DAG.getConstant(Offs, PTy);
Bill Wendlinge1a90422009-12-21 23:10:19 +00003285
Andrew Trickac6d9be2013-05-25 02:42:55 +00003286 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00003287 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003288 continue;
3289 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003290
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003291 // N = N + Idx * ElementSize;
Tom Stellardda25cd32013-08-26 15:05:36 +00003292 APInt ElementSize = APInt(TLI->getPointerSizeInBits(AS),
Dan Gohman7abbd042009-10-23 17:57:43 +00003293 TD->getTypeAllocSize(Ty));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003294 SDValue IdxN = getValue(Idx);
3295
3296 // If the index is smaller or larger than intptr_t, truncate or extend
3297 // it.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003298 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003299
3300 // If this is a multiply by a power of two, turn it into a shl
3301 // immediately. This is a very common case.
3302 if (ElementSize != 1) {
Dan Gohman7abbd042009-10-23 17:57:43 +00003303 if (ElementSize.isPowerOf2()) {
3304 unsigned Amt = ElementSize.logBase2();
Andrew Trickac6d9be2013-05-25 02:42:55 +00003305 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003306 N.getValueType(), IdxN,
Nadav Rotem16087692011-12-05 06:29:09 +00003307 DAG.getConstant(Amt, IdxN.getValueType()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003308 } else {
Duncan Sandsb2df01a2012-11-13 13:01:58 +00003309 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00003310 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003311 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003312 }
3313 }
3314
Andrew Trickac6d9be2013-05-25 02:42:55 +00003315 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003316 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003317 }
3318 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00003319
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003320 setValue(&I, N);
3321}
3322
Dan Gohman46510a72010-04-15 01:51:59 +00003323void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003324 // If this is a fixed sized alloca in the entry block of the function,
3325 // allocate it statically on the stack.
3326 if (FuncInfo.StaticAllocaMap.count(&I))
3327 return; // getValue will auto-populate this.
3328
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003329 Type *Ty = I.getAllocatedType();
Bill Wendlingba54bca2013-06-19 21:36:55 +00003330 const TargetLowering *TLI = TM.getTargetLowering();
3331 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003332 unsigned Align =
Bill Wendlingba54bca2013-06-19 21:36:55 +00003333 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003334 I.getAlignment());
3335
3336 SDValue AllocSize = getValue(I.getArraySize());
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003337
Bill Wendlingba54bca2013-06-19 21:36:55 +00003338 EVT IntPtr = TLI->getPointerTy();
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003339 if (AllocSize.getValueType() != IntPtr)
Andrew Trickac6d9be2013-05-25 02:42:55 +00003340 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003341
Andrew Trickac6d9be2013-05-25 02:42:55 +00003342 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003343 AllocSize,
3344 DAG.getConstant(TySize, IntPtr));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003345
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003346 // Handle alignment. If the requested alignment is less than or equal to
3347 // the stack alignment, ignore it. If the size is greater than or equal to
3348 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00003349 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003350 if (Align <= StackAlign)
3351 Align = 0;
3352
3353 // Round the size of the allocation up to the stack alignment size
3354 // by add SA-1 to the size.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003355 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003356 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003357 DAG.getIntPtrConstant(StackAlign-1));
Bill Wendling856ff412009-12-22 00:12:37 +00003358
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003359 // Mask out the low bits for alignment purposes.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003360 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003361 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003362 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3363
3364 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson825b72b2009-08-11 20:47:22 +00003365 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003366 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003367 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003368 setValue(&I, DSA);
3369 DAG.setRoot(DSA.getValue(1));
Bill Wendling856ff412009-12-22 00:12:37 +00003370
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003371 // Inform the Frame Information that we have just allocated a variable-sized
3372 // object.
Bob Wilson8f637ad2013-02-08 20:35:15 +00003373 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003374}
3375
Dan Gohman46510a72010-04-15 01:51:59 +00003376void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
Eli Friedman327236c2011-08-24 20:50:09 +00003377 if (I.isAtomic())
3378 return visitAtomicLoad(I);
3379
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003380 const Value *SV = I.getOperand(0);
3381 SDValue Ptr = getValue(SV);
3382
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003383 Type *Ty = I.getType();
David Greene1e559442010-02-15 17:00:31 +00003384
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003385 bool isVolatile = I.isVolatile();
David Greene1e559442010-02-15 17:00:31 +00003386 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Pete Cooperd752e0f2011-11-08 18:42:53 +00003387 bool isInvariant = I.getMetadata("invariant.load") != 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003388 unsigned Alignment = I.getAlignment();
Dan Gohmanf96e4bd2010-10-20 00:31:05 +00003389 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
Rafael Espindola95d594c2012-03-31 18:14:00 +00003390 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003391
Owen Andersone50ed302009-08-10 22:56:29 +00003392 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003393 SmallVector<uint64_t, 4> Offsets;
Bill Wendlingba54bca2013-06-19 21:36:55 +00003394 ComputeValueVTs(*TM.getTargetLowering(), Ty, ValueVTs, &Offsets);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003395 unsigned NumValues = ValueVTs.size();
3396 if (NumValues == 0)
3397 return;
3398
3399 SDValue Root;
3400 bool ConstantMemory = false;
Andrew Trickde91f3c2010-11-12 17:50:46 +00003401 if (I.isVolatile() || NumValues > MaxParallelChains)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003402 // Serialize volatile loads with other side effects.
3403 Root = getRoot();
Dan Gohmanf96e4bd2010-10-20 00:31:05 +00003404 else if (AA->pointsToConstantMemory(
3405 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003406 // Do not serialize (non-volatile) loads of constant memory with anything.
3407 Root = DAG.getEntryNode();
3408 ConstantMemory = true;
3409 } else {
3410 // Do not serialize non-volatile loads against each other.
3411 Root = DAG.getRoot();
3412 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003413
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003414 SmallVector<SDValue, 4> Values(NumValues);
Andrew Trickde91f3c2010-11-12 17:50:46 +00003415 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3416 NumValues));
Owen Andersone50ed302009-08-10 22:56:29 +00003417 EVT PtrVT = Ptr.getValueType();
Andrew Trickde91f3c2010-11-12 17:50:46 +00003418 unsigned ChainI = 0;
3419 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3420 // Serializing loads here may result in excessive register pressure, and
3421 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3422 // could recover a bit by hoisting nodes upward in the chain by recognizing
3423 // they are side-effect free or do not alias. The optimizer should really
3424 // avoid this case by converting large object/array copies to llvm.memcpy
3425 // (MaxParallelChains should always remain as failsafe).
3426 if (ChainI == MaxParallelChains) {
3427 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
Andrew Trickac6d9be2013-05-25 02:42:55 +00003428 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Andrew Trickde91f3c2010-11-12 17:50:46 +00003429 MVT::Other, &Chains[0], ChainI);
3430 Root = Chain;
3431 ChainI = 0;
3432 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00003433 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
Bill Wendling856ff412009-12-22 00:12:37 +00003434 PtrVT, Ptr,
3435 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00003436 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
Michael J. Spencere70c5262010-10-16 08:25:21 +00003437 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
Rafael Espindola95d594c2012-03-31 18:14:00 +00003438 isNonTemporal, isInvariant, Alignment, TBAAInfo,
3439 Ranges);
Bill Wendling856ff412009-12-22 00:12:37 +00003440
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003441 Values[i] = L;
Andrew Trickde91f3c2010-11-12 17:50:46 +00003442 Chains[ChainI] = L.getValue(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003443 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003444
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003445 if (!ConstantMemory) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003446 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Andrew Trickde91f3c2010-11-12 17:50:46 +00003447 MVT::Other, &Chains[0], ChainI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003448 if (isVolatile)
3449 DAG.setRoot(Chain);
3450 else
3451 PendingLoads.push_back(Chain);
3452 }
3453
Andrew Trickac6d9be2013-05-25 02:42:55 +00003454 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00003455 DAG.getVTList(&ValueVTs[0], NumValues),
3456 &Values[0], NumValues));
Bill Wendling856ff412009-12-22 00:12:37 +00003457}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003458
Dan Gohman46510a72010-04-15 01:51:59 +00003459void SelectionDAGBuilder::visitStore(const StoreInst &I) {
Eli Friedman327236c2011-08-24 20:50:09 +00003460 if (I.isAtomic())
3461 return visitAtomicStore(I);
3462
Dan Gohman46510a72010-04-15 01:51:59 +00003463 const Value *SrcV = I.getOperand(0);
3464 const Value *PtrV = I.getOperand(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003465
Owen Andersone50ed302009-08-10 22:56:29 +00003466 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003467 SmallVector<uint64_t, 4> Offsets;
Bill Wendlingba54bca2013-06-19 21:36:55 +00003468 ComputeValueVTs(*TM.getTargetLowering(), SrcV->getType(), ValueVTs, &Offsets);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003469 unsigned NumValues = ValueVTs.size();
3470 if (NumValues == 0)
3471 return;
3472
3473 // Get the lowered operands. Note that we do this after
3474 // checking if NumResults is zero, because with zero results
3475 // the operands won't have values in the map.
3476 SDValue Src = getValue(SrcV);
3477 SDValue Ptr = getValue(PtrV);
3478
3479 SDValue Root = getRoot();
Andrew Trickde91f3c2010-11-12 17:50:46 +00003480 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3481 NumValues));
Owen Andersone50ed302009-08-10 22:56:29 +00003482 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003483 bool isVolatile = I.isVolatile();
David Greene1e559442010-02-15 17:00:31 +00003484 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003485 unsigned Alignment = I.getAlignment();
Dan Gohmanf96e4bd2010-10-20 00:31:05 +00003486 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
Bill Wendling856ff412009-12-22 00:12:37 +00003487
Andrew Trickde91f3c2010-11-12 17:50:46 +00003488 unsigned ChainI = 0;
3489 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3490 // See visitLoad comments.
3491 if (ChainI == MaxParallelChains) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003492 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Andrew Trickde91f3c2010-11-12 17:50:46 +00003493 MVT::Other, &Chains[0], ChainI);
3494 Root = Chain;
3495 ChainI = 0;
3496 }
Andrew Trickac6d9be2013-05-25 02:42:55 +00003497 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
Bill Wendling856ff412009-12-22 00:12:37 +00003498 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00003499 SDValue St = DAG.getStore(Root, getCurSDLoc(),
Andrew Trickde91f3c2010-11-12 17:50:46 +00003500 SDValue(Src.getNode(), Src.getResNo() + i),
3501 Add, MachinePointerInfo(PtrV, Offsets[i]),
3502 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3503 Chains[ChainI] = St;
Bill Wendling856ff412009-12-22 00:12:37 +00003504 }
3505
Andrew Trickac6d9be2013-05-25 02:42:55 +00003506 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Andrew Trickde91f3c2010-11-12 17:50:46 +00003507 MVT::Other, &Chains[0], ChainI);
Devang Patel7e13efa2010-10-26 22:14:52 +00003508 DAG.setRoot(StoreNode);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003509}
3510
Eli Friedman26689ac2011-08-03 21:06:02 +00003511static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
Eli Friedman327236c2011-08-24 20:50:09 +00003512 SynchronizationScope Scope,
Andrew Trickac6d9be2013-05-25 02:42:55 +00003513 bool Before, SDLoc dl,
Eli Friedman26689ac2011-08-03 21:06:02 +00003514 SelectionDAG &DAG,
3515 const TargetLowering &TLI) {
3516 // Fence, if necessary
3517 if (Before) {
Eli Friedman069e2ed2011-08-26 02:59:24 +00003518 if (Order == AcquireRelease || Order == SequentiallyConsistent)
Eli Friedman26689ac2011-08-03 21:06:02 +00003519 Order = Release;
3520 else if (Order == Acquire || Order == Monotonic)
3521 return Chain;
3522 } else {
3523 if (Order == AcquireRelease)
3524 Order = Acquire;
3525 else if (Order == Release || Order == Monotonic)
3526 return Chain;
3527 }
3528 SDValue Ops[3];
3529 Ops[0] = Chain;
Eli Friedman327236c2011-08-24 20:50:09 +00003530 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
3531 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
Eli Friedman26689ac2011-08-03 21:06:02 +00003532 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
3533}
3534
Eli Friedmanff030482011-07-28 21:48:00 +00003535void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003536 SDLoc dl = getCurSDLoc();
Eli Friedman26689ac2011-08-03 21:06:02 +00003537 AtomicOrdering Order = I.getOrdering();
Eli Friedman327236c2011-08-24 20:50:09 +00003538 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman26689ac2011-08-03 21:06:02 +00003539
3540 SDValue InChain = getRoot();
3541
Bill Wendlingba54bca2013-06-19 21:36:55 +00003542 const TargetLowering *TLI = TM.getTargetLowering();
3543 if (TLI->getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003544 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
Bill Wendlingba54bca2013-06-19 21:36:55 +00003545 DAG, *TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003546
Eli Friedman55ba8162011-07-29 03:05:32 +00003547 SDValue L =
Eli Friedman26689ac2011-08-03 21:06:02 +00003548 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
Craig Topper0ff11902013-08-15 02:44:19 +00003549 getValue(I.getCompareOperand()).getSimpleValueType(),
Eli Friedman26689ac2011-08-03 21:06:02 +00003550 InChain,
Eli Friedman55ba8162011-07-29 03:05:32 +00003551 getValue(I.getPointerOperand()),
3552 getValue(I.getCompareOperand()),
3553 getValue(I.getNewValOperand()),
3554 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
Bill Wendlingba54bca2013-06-19 21:36:55 +00003555 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
Eli Friedman327236c2011-08-24 20:50:09 +00003556 Scope);
Eli Friedman26689ac2011-08-03 21:06:02 +00003557
3558 SDValue OutChain = L.getValue(1);
3559
Bill Wendlingba54bca2013-06-19 21:36:55 +00003560 if (TLI->getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003561 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
Bill Wendlingba54bca2013-06-19 21:36:55 +00003562 DAG, *TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003563
Eli Friedman55ba8162011-07-29 03:05:32 +00003564 setValue(&I, L);
Eli Friedman26689ac2011-08-03 21:06:02 +00003565 DAG.setRoot(OutChain);
Eli Friedmanff030482011-07-28 21:48:00 +00003566}
3567
3568void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003569 SDLoc dl = getCurSDLoc();
Eli Friedman55ba8162011-07-29 03:05:32 +00003570 ISD::NodeType NT;
3571 switch (I.getOperation()) {
David Blaikie4d6ccb52012-01-20 21:51:11 +00003572 default: llvm_unreachable("Unknown atomicrmw operation");
Eli Friedman55ba8162011-07-29 03:05:32 +00003573 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3574 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3575 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3576 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3577 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3578 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3579 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3580 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3581 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3582 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3583 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3584 }
Eli Friedman26689ac2011-08-03 21:06:02 +00003585 AtomicOrdering Order = I.getOrdering();
Eli Friedman327236c2011-08-24 20:50:09 +00003586 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman26689ac2011-08-03 21:06:02 +00003587
3588 SDValue InChain = getRoot();
3589
Bill Wendlingba54bca2013-06-19 21:36:55 +00003590 const TargetLowering *TLI = TM.getTargetLowering();
3591 if (TLI->getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003592 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
Bill Wendlingba54bca2013-06-19 21:36:55 +00003593 DAG, *TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003594
Eli Friedman55ba8162011-07-29 03:05:32 +00003595 SDValue L =
Eli Friedman26689ac2011-08-03 21:06:02 +00003596 DAG.getAtomic(NT, dl,
Craig Topper0ff11902013-08-15 02:44:19 +00003597 getValue(I.getValOperand()).getSimpleValueType(),
Eli Friedman26689ac2011-08-03 21:06:02 +00003598 InChain,
Eli Friedman55ba8162011-07-29 03:05:32 +00003599 getValue(I.getPointerOperand()),
3600 getValue(I.getValOperand()),
3601 I.getPointerOperand(), 0 /* Alignment */,
Bill Wendlingba54bca2013-06-19 21:36:55 +00003602 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
Eli Friedman327236c2011-08-24 20:50:09 +00003603 Scope);
Eli Friedman26689ac2011-08-03 21:06:02 +00003604
3605 SDValue OutChain = L.getValue(1);
3606
Bill Wendlingba54bca2013-06-19 21:36:55 +00003607 if (TLI->getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003608 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
Bill Wendlingba54bca2013-06-19 21:36:55 +00003609 DAG, *TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003610
Eli Friedman55ba8162011-07-29 03:05:32 +00003611 setValue(&I, L);
Eli Friedman26689ac2011-08-03 21:06:02 +00003612 DAG.setRoot(OutChain);
Eli Friedmanff030482011-07-28 21:48:00 +00003613}
3614
Eli Friedman47f35132011-07-25 23:16:38 +00003615void SelectionDAGBuilder::visitFence(const FenceInst &I) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003616 SDLoc dl = getCurSDLoc();
Bill Wendlingba54bca2013-06-19 21:36:55 +00003617 const TargetLowering *TLI = TM.getTargetLowering();
Eli Friedman14648462011-07-27 22:21:52 +00003618 SDValue Ops[3];
3619 Ops[0] = getRoot();
Bill Wendlingba54bca2013-06-19 21:36:55 +00003620 Ops[1] = DAG.getConstant(I.getOrdering(), TLI->getPointerTy());
3621 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI->getPointerTy());
Eli Friedman14648462011-07-27 22:21:52 +00003622 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
Eli Friedman47f35132011-07-25 23:16:38 +00003623}
3624
Eli Friedman327236c2011-08-24 20:50:09 +00003625void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003626 SDLoc dl = getCurSDLoc();
Eli Friedman327236c2011-08-24 20:50:09 +00003627 AtomicOrdering Order = I.getOrdering();
3628 SynchronizationScope Scope = I.getSynchScope();
3629
3630 SDValue InChain = getRoot();
3631
Bill Wendlingba54bca2013-06-19 21:36:55 +00003632 const TargetLowering *TLI = TM.getTargetLowering();
3633 EVT VT = TLI->getValueType(I.getType());
Eli Friedman327236c2011-08-24 20:50:09 +00003634
Evan Cheng607acd62013-02-06 02:06:33 +00003635 if (I.getAlignment() < VT.getSizeInBits() / 8)
Eli Friedmanfe731212011-09-13 20:50:54 +00003636 report_fatal_error("Cannot generate unaligned atomic load");
3637
Eli Friedman327236c2011-08-24 20:50:09 +00003638 SDValue L =
3639 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3640 getValue(I.getPointerOperand()),
3641 I.getPointerOperand(), I.getAlignment(),
Bill Wendlingba54bca2013-06-19 21:36:55 +00003642 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
Eli Friedman327236c2011-08-24 20:50:09 +00003643 Scope);
3644
3645 SDValue OutChain = L.getValue(1);
3646
Bill Wendlingba54bca2013-06-19 21:36:55 +00003647 if (TLI->getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003648 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
Bill Wendlingba54bca2013-06-19 21:36:55 +00003649 DAG, *TLI);
Eli Friedman327236c2011-08-24 20:50:09 +00003650
3651 setValue(&I, L);
3652 DAG.setRoot(OutChain);
3653}
3654
3655void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003656 SDLoc dl = getCurSDLoc();
Eli Friedman327236c2011-08-24 20:50:09 +00003657
3658 AtomicOrdering Order = I.getOrdering();
3659 SynchronizationScope Scope = I.getSynchScope();
3660
3661 SDValue InChain = getRoot();
3662
Bill Wendlingba54bca2013-06-19 21:36:55 +00003663 const TargetLowering *TLI = TM.getTargetLowering();
3664 EVT VT = TLI->getValueType(I.getValueOperand()->getType());
Eli Friedmanfe731212011-09-13 20:50:54 +00003665
Evan Cheng607acd62013-02-06 02:06:33 +00003666 if (I.getAlignment() < VT.getSizeInBits() / 8)
Eli Friedmanfe731212011-09-13 20:50:54 +00003667 report_fatal_error("Cannot generate unaligned atomic store");
3668
Bill Wendlingba54bca2013-06-19 21:36:55 +00003669 if (TLI->getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003670 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
Bill Wendlingba54bca2013-06-19 21:36:55 +00003671 DAG, *TLI);
Eli Friedman327236c2011-08-24 20:50:09 +00003672
3673 SDValue OutChain =
Eli Friedmanfe731212011-09-13 20:50:54 +00003674 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
Eli Friedman327236c2011-08-24 20:50:09 +00003675 InChain,
3676 getValue(I.getPointerOperand()),
3677 getValue(I.getValueOperand()),
3678 I.getPointerOperand(), I.getAlignment(),
Bill Wendlingba54bca2013-06-19 21:36:55 +00003679 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
Eli Friedman327236c2011-08-24 20:50:09 +00003680 Scope);
3681
Bill Wendlingba54bca2013-06-19 21:36:55 +00003682 if (TLI->getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003683 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
Bill Wendlingba54bca2013-06-19 21:36:55 +00003684 DAG, *TLI);
Eli Friedman327236c2011-08-24 20:50:09 +00003685
3686 DAG.setRoot(OutChain);
3687}
3688
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003689/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3690/// node.
Dan Gohman46510a72010-04-15 01:51:59 +00003691void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
Dan Gohman2048b852009-11-23 18:04:58 +00003692 unsigned Intrinsic) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003693 bool HasChain = !I.doesNotAccessMemory();
3694 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3695
3696 // Build the operand list.
3697 SmallVector<SDValue, 8> Ops;
3698 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3699 if (OnlyLoad) {
3700 // We don't need to serialize loads against other loads.
3701 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003702 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003703 Ops.push_back(getRoot());
3704 }
3705 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003706
3707 // Info is set by getTgtMemInstrinsic
3708 TargetLowering::IntrinsicInfo Info;
Bill Wendlingba54bca2013-06-19 21:36:55 +00003709 const TargetLowering *TLI = TM.getTargetLowering();
3710 bool IsTgtIntrinsic = TLI->getTgtMemIntrinsic(Info, I, Intrinsic);
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003711
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003712 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Bob Wilson65ffec42010-09-21 17:56:22 +00003713 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3714 Info.opc == ISD::INTRINSIC_W_CHAIN)
Bill Wendlingba54bca2013-06-19 21:36:55 +00003715 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI->getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003716
3717 // Add all operands of the call to the operand list.
Gabor Greif0635f352010-06-25 09:38:13 +00003718 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3719 SDValue Op = getValue(I.getArgOperand(i));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003720 Ops.push_back(Op);
3721 }
3722
Owen Andersone50ed302009-08-10 22:56:29 +00003723 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00003724 ComputeValueVTs(*TLI, I.getType(), ValueVTs);
Bill Wendling856ff412009-12-22 00:12:37 +00003725
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003726 if (HasChain)
Owen Anderson825b72b2009-08-11 20:47:22 +00003727 ValueVTs.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003728
Bob Wilson8d919552009-07-31 22:41:21 +00003729 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003730
3731 // Create the node.
3732 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003733 if (IsTgtIntrinsic) {
3734 // This is target intrinsic that touches memory
Andrew Trickac6d9be2013-05-25 02:42:55 +00003735 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003736 VTs, &Ops[0], Ops.size(),
Chris Lattnere9ba5dd2010-09-21 04:57:15 +00003737 Info.memVT,
3738 MachinePointerInfo(Info.ptrVal, Info.offset),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003739 Info.align, Info.vol,
3740 Info.readMem, Info.writeMem);
Bill Wendling856ff412009-12-22 00:12:37 +00003741 } else if (!HasChain) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003742 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003743 VTs, &Ops[0], Ops.size());
Benjamin Kramerf0127052010-01-05 13:12:22 +00003744 } else if (!I.getType()->isVoidTy()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003745 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003746 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00003747 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +00003748 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003749 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00003750 }
3751
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003752 if (HasChain) {
3753 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3754 if (OnlyLoad)
3755 PendingLoads.push_back(Chain);
3756 else
3757 DAG.setRoot(Chain);
3758 }
Bill Wendling856ff412009-12-22 00:12:37 +00003759
Benjamin Kramerf0127052010-01-05 13:12:22 +00003760 if (!I.getType()->isVoidTy()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003761 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00003762 EVT VT = TLI->getValueType(PTy);
Andrew Trickac6d9be2013-05-25 02:42:55 +00003763 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003764 }
Bill Wendling856ff412009-12-22 00:12:37 +00003765
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003766 setValue(&I, Result);
3767 }
3768}
3769
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003770/// GetSignificand - Get the significand and build it into a floating-point
3771/// number with exponent of 1:
3772///
3773/// Op = (Op & 0x007fffff) | 0x3f800000;
3774///
Matt Beaumont-Gay50e75bf2013-02-25 18:11:18 +00003775/// where Op is the hexadecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003776static SDValue
Andrew Trickac6d9be2013-05-25 02:42:55 +00003777GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003778 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3779 DAG.getConstant(0x007fffff, MVT::i32));
3780 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3781 DAG.getConstant(0x3f800000, MVT::i32));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003782 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003783}
3784
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003785/// GetExponent - Get the exponent:
3786///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003787/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003788///
Matt Beaumont-Gay50e75bf2013-02-25 18:11:18 +00003789/// where Op is the hexadecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003790static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003791GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
Andrew Trickac6d9be2013-05-25 02:42:55 +00003792 SDLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003793 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3794 DAG.getConstant(0x7f800000, MVT::i32));
3795 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003796 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson825b72b2009-08-11 20:47:22 +00003797 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3798 DAG.getConstant(127, MVT::i32));
Bill Wendling4533cac2010-01-28 21:51:40 +00003799 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003800}
3801
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003802/// getF32Constant - Get 32-bit floating point constant.
3803static SDValue
3804getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Tim Northover0a29cb02013-01-22 09:46:31 +00003805 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3806 MVT::f32);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003807}
3808
Craig Topper538cd482012-11-24 18:52:06 +00003809/// expandExp - Lower an exp intrinsic. Handles the special sequences for
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003810/// limited-precision mode.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003811static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topper538cd482012-11-24 18:52:06 +00003812 const TargetLowering &TLI) {
3813 if (Op.getValueType() == MVT::f32 &&
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003814 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003815
3816 // Put the exponent in the right bit position for later addition to the
3817 // final result:
3818 //
3819 // #define LOG2OFe 1.4426950f
3820 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson825b72b2009-08-11 20:47:22 +00003821 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003822 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003823 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003824
3825 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003826 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3827 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003828
3829 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003830 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003831 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendling856ff412009-12-22 00:12:37 +00003832
Craig Topperb3157722012-11-24 08:22:37 +00003833 SDValue TwoToFracPartOfX;
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003834 if (LimitFloatPrecision <= 6) {
3835 // For floating-point precision of 6:
3836 //
3837 // TwoToFractionalPartOfX =
3838 // 0.997535578f +
3839 // (0.735607626f + 0.252464424f * x) * x;
3840 //
3841 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003842 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003843 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003844 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003845 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003846 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topperb3157722012-11-24 08:22:37 +00003847 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3848 getF32Constant(DAG, 0x3f7f5e7e));
Craig Topper08ac4692012-11-16 20:01:39 +00003849 } else if (LimitFloatPrecision <= 12) {
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003850 // For floating-point precision of 12:
3851 //
3852 // TwoToFractionalPartOfX =
3853 // 0.999892986f +
3854 // (0.696457318f +
3855 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3856 //
3857 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003858 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003859 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003860 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003861 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003862 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3863 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003864 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003865 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topperb3157722012-11-24 08:22:37 +00003866 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3867 getF32Constant(DAG, 0x3f7ff8fd));
Craig Topper08ac4692012-11-16 20:01:39 +00003868 } else { // LimitFloatPrecision <= 18
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003869 // For floating-point precision of 18:
3870 //
3871 // TwoToFractionalPartOfX =
3872 // 0.999999982f +
3873 // (0.693148872f +
3874 // (0.240227044f +
3875 // (0.554906021e-1f +
3876 // (0.961591928e-2f +
3877 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3878 //
3879 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003880 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003881 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003882 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003883 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003884 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3885 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003886 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003887 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3888 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003889 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003890 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3891 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003892 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003893 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3894 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003895 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003896 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topperb3157722012-11-24 08:22:37 +00003897 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3898 getF32Constant(DAG, 0x3f800000));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003899 }
Craig Topperb3157722012-11-24 08:22:37 +00003900
3901 // Add the exponent into the result in integer domain.
3902 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
Craig Topper538cd482012-11-24 18:52:06 +00003903 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3904 DAG.getNode(ISD::ADD, dl, MVT::i32,
3905 t13, IntegerPartOfX));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003906 }
3907
Craig Topper538cd482012-11-24 18:52:06 +00003908 // No special expansion.
3909 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
Dale Johannesen59e577f2008-09-05 18:38:42 +00003910}
3911
Craig Topper5d1e0892012-11-23 18:38:31 +00003912/// expandLog - Lower a log intrinsic. Handles the special sequences for
Bill Wendling39150252008-09-09 20:39:27 +00003913/// limited-precision mode.
Andrew Trickac6d9be2013-05-25 02:42:55 +00003914static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topper5d1e0892012-11-23 18:38:31 +00003915 const TargetLowering &TLI) {
3916 if (Op.getValueType() == MVT::f32 &&
Bill Wendling39150252008-09-09 20:39:27 +00003917 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003918 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003919
3920 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling46ada192010-03-02 01:55:18 +00003921 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003922 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003923 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003924
3925 // Get the significand and build it into a floating-point number with
3926 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00003927 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003928
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003929 SDValue LogOfMantissa;
Bill Wendling39150252008-09-09 20:39:27 +00003930 if (LimitFloatPrecision <= 6) {
3931 // For floating-point precision of 6:
3932 //
3933 // LogofMantissa =
3934 // -1.1609546f +
3935 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003936 //
Bill Wendling39150252008-09-09 20:39:27 +00003937 // error 0.0034276066, which is better than 8 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003938 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003939 getF32Constant(DAG, 0xbe74c456));
Owen Anderson825b72b2009-08-11 20:47:22 +00003940 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003941 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003942 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003943 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3944 getF32Constant(DAG, 0x3f949a29));
Craig Topper08ac4692012-11-16 20:01:39 +00003945 } else if (LimitFloatPrecision <= 12) {
Bill Wendling39150252008-09-09 20:39:27 +00003946 // For floating-point precision of 12:
3947 //
3948 // LogOfMantissa =
3949 // -1.7417939f +
3950 // (2.8212026f +
3951 // (-1.4699568f +
3952 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3953 //
3954 // error 0.000061011436, which is 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003955 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003956 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson825b72b2009-08-11 20:47:22 +00003957 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003958 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003959 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3960 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003961 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003962 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3963 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003964 getF32Constant(DAG, 0x40348e95));
Owen Anderson825b72b2009-08-11 20:47:22 +00003965 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003966 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3967 getF32Constant(DAG, 0x3fdef31a));
Craig Topper08ac4692012-11-16 20:01:39 +00003968 } else { // LimitFloatPrecision <= 18
Bill Wendling39150252008-09-09 20:39:27 +00003969 // For floating-point precision of 18:
3970 //
3971 // LogOfMantissa =
3972 // -2.1072184f +
3973 // (4.2372794f +
3974 // (-3.7029485f +
3975 // (2.2781945f +
3976 // (-0.87823314f +
3977 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3978 //
3979 // error 0.0000023660568, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003980 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003981 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson825b72b2009-08-11 20:47:22 +00003982 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003983 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson825b72b2009-08-11 20:47:22 +00003984 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3985 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003986 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003987 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3988 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003989 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003990 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3991 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003992 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003993 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3994 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003995 getF32Constant(DAG, 0x408797cb));
Owen Anderson825b72b2009-08-11 20:47:22 +00003996 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003997 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3998 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003999 }
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004000
Craig Topper5d1e0892012-11-23 18:38:31 +00004001 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00004002 }
4003
Craig Topper5d1e0892012-11-23 18:38:31 +00004004 // No special expansion.
4005 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
Dale Johannesen59e577f2008-09-05 18:38:42 +00004006}
4007
Craig Topper5d1e0892012-11-23 18:38:31 +00004008/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
Bill Wendling3eb59402008-09-09 00:28:24 +00004009/// limited-precision mode.
Andrew Trickac6d9be2013-05-25 02:42:55 +00004010static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topper5d1e0892012-11-23 18:38:31 +00004011 const TargetLowering &TLI) {
4012 if (Op.getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00004013 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004014 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00004015
Bill Wendling39150252008-09-09 20:39:27 +00004016 // Get the exponent.
Bill Wendling46ada192010-03-02 01:55:18 +00004017 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling856ff412009-12-22 00:12:37 +00004018
Bill Wendling3eb59402008-09-09 00:28:24 +00004019 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00004020 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00004021 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004022
Bill Wendling3eb59402008-09-09 00:28:24 +00004023 // Different possible minimax approximations of significand in
4024 // floating-point for various degrees of accuracy over [1,2].
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004025 SDValue Log2ofMantissa;
Bill Wendling3eb59402008-09-09 00:28:24 +00004026 if (LimitFloatPrecision <= 6) {
4027 // For floating-point precision of 6:
4028 //
4029 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4030 //
4031 // error 0.0049451742, which is more than 7 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004032 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004033 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson825b72b2009-08-11 20:47:22 +00004034 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004035 getF32Constant(DAG, 0x40019463));
Owen Anderson825b72b2009-08-11 20:47:22 +00004036 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004037 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4038 getF32Constant(DAG, 0x3fd6633d));
Craig Topper08ac4692012-11-16 20:01:39 +00004039 } else if (LimitFloatPrecision <= 12) {
Bill Wendling3eb59402008-09-09 00:28:24 +00004040 // For floating-point precision of 12:
4041 //
4042 // Log2ofMantissa =
4043 // -2.51285454f +
4044 // (4.07009056f +
4045 // (-2.12067489f +
4046 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004047 //
Bill Wendling3eb59402008-09-09 00:28:24 +00004048 // error 0.0000876136000, which is better than 13 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004049 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004050 getF32Constant(DAG, 0xbda7262e));
Owen Anderson825b72b2009-08-11 20:47:22 +00004051 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004052 getF32Constant(DAG, 0x3f25280b));
Owen Anderson825b72b2009-08-11 20:47:22 +00004053 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4054 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004055 getF32Constant(DAG, 0x4007b923));
Owen Anderson825b72b2009-08-11 20:47:22 +00004056 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4057 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004058 getF32Constant(DAG, 0x40823e2f));
Owen Anderson825b72b2009-08-11 20:47:22 +00004059 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004060 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4061 getF32Constant(DAG, 0x4020d29c));
Craig Topper08ac4692012-11-16 20:01:39 +00004062 } else { // LimitFloatPrecision <= 18
Bill Wendling3eb59402008-09-09 00:28:24 +00004063 // For floating-point precision of 18:
4064 //
4065 // Log2ofMantissa =
4066 // -3.0400495f +
4067 // (6.1129976f +
4068 // (-5.3420409f +
4069 // (3.2865683f +
4070 // (-1.2669343f +
4071 // (0.27515199f -
4072 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4073 //
4074 // error 0.0000018516, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004075 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004076 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson825b72b2009-08-11 20:47:22 +00004077 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004078 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson825b72b2009-08-11 20:47:22 +00004079 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4080 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004081 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson825b72b2009-08-11 20:47:22 +00004082 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4083 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004084 getF32Constant(DAG, 0x40525723));
Owen Anderson825b72b2009-08-11 20:47:22 +00004085 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4086 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004087 getF32Constant(DAG, 0x40aaf200));
Owen Anderson825b72b2009-08-11 20:47:22 +00004088 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4089 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004090 getF32Constant(DAG, 0x40c39dad));
Owen Anderson825b72b2009-08-11 20:47:22 +00004091 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004092 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4093 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00004094 }
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004095
Craig Topper5d1e0892012-11-23 18:38:31 +00004096 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
Dale Johannesen853244f2008-09-05 23:49:37 +00004097 }
Bill Wendling3eb59402008-09-09 00:28:24 +00004098
Craig Topper5d1e0892012-11-23 18:38:31 +00004099 // No special expansion.
4100 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
Dale Johannesen59e577f2008-09-05 18:38:42 +00004101}
4102
Craig Topper5d1e0892012-11-23 18:38:31 +00004103/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
Bill Wendling3eb59402008-09-09 00:28:24 +00004104/// limited-precision mode.
Andrew Trickac6d9be2013-05-25 02:42:55 +00004105static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topper5d1e0892012-11-23 18:38:31 +00004106 const TargetLowering &TLI) {
4107 if (Op.getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00004108 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004109 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00004110
Bill Wendling39150252008-09-09 20:39:27 +00004111 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling46ada192010-03-02 01:55:18 +00004112 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00004113 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004114 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00004115
4116 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00004117 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00004118 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00004119
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004120 SDValue Log10ofMantissa;
Bill Wendling3eb59402008-09-09 00:28:24 +00004121 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004122 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004123 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004124 // Log10ofMantissa =
4125 // -0.50419619f +
4126 // (0.60948995f - 0.10380950f * x) * x;
4127 //
4128 // error 0.0014886165, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004129 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004130 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson825b72b2009-08-11 20:47:22 +00004131 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004132 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson825b72b2009-08-11 20:47:22 +00004133 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004134 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4135 getF32Constant(DAG, 0x3f011300));
Craig Topper08ac4692012-11-16 20:01:39 +00004136 } else if (LimitFloatPrecision <= 12) {
Bill Wendling3eb59402008-09-09 00:28:24 +00004137 // For floating-point precision of 12:
4138 //
4139 // Log10ofMantissa =
4140 // -0.64831180f +
4141 // (0.91751397f +
4142 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4143 //
4144 // error 0.00019228036, which is better than 12 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004145 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004146 getF32Constant(DAG, 0x3d431f31));
Owen Anderson825b72b2009-08-11 20:47:22 +00004147 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004148 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson825b72b2009-08-11 20:47:22 +00004149 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4150 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004151 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson825b72b2009-08-11 20:47:22 +00004152 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004153 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4154 getF32Constant(DAG, 0x3f25f7c3));
Craig Topper08ac4692012-11-16 20:01:39 +00004155 } else { // LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004156 // For floating-point precision of 18:
4157 //
4158 // Log10ofMantissa =
4159 // -0.84299375f +
4160 // (1.5327582f +
4161 // (-1.0688956f +
4162 // (0.49102474f +
4163 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4164 //
4165 // error 0.0000037995730, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004166 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004167 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson825b72b2009-08-11 20:47:22 +00004168 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004169 getF32Constant(DAG, 0x3e00685a));
Owen Anderson825b72b2009-08-11 20:47:22 +00004170 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4171 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004172 getF32Constant(DAG, 0x3efb6798));
Owen Anderson825b72b2009-08-11 20:47:22 +00004173 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4174 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004175 getF32Constant(DAG, 0x3f88d192));
Owen Anderson825b72b2009-08-11 20:47:22 +00004176 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4177 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004178 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson825b72b2009-08-11 20:47:22 +00004179 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004180 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4181 getF32Constant(DAG, 0x3f57ce70));
Bill Wendling3eb59402008-09-09 00:28:24 +00004182 }
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004183
Craig Topper5d1e0892012-11-23 18:38:31 +00004184 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
Dale Johannesen852680a2008-09-05 21:27:19 +00004185 }
Bill Wendling3eb59402008-09-09 00:28:24 +00004186
Craig Topper5d1e0892012-11-23 18:38:31 +00004187 // No special expansion.
4188 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
Dale Johannesen59e577f2008-09-05 18:38:42 +00004189}
4190
Craig Topper538cd482012-11-24 18:52:06 +00004191/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
Bill Wendlinge10c8142008-09-09 22:39:21 +00004192/// limited-precision mode.
Andrew Trickac6d9be2013-05-25 02:42:55 +00004193static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topper538cd482012-11-24 18:52:06 +00004194 const TargetLowering &TLI) {
4195 if (Op.getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00004196 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004197 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004198
4199 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00004200 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4201 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004202
4203 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00004204 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00004205 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00004206
Craig Topperb3157722012-11-24 08:22:37 +00004207 SDValue TwoToFractionalPartOfX;
Bill Wendlinge10c8142008-09-09 22:39:21 +00004208 if (LimitFloatPrecision <= 6) {
4209 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004210 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00004211 // TwoToFractionalPartOfX =
4212 // 0.997535578f +
4213 // (0.735607626f + 0.252464424f * x) * x;
4214 //
4215 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004216 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004217 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00004218 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004219 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00004220 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topperb3157722012-11-24 08:22:37 +00004221 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4222 getF32Constant(DAG, 0x3f7f5e7e));
Craig Topper08ac4692012-11-16 20:01:39 +00004223 } else if (LimitFloatPrecision <= 12) {
Bill Wendlinge10c8142008-09-09 22:39:21 +00004224 // For floating-point precision of 12:
4225 //
4226 // TwoToFractionalPartOfX =
4227 // 0.999892986f +
4228 // (0.696457318f +
4229 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4230 //
4231 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004232 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004233 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004234 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004235 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004236 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4237 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004238 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00004239 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topperb3157722012-11-24 08:22:37 +00004240 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4241 getF32Constant(DAG, 0x3f7ff8fd));
Craig Topper08ac4692012-11-16 20:01:39 +00004242 } else { // LimitFloatPrecision <= 18
Bill Wendlinge10c8142008-09-09 22:39:21 +00004243 // For floating-point precision of 18:
4244 //
4245 // TwoToFractionalPartOfX =
4246 // 0.999999982f +
4247 // (0.693148872f +
4248 // (0.240227044f +
4249 // (0.554906021e-1f +
4250 // (0.961591928e-2f +
4251 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4252 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004253 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004254 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00004255 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004256 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00004257 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4258 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004259 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00004260 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4261 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004262 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00004263 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4264 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004265 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00004266 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4267 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004268 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00004269 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topperb3157722012-11-24 08:22:37 +00004270 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4271 getF32Constant(DAG, 0x3f800000));
Bill Wendlinge10c8142008-09-09 22:39:21 +00004272 }
Craig Topperb3157722012-11-24 08:22:37 +00004273
4274 // Add the exponent into the result in integer domain.
4275 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4276 TwoToFractionalPartOfX);
Craig Topper538cd482012-11-24 18:52:06 +00004277 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4278 DAG.getNode(ISD::ADD, dl, MVT::i32,
4279 t13, IntegerPartOfX));
Dale Johannesen601d3c02008-09-05 01:48:15 +00004280 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00004281
Craig Topper538cd482012-11-24 18:52:06 +00004282 // No special expansion.
4283 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
Dale Johannesen601d3c02008-09-05 01:48:15 +00004284}
4285
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004286/// visitPow - Lower a pow intrinsic. Handles the special sequences for
4287/// limited-precision mode with x == 10.0f.
Andrew Trickac6d9be2013-05-25 02:42:55 +00004288static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
Craig Topper327e4cb2012-11-25 08:08:58 +00004289 SelectionDAG &DAG, const TargetLowering &TLI) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004290 bool IsExp10 = false;
Craig Topper327e4cb2012-11-25 08:08:58 +00004291 if (LHS.getValueType() == MVT::f32 && LHS.getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004292 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Craig Topper327e4cb2012-11-25 08:08:58 +00004293 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4294 APFloat Ten(10.0f);
4295 IsExp10 = LHSC->isExactlyValue(Ten);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004296 }
4297 }
4298
Craig Topperc1aa6382012-11-25 00:48:58 +00004299 if (IsExp10) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004300 // Put the exponent in the right bit position for later addition to the
4301 // final result:
4302 //
4303 // #define LOG2OF10 3.3219281f
4304 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Craig Topper327e4cb2012-11-25 08:08:58 +00004305 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004306 getF32Constant(DAG, 0x40549a78));
Owen Anderson825b72b2009-08-11 20:47:22 +00004307 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004308
4309 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00004310 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4311 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004312
4313 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00004314 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00004315 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004316
Craig Topper915562e2012-11-25 00:15:07 +00004317 SDValue TwoToFractionalPartOfX;
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004318 if (LimitFloatPrecision <= 6) {
4319 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004320 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004321 // twoToFractionalPartOfX =
4322 // 0.997535578f +
4323 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004324 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004325 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004326 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004327 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00004328 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004329 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00004330 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper915562e2012-11-25 00:15:07 +00004331 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4332 getF32Constant(DAG, 0x3f7f5e7e));
Craig Topper08ac4692012-11-16 20:01:39 +00004333 } else if (LimitFloatPrecision <= 12) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004334 // For floating-point precision of 12:
4335 //
4336 // TwoToFractionalPartOfX =
4337 // 0.999892986f +
4338 // (0.696457318f +
4339 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4340 //
4341 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004342 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004343 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004344 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004345 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004346 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4347 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004348 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00004349 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper915562e2012-11-25 00:15:07 +00004350 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4351 getF32Constant(DAG, 0x3f7ff8fd));
Craig Topper08ac4692012-11-16 20:01:39 +00004352 } else { // LimitFloatPrecision <= 18
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004353 // For floating-point precision of 18:
4354 //
4355 // TwoToFractionalPartOfX =
4356 // 0.999999982f +
4357 // (0.693148872f +
4358 // (0.240227044f +
4359 // (0.554906021e-1f +
4360 // (0.961591928e-2f +
4361 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4362 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004363 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004364 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00004365 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004366 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00004367 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4368 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004369 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00004370 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4371 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004372 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00004373 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4374 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004375 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00004376 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4377 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004378 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00004379 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topper915562e2012-11-25 00:15:07 +00004380 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4381 getF32Constant(DAG, 0x3f800000));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004382 }
Craig Topper915562e2012-11-25 00:15:07 +00004383
4384 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
Craig Topper327e4cb2012-11-25 08:08:58 +00004385 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4386 DAG.getNode(ISD::ADD, dl, MVT::i32,
4387 t13, IntegerPartOfX));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004388 }
4389
Craig Topper327e4cb2012-11-25 08:08:58 +00004390 // No special expansion.
4391 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004392}
4393
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004394
4395/// ExpandPowI - Expand a llvm.powi intrinsic.
Andrew Trickac6d9be2013-05-25 02:42:55 +00004396static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004397 SelectionDAG &DAG) {
4398 // If RHS is a constant, we can expand this out to a multiplication tree,
4399 // otherwise we end up lowering to a call to __powidf2 (for example). When
4400 // optimizing for size, we only want to do this if the expansion would produce
4401 // a small number of multiplies, otherwise we do the full expansion.
4402 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4403 // Get the exponent as a positive value.
4404 unsigned Val = RHSC->getSExtValue();
4405 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004406
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004407 // powi(x, 0) -> 1.0
4408 if (Val == 0)
4409 return DAG.getConstantFP(1.0, LHS.getValueType());
4410
Dan Gohmanae541aa2010-04-15 04:33:49 +00004411 const Function *F = DAG.getMachineFunction().getFunction();
Bill Wendling831737d2012-12-30 10:32:01 +00004412 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
4413 Attribute::OptimizeForSize) ||
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004414 // If optimizing for size, don't insert too many multiplies. This
4415 // inserts up to 5 multiplies.
4416 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4417 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004418 // sequence. There are more optimal ways to do this (for example,
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004419 // powi(x,15) generates one more multiply than it should), but this has
4420 // the benefit of being both really simple and much better than a libcall.
4421 SDValue Res; // Logically starts equal to 1.0
4422 SDValue CurSquare = LHS;
4423 while (Val) {
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00004424 if (Val & 1) {
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004425 if (Res.getNode())
4426 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4427 else
4428 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00004429 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004430
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004431 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4432 CurSquare, CurSquare);
4433 Val >>= 1;
4434 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004435
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004436 // If the original was negative, invert the result, producing 1/(x*x*x).
4437 if (RHSC->getSExtValue() < 0)
4438 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4439 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4440 return Res;
4441 }
4442 }
4443
4444 // Otherwise, expand to a libcall.
4445 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4446}
4447
Devang Patel227dfdb2011-05-16 21:24:05 +00004448// getTruncatedArgReg - Find underlying register used for an truncated
4449// argument.
4450static unsigned getTruncatedArgReg(const SDValue &N) {
4451 if (N.getOpcode() != ISD::TRUNCATE)
4452 return 0;
4453
4454 const SDValue &Ext = N.getOperand(0);
Stephen Lin09f8ca32013-07-06 21:44:25 +00004455 if (Ext.getOpcode() == ISD::AssertZext ||
4456 Ext.getOpcode() == ISD::AssertSext) {
Devang Patel227dfdb2011-05-16 21:24:05 +00004457 const SDValue &CFR = Ext.getOperand(0);
4458 if (CFR.getOpcode() == ISD::CopyFromReg)
4459 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
Craig Topper7eb46d82012-04-11 04:55:51 +00004460 if (CFR.getOpcode() == ISD::TRUNCATE)
4461 return getTruncatedArgReg(CFR);
Devang Patel227dfdb2011-05-16 21:24:05 +00004462 }
4463 return 0;
4464}
4465
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004466/// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4467/// argument, create the corresponding DBG_VALUE machine instruction for it now.
4468/// At the end of instruction selection, they will be inserted to the entry BB.
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004469bool
Devang Patel78a06e52010-08-25 20:39:26 +00004470SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
Michael J. Spencere70c5262010-10-16 08:25:21 +00004471 int64_t Offset,
Dan Gohman5d11ea32010-05-01 00:33:16 +00004472 const SDValue &N) {
Devang Patel0b48ead2010-08-31 22:22:42 +00004473 const Argument *Arg = dyn_cast<Argument>(V);
4474 if (!Arg)
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004475 return false;
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004476
Devang Patel719f6a92010-04-29 20:40:36 +00004477 MachineFunction &MF = DAG.getMachineFunction();
Devang Patela90b3052010-11-02 17:01:30 +00004478 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
Devang Patela90b3052010-11-02 17:01:30 +00004479
Devang Patela83ce982010-04-29 18:50:36 +00004480 // Ignore inlined function arguments here.
4481 DIVariable DV(Variable);
Devang Patel719f6a92010-04-29 20:40:36 +00004482 if (DV.isInlinedFnArgument(MF.getFunction()))
Devang Patela83ce982010-04-29 18:50:36 +00004483 return false;
4484
David Blaikie6d9dbd52013-06-16 20:34:15 +00004485 Optional<MachineOperand> Op;
Devang Patel9aee3352011-09-08 22:59:09 +00004486 // Some arguments' frame index is recorded during argument lowering.
David Blaikie6d9dbd52013-06-16 20:34:15 +00004487 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4488 Op = MachineOperand::CreateFI(FI);
Devang Patel0b48ead2010-08-31 22:22:42 +00004489
David Blaikie6d9dbd52013-06-16 20:34:15 +00004490 if (!Op && N.getNode()) {
4491 unsigned Reg;
Devang Patel227dfdb2011-05-16 21:24:05 +00004492 if (N.getOpcode() == ISD::CopyFromReg)
4493 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4494 else
4495 Reg = getTruncatedArgReg(N);
4496 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004497 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4498 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4499 if (PR)
4500 Reg = PR;
4501 }
David Blaikie6d9dbd52013-06-16 20:34:15 +00004502 if (Reg)
4503 Op = MachineOperand::CreateReg(Reg, false);
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004504 }
4505
David Blaikie6d9dbd52013-06-16 20:34:15 +00004506 if (!Op) {
Devang Patela90b3052010-11-02 17:01:30 +00004507 // Check if ValueMap has reg number.
Evan Chenga36acad2010-04-29 06:33:38 +00004508 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
Devang Patel8bc9ef72010-11-02 17:19:03 +00004509 if (VMI != FuncInfo.ValueMap.end())
David Blaikie6d9dbd52013-06-16 20:34:15 +00004510 Op = MachineOperand::CreateReg(VMI->second, false);
Evan Chenga36acad2010-04-29 06:33:38 +00004511 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004512
David Blaikie6d9dbd52013-06-16 20:34:15 +00004513 if (!Op && N.getNode())
Devang Patela90b3052010-11-02 17:01:30 +00004514 // Check if frame index is available.
4515 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004516 if (FrameIndexSDNode *FINode =
David Blaikie6d9dbd52013-06-16 20:34:15 +00004517 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4518 Op = MachineOperand::CreateFI(FINode->getIndex());
Devang Patel8bc9ef72010-11-02 17:19:03 +00004519
David Blaikie6d9dbd52013-06-16 20:34:15 +00004520 if (!Op)
Devang Patel8bc9ef72010-11-02 17:19:03 +00004521 return false;
Devang Patela90b3052010-11-02 17:01:30 +00004522
Adrian Prantl893ae832013-07-10 01:53:30 +00004523 // FIXME: This does not handle register-indirect values at offset 0.
4524 bool IsIndirect = Offset != 0;
David Blaikie6d9dbd52013-06-16 20:34:15 +00004525 if (Op->isReg())
Adrian Prantl35176402013-07-09 20:28:37 +00004526 FuncInfo.ArgDbgValues.push_back(BuildMI(MF, getCurDebugLoc(),
4527 TII->get(TargetOpcode::DBG_VALUE),
Adrian Prantl893ae832013-07-10 01:53:30 +00004528 IsIndirect,
Adrian Prantl35176402013-07-09 20:28:37 +00004529 Op->getReg(), Offset, Variable));
4530 else
4531 FuncInfo.ArgDbgValues.push_back(
David Blaikie6d9dbd52013-06-16 20:34:15 +00004532 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4533 .addOperand(*Op).addImm(Offset).addMetadata(Variable));
Adrian Prantl35176402013-07-09 20:28:37 +00004534
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004535 return true;
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004536}
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004537
Douglas Gregor7d9663c2010-05-11 06:17:44 +00004538// VisualStudio defines setjmp as _setjmp
Michael J. Spencer1f409602010-09-24 19:48:47 +00004539#if defined(_MSC_VER) && defined(setjmp) && \
4540 !defined(setjmp_undefined_for_msvc)
4541# pragma push_macro("setjmp")
4542# undef setjmp
4543# define setjmp_undefined_for_msvc
Douglas Gregor7d9663c2010-05-11 06:17:44 +00004544#endif
4545
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004546/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4547/// we want to emit this as a call to a named external function, return the name
4548/// otherwise lower it and return null.
4549const char *
Dan Gohman46510a72010-04-15 01:51:59 +00004550SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00004551 const TargetLowering *TLI = TM.getTargetLowering();
Andrew Trickac6d9be2013-05-25 02:42:55 +00004552 SDLoc sdl = getCurSDLoc();
Dale Johannesen66978ee2009-01-31 02:22:37 +00004553 DebugLoc dl = getCurDebugLoc();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004554 SDValue Res;
4555
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004556 switch (Intrinsic) {
4557 default:
4558 // By default, turn this into a target intrinsic node.
4559 visitTargetIntrinsic(I, Intrinsic);
4560 return 0;
4561 case Intrinsic::vastart: visitVAStart(I); return 0;
4562 case Intrinsic::vaend: visitVAEnd(I); return 0;
4563 case Intrinsic::vacopy: visitVACopy(I); return 0;
4564 case Intrinsic::returnaddress:
Bill Wendlingba54bca2013-06-19 21:36:55 +00004565 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI->getPointerTy(),
Gabor Greif0635f352010-06-25 09:38:13 +00004566 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004567 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00004568 case Intrinsic::frameaddress:
Bill Wendlingba54bca2013-06-19 21:36:55 +00004569 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI->getPointerTy(),
Gabor Greif0635f352010-06-25 09:38:13 +00004570 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004571 return 0;
4572 case Intrinsic::setjmp:
Bill Wendlingba54bca2013-06-19 21:36:55 +00004573 return &"_setjmp"[!TLI->usesUnderscoreSetJmp()];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004574 case Intrinsic::longjmp:
Bill Wendlingba54bca2013-06-19 21:36:55 +00004575 return &"_longjmp"[!TLI->usesUnderscoreLongJmp()];
Chris Lattner824b9582008-11-21 16:42:48 +00004576 case Intrinsic::memcpy: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004577 // Assert for address < 256 since we support only user defined address
4578 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004579 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004580 < 256 &&
Gabor Greif0635f352010-06-25 09:38:13 +00004581 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004582 < 256 &&
4583 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004584 SDValue Op1 = getValue(I.getArgOperand(0));
4585 SDValue Op2 = getValue(I.getArgOperand(1));
4586 SDValue Op3 = getValue(I.getArgOperand(2));
4587 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruthaf23f8e2013-02-25 14:20:21 +00004588 if (!Align)
4589 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
Gabor Greif0635f352010-06-25 09:38:13 +00004590 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickac6d9be2013-05-25 02:42:55 +00004591 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
Chris Lattnere72f2022010-09-21 05:40:29 +00004592 MachinePointerInfo(I.getArgOperand(0)),
4593 MachinePointerInfo(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004594 return 0;
4595 }
Chris Lattner824b9582008-11-21 16:42:48 +00004596 case Intrinsic::memset: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004597 // Assert for address < 256 since we support only user defined address
4598 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004599 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004600 < 256 &&
4601 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004602 SDValue Op1 = getValue(I.getArgOperand(0));
4603 SDValue Op2 = getValue(I.getArgOperand(1));
4604 SDValue Op3 = getValue(I.getArgOperand(2));
4605 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruthaf23f8e2013-02-25 14:20:21 +00004606 if (!Align)
4607 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
Gabor Greif0635f352010-06-25 09:38:13 +00004608 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickac6d9be2013-05-25 02:42:55 +00004609 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
Chris Lattnere72f2022010-09-21 05:40:29 +00004610 MachinePointerInfo(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004611 return 0;
4612 }
Chris Lattner824b9582008-11-21 16:42:48 +00004613 case Intrinsic::memmove: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004614 // Assert for address < 256 since we support only user defined address
4615 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004616 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004617 < 256 &&
Gabor Greif0635f352010-06-25 09:38:13 +00004618 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004619 < 256 &&
4620 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004621 SDValue Op1 = getValue(I.getArgOperand(0));
4622 SDValue Op2 = getValue(I.getArgOperand(1));
4623 SDValue Op3 = getValue(I.getArgOperand(2));
4624 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruthaf23f8e2013-02-25 14:20:21 +00004625 if (!Align)
4626 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
Gabor Greif0635f352010-06-25 09:38:13 +00004627 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickac6d9be2013-05-25 02:42:55 +00004628 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
Chris Lattnere72f2022010-09-21 05:40:29 +00004629 MachinePointerInfo(I.getArgOperand(0)),
4630 MachinePointerInfo(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004631 return 0;
4632 }
Bill Wendling92c1e122009-02-13 02:16:35 +00004633 case Intrinsic::dbg_declare: {
Dan Gohman46510a72010-04-15 01:51:59 +00004634 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Devang Patelac1ceb32009-10-09 22:42:28 +00004635 MDNode *Variable = DI.getVariable();
Dan Gohman46510a72010-04-15 01:51:59 +00004636 const Value *Address = DI.getAddress();
Manman Rencbafae62013-06-28 05:43:10 +00004637 DIVariable DIVar(Variable);
4638 assert((!DIVar || DIVar.isVariable()) &&
4639 "Variable in DbgDeclareInst should be either null or a DIVariable.");
4640 if (!Address || !DIVar) {
Eric Christopher8f2a88d2012-03-15 21:33:41 +00004641 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesen8ac38f22010-02-08 21:53:27 +00004642 return 0;
Eric Christopher8f2a88d2012-03-15 21:33:41 +00004643 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004644
Devang Patel3f74a112010-09-02 21:29:42 +00004645 // Check if address has undef value.
4646 if (isa<UndefValue>(Address) ||
4647 (Address->use_empty() && !isa<Argument>(Address))) {
Eric Christopher24413672012-02-23 03:39:39 +00004648 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patel3f74a112010-09-02 21:29:42 +00004649 return 0;
4650 }
4651
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004652 SDValue &N = NodeMap[Address];
Devang Patel0b48ead2010-08-31 22:22:42 +00004653 if (!N.getNode() && isa<Argument>(Address))
4654 // Check unused arguments map.
4655 N = UnusedArgNodeMap[Address];
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004656 SDDbgValue *SDV;
4657 if (N.getNode()) {
Devang Patel8e741ed2010-09-02 21:02:27 +00004658 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4659 Address = BCI->getOperand(0);
Eric Christopher178606d2012-02-24 01:59:08 +00004660 // Parameters are handled specially.
4661 bool isParameter =
4662 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4663 isa<Argument>(Address));
4664
Devang Patel8e741ed2010-09-02 21:02:27 +00004665 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4666
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004667 if (isParameter && !AI) {
4668 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4669 if (FINode)
4670 // Byval parameter. We have a frame index at this point.
4671 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4672 0, dl, SDNodeOrder);
Devang Patelafeaae72010-12-06 22:39:26 +00004673 else {
Devang Patel227dfdb2011-05-16 21:24:05 +00004674 // Address is an argument, so try to emit its dbg value using
4675 // virtual register info from the FuncInfo.ValueMap.
4676 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004677 return 0;
Devang Patelafeaae72010-12-06 22:39:26 +00004678 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004679 } else if (AI)
4680 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4681 0, dl, SDNodeOrder);
Devang Patelafeaae72010-12-06 22:39:26 +00004682 else {
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004683 // Can't do anything with other non-AI cases yet.
Eric Christopher24413672012-02-23 03:39:39 +00004684 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Eric Christopher178606d2012-02-24 01:59:08 +00004685 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4686 DEBUG(Address->dump());
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004687 return 0;
Devang Patelafeaae72010-12-06 22:39:26 +00004688 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004689 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4690 } else {
Gabor Greiffb4032f2010-10-01 10:32:19 +00004691 // If Address is an argument then try to emit its dbg value using
Michael J. Spencere70c5262010-10-16 08:25:21 +00004692 // virtual register info from the FuncInfo.ValueMap.
Devang Patel6cd467b2010-08-26 22:53:27 +00004693 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
Devang Patel1397fdc2010-09-15 14:48:53 +00004694 // If variable is pinned by a alloca in dominating bb then
4695 // use StaticAllocaMap.
4696 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
Devang Patel27ede1b2010-09-15 18:13:55 +00004697 if (AI->getParent() != DI.getParent()) {
4698 DenseMap<const AllocaInst*, int>::iterator SI =
4699 FuncInfo.StaticAllocaMap.find(AI);
4700 if (SI != FuncInfo.StaticAllocaMap.end()) {
4701 SDV = DAG.getDbgValue(Variable, SI->second,
4702 0, dl, SDNodeOrder);
4703 DAG.AddDbgValue(SDV, 0, false);
4704 return 0;
4705 }
Devang Patel1397fdc2010-09-15 14:48:53 +00004706 }
4707 }
Eric Christopher0822e012012-02-23 03:39:43 +00004708 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patel6cd467b2010-08-26 22:53:27 +00004709 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004710 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004711 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00004712 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004713 case Intrinsic::dbg_value: {
Dan Gohman46510a72010-04-15 01:51:59 +00004714 const DbgValueInst &DI = cast<DbgValueInst>(I);
Manman Rencbafae62013-06-28 05:43:10 +00004715 DIVariable DIVar(DI.getVariable());
4716 assert((!DIVar || DIVar.isVariable()) &&
4717 "Variable in DbgValueInst should be either null or a DIVariable.");
4718 if (!DIVar)
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004719 return 0;
4720
4721 MDNode *Variable = DI.getVariable();
Devang Patel00190342010-03-15 19:15:44 +00004722 uint64_t Offset = DI.getOffset();
Dan Gohman46510a72010-04-15 01:51:59 +00004723 const Value *V = DI.getValue();
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004724 if (!V)
4725 return 0;
Devang Patel00190342010-03-15 19:15:44 +00004726
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004727 SDDbgValue *SDV;
Devang Patel57871242011-08-03 23:13:55 +00004728 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004729 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4730 DAG.AddDbgValue(SDV, 0, false);
Devang Patel00190342010-03-15 19:15:44 +00004731 } else {
Dale Johannesenbdc09d92010-07-16 00:02:08 +00004732 // Do not use getValue() in here; we don't want to generate code at
4733 // this point if it hasn't been done yet.
Devang Patel9126c0d2010-06-01 19:59:01 +00004734 SDValue N = NodeMap[V];
4735 if (!N.getNode() && isa<Argument>(V))
4736 // Check unused arguments map.
4737 N = UnusedArgNodeMap[V];
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004738 if (N.getNode()) {
Devang Patel78a06e52010-08-25 20:39:26 +00004739 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004740 SDV = DAG.getDbgValue(Variable, N.getNode(),
4741 N.getResNo(), Offset, dl, SDNodeOrder);
4742 DAG.AddDbgValue(SDV, N.getNode(), false);
4743 }
Devang Patela778f5c2011-02-18 22:43:42 +00004744 } else if (!V->use_empty() ) {
Dale Johannesenbdc09d92010-07-16 00:02:08 +00004745 // Do not call getValue(V) yet, as we don't want to generate code.
4746 // Remember it for later.
4747 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4748 DanglingDebugInfoMap[V] = DDI;
Devang Patel0991dfb2010-08-27 22:25:51 +00004749 } else {
Devang Patel00190342010-03-15 19:15:44 +00004750 // We may expand this to cover more cases. One case where we have no
Devang Patelafeaae72010-12-06 22:39:26 +00004751 // data available is an unreferenced parameter.
Eric Christopher0822e012012-02-23 03:39:43 +00004752 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004753 }
Devang Patel00190342010-03-15 19:15:44 +00004754 }
4755
4756 // Build a debug info table entry.
Dan Gohman46510a72010-04-15 01:51:59 +00004757 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004758 V = BCI->getOperand(0);
Dan Gohman46510a72010-04-15 01:51:59 +00004759 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004760 // Don't handle byval struct arguments or VLAs, for example.
Eric Christopher7e1e18f2012-03-26 06:10:32 +00004761 if (!AI) {
Eric Christopher9fc5c832012-03-28 07:34:36 +00004762 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4763 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004764 return 0;
Eric Christopher7e1e18f2012-03-26 06:10:32 +00004765 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004766 DenseMap<const AllocaInst*, int>::iterator SI =
4767 FuncInfo.StaticAllocaMap.find(AI);
4768 if (SI == FuncInfo.StaticAllocaMap.end())
4769 return 0; // VLAs.
4770 int FI = SI->second;
Michael J. Spencere70c5262010-10-16 08:25:21 +00004771
Chris Lattner512063d2010-04-05 06:19:28 +00004772 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4773 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4774 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004775 return 0;
4776 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004777
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004778 case Intrinsic::eh_typeid_for: {
Chris Lattner512063d2010-04-05 06:19:28 +00004779 // Find the type id for the given typeinfo.
Gabor Greif0635f352010-06-25 09:38:13 +00004780 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
Chris Lattner512063d2010-04-05 06:19:28 +00004781 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4782 Res = DAG.getConstant(TypeID, MVT::i32);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004783 setValue(&I, Res);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004784 return 0;
4785 }
4786
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004787 case Intrinsic::eh_return_i32:
4788 case Intrinsic::eh_return_i64:
Chris Lattner512063d2010-04-05 06:19:28 +00004789 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004790 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
Chris Lattner512063d2010-04-05 06:19:28 +00004791 MVT::Other,
4792 getControlRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00004793 getValue(I.getArgOperand(0)),
4794 getValue(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004795 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004796 case Intrinsic::eh_unwind_init:
Chris Lattner512063d2010-04-05 06:19:28 +00004797 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004798 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004799 case Intrinsic::eh_dwarf_cfa: {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004800 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
Bill Wendlingba54bca2013-06-19 21:36:55 +00004801 TLI->getPointerTy());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004802 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
Tom Stellardedd08f72013-08-26 15:06:10 +00004803 CfaArg.getValueType(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00004804 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
Tom Stellardedd08f72013-08-26 15:06:10 +00004805 CfaArg.getValueType()),
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004806 CfaArg);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004807 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl,
Bill Wendlingba54bca2013-06-19 21:36:55 +00004808 TLI->getPointerTy(),
4809 DAG.getConstant(0, TLI->getPointerTy()));
Tom Stellardedd08f72013-08-26 15:06:10 +00004810 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
Bill Wendling4533cac2010-01-28 21:51:40 +00004811 FA, Offset));
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004812 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004813 }
Jim Grosbachca752c92010-01-28 01:45:32 +00004814 case Intrinsic::eh_sjlj_callsite: {
Chris Lattner512063d2010-04-05 06:19:28 +00004815 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Gabor Greif0635f352010-06-25 09:38:13 +00004816 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
Jim Grosbachca752c92010-01-28 01:45:32 +00004817 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
Chris Lattner512063d2010-04-05 06:19:28 +00004818 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
Jim Grosbachca752c92010-01-28 01:45:32 +00004819
Chris Lattner512063d2010-04-05 06:19:28 +00004820 MMI.setCurrentCallSite(CI->getZExtValue());
Jim Grosbachca752c92010-01-28 01:45:32 +00004821 return 0;
4822 }
Bill Wendling6ef94172011-09-28 03:36:43 +00004823 case Intrinsic::eh_sjlj_functioncontext: {
4824 // Get and store the index of the function context.
4825 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
Bill Wendlingadbf7b22011-09-28 03:52:41 +00004826 AllocaInst *FnCtx =
4827 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
Bill Wendling6ef94172011-09-28 03:36:43 +00004828 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4829 MFI->setFunctionContextIndex(FI);
4830 return 0;
4831 }
Jim Grosbach23ff7cf2010-05-26 20:22:18 +00004832 case Intrinsic::eh_sjlj_setjmp: {
Bill Wendlingce370cf2011-10-07 21:25:38 +00004833 SDValue Ops[2];
4834 Ops[0] = getRoot();
4835 Ops[1] = getValue(I.getArgOperand(0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00004836 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
Bill Wendlingce370cf2011-10-07 21:25:38 +00004837 DAG.getVTList(MVT::i32, MVT::Other),
4838 Ops, 2);
4839 setValue(&I, Op.getValue(0));
4840 DAG.setRoot(Op.getValue(1));
Jim Grosbach23ff7cf2010-05-26 20:22:18 +00004841 return 0;
4842 }
Jim Grosbach5eb19512010-05-22 01:06:18 +00004843 case Intrinsic::eh_sjlj_longjmp: {
Andrew Trickac6d9be2013-05-25 02:42:55 +00004844 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
Jim Grosbache4ad3872010-10-19 23:27:08 +00004845 getRoot(), getValue(I.getArgOperand(0))));
4846 return 0;
4847 }
Jim Grosbachca752c92010-01-28 01:45:32 +00004848
Dale Johannesen0488fb62010-09-30 23:57:10 +00004849 case Intrinsic::x86_mmx_pslli_w:
4850 case Intrinsic::x86_mmx_pslli_d:
4851 case Intrinsic::x86_mmx_pslli_q:
4852 case Intrinsic::x86_mmx_psrli_w:
4853 case Intrinsic::x86_mmx_psrli_d:
4854 case Intrinsic::x86_mmx_psrli_q:
4855 case Intrinsic::x86_mmx_psrai_w:
4856 case Intrinsic::x86_mmx_psrai_d: {
4857 SDValue ShAmt = getValue(I.getArgOperand(1));
4858 if (isa<ConstantSDNode>(ShAmt)) {
4859 visitTargetIntrinsic(I, Intrinsic);
4860 return 0;
4861 }
4862 unsigned NewIntrinsic = 0;
4863 EVT ShAmtVT = MVT::v2i32;
4864 switch (Intrinsic) {
4865 case Intrinsic::x86_mmx_pslli_w:
4866 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4867 break;
4868 case Intrinsic::x86_mmx_pslli_d:
4869 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4870 break;
4871 case Intrinsic::x86_mmx_pslli_q:
4872 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4873 break;
4874 case Intrinsic::x86_mmx_psrli_w:
4875 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4876 break;
4877 case Intrinsic::x86_mmx_psrli_d:
4878 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4879 break;
4880 case Intrinsic::x86_mmx_psrli_q:
4881 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4882 break;
4883 case Intrinsic::x86_mmx_psrai_w:
4884 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4885 break;
4886 case Intrinsic::x86_mmx_psrai_d:
4887 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4888 break;
4889 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4890 }
4891
4892 // The vector shift intrinsics with scalars uses 32b shift amounts but
4893 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4894 // to be zero.
4895 // We must do this early because v2i32 is not a legal type.
Dale Johannesen0488fb62010-09-30 23:57:10 +00004896 SDValue ShOps[2];
4897 ShOps[0] = ShAmt;
4898 ShOps[1] = DAG.getConstant(0, MVT::i32);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004899 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, &ShOps[0], 2);
Bill Wendlingba54bca2013-06-19 21:36:55 +00004900 EVT DestVT = TLI->getValueType(I.getType());
Andrew Trickac6d9be2013-05-25 02:42:55 +00004901 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4902 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
Dale Johannesen0488fb62010-09-30 23:57:10 +00004903 DAG.getConstant(NewIntrinsic, MVT::i32),
4904 getValue(I.getArgOperand(0)), ShAmt);
4905 setValue(&I, Res);
4906 return 0;
4907 }
Pete Cooperd18134f2012-02-24 03:51:49 +00004908 case Intrinsic::x86_avx_vinsertf128_pd_256:
4909 case Intrinsic::x86_avx_vinsertf128_ps_256:
Craig Topperb45c9692012-04-07 22:32:29 +00004910 case Intrinsic::x86_avx_vinsertf128_si_256:
4911 case Intrinsic::x86_avx2_vinserti128: {
Bill Wendlingba54bca2013-06-19 21:36:55 +00004912 EVT DestVT = TLI->getValueType(I.getType());
4913 EVT ElVT = TLI->getValueType(I.getArgOperand(1)->getType());
Pete Cooperd18134f2012-02-24 03:51:49 +00004914 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
4915 ElVT.getVectorNumElements();
Andrew Trickac6d9be2013-05-25 02:42:55 +00004916 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
Pete Cooperd18134f2012-02-24 03:51:49 +00004917 getValue(I.getArgOperand(0)),
4918 getValue(I.getArgOperand(1)),
Tom Stellard425b76c2013-08-05 22:22:01 +00004919 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
Craig Topperf6dc7922012-09-05 05:48:09 +00004920 setValue(&I, Res);
4921 return 0;
4922 }
4923 case Intrinsic::x86_avx_vextractf128_pd_256:
4924 case Intrinsic::x86_avx_vextractf128_ps_256:
4925 case Intrinsic::x86_avx_vextractf128_si_256:
4926 case Intrinsic::x86_avx2_vextracti128: {
Bill Wendlingba54bca2013-06-19 21:36:55 +00004927 EVT DestVT = TLI->getValueType(I.getType());
Craig Topperf6dc7922012-09-05 05:48:09 +00004928 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
4929 DestVT.getVectorNumElements();
Andrew Trickac6d9be2013-05-25 02:42:55 +00004930 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
Craig Topperf6dc7922012-09-05 05:48:09 +00004931 getValue(I.getArgOperand(0)),
Tom Stellard425b76c2013-08-05 22:22:01 +00004932 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
Pete Cooperd18134f2012-02-24 03:51:49 +00004933 setValue(&I, Res);
4934 return 0;
4935 }
Mon P Wang77cdf302008-11-10 20:54:11 +00004936 case Intrinsic::convertff:
4937 case Intrinsic::convertfsi:
4938 case Intrinsic::convertfui:
4939 case Intrinsic::convertsif:
4940 case Intrinsic::convertuif:
4941 case Intrinsic::convertss:
4942 case Intrinsic::convertsu:
4943 case Intrinsic::convertus:
4944 case Intrinsic::convertuu: {
4945 ISD::CvtCode Code = ISD::CVT_INVALID;
4946 switch (Intrinsic) {
Craig Topperc42e6402012-04-11 04:34:11 +00004947 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
Mon P Wang77cdf302008-11-10 20:54:11 +00004948 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4949 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4950 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4951 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4952 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4953 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4954 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4955 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4956 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4957 }
Bill Wendlingba54bca2013-06-19 21:36:55 +00004958 EVT DestVT = TLI->getValueType(I.getType());
Gabor Greif0635f352010-06-25 09:38:13 +00004959 const Value *Op1 = I.getArgOperand(0);
Andrew Trickac6d9be2013-05-25 02:42:55 +00004960 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004961 DAG.getValueType(DestVT),
4962 DAG.getValueType(getValue(Op1).getValueType()),
Gabor Greif0635f352010-06-25 09:38:13 +00004963 getValue(I.getArgOperand(1)),
4964 getValue(I.getArgOperand(2)),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004965 Code);
4966 setValue(&I, Res);
Mon P Wang77cdf302008-11-10 20:54:11 +00004967 return 0;
4968 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004969 case Intrinsic::powi:
Andrew Trickac6d9be2013-05-25 02:42:55 +00004970 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
Gabor Greif0635f352010-06-25 09:38:13 +00004971 getValue(I.getArgOperand(1)), DAG));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004972 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004973 case Intrinsic::log:
Bill Wendlingba54bca2013-06-19 21:36:55 +00004974 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004975 return 0;
4976 case Intrinsic::log2:
Bill Wendlingba54bca2013-06-19 21:36:55 +00004977 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004978 return 0;
4979 case Intrinsic::log10:
Bill Wendlingba54bca2013-06-19 21:36:55 +00004980 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004981 return 0;
4982 case Intrinsic::exp:
Bill Wendlingba54bca2013-06-19 21:36:55 +00004983 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004984 return 0;
4985 case Intrinsic::exp2:
Bill Wendlingba54bca2013-06-19 21:36:55 +00004986 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004987 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004988 case Intrinsic::pow:
Andrew Trickac6d9be2013-05-25 02:42:55 +00004989 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
Bill Wendlingba54bca2013-06-19 21:36:55 +00004990 getValue(I.getArgOperand(1)), DAG, *TLI));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004991 return 0;
Craig Topper9bd4dd72012-11-16 07:48:23 +00004992 case Intrinsic::sqrt:
Peter Collingbourneb34d3aa2012-05-28 21:48:37 +00004993 case Intrinsic::fabs:
Craig Topper9bd4dd72012-11-16 07:48:23 +00004994 case Intrinsic::sin:
4995 case Intrinsic::cos:
Dan Gohman27db99f2012-07-26 17:43:27 +00004996 case Intrinsic::floor:
Craig Topper49010472012-11-15 06:51:10 +00004997 case Intrinsic::ceil:
Craig Topper49010472012-11-15 06:51:10 +00004998 case Intrinsic::trunc:
Craig Topper49010472012-11-15 06:51:10 +00004999 case Intrinsic::rint:
Hal Finkel41418d12013-08-07 22:49:12 +00005000 case Intrinsic::nearbyint:
5001 case Intrinsic::round: {
Craig Topper9bd4dd72012-11-16 07:48:23 +00005002 unsigned Opcode;
5003 switch (Intrinsic) {
5004 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5005 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5006 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5007 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5008 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5009 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5010 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5011 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5012 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5013 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
Hal Finkel41418d12013-08-07 22:49:12 +00005014 case Intrinsic::round: Opcode = ISD::FROUND; break;
Craig Topper9bd4dd72012-11-16 07:48:23 +00005015 }
5016
Andrew Trickac6d9be2013-05-25 02:42:55 +00005017 setValue(&I, DAG.getNode(Opcode, sdl,
Craig Topper49010472012-11-15 06:51:10 +00005018 getValue(I.getArgOperand(0)).getValueType(),
5019 getValue(I.getArgOperand(0))));
5020 return 0;
Craig Topper9bd4dd72012-11-16 07:48:23 +00005021 }
Hal Finkel66d1fa62013-08-19 23:35:46 +00005022 case Intrinsic::copysign:
5023 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5024 getValue(I.getArgOperand(0)).getValueType(),
5025 getValue(I.getArgOperand(0)),
5026 getValue(I.getArgOperand(1))));
5027 return 0;
Cameron Zwarich33390842011-07-08 21:39:21 +00005028 case Intrinsic::fma:
Andrew Trickac6d9be2013-05-25 02:42:55 +00005029 setValue(&I, DAG.getNode(ISD::FMA, sdl,
Cameron Zwarich33390842011-07-08 21:39:21 +00005030 getValue(I.getArgOperand(0)).getValueType(),
5031 getValue(I.getArgOperand(0)),
5032 getValue(I.getArgOperand(1)),
5033 getValue(I.getArgOperand(2))));
5034 return 0;
Lang Hames5afba6f2012-06-05 19:07:46 +00005035 case Intrinsic::fmuladd: {
Bill Wendlingba54bca2013-06-19 21:36:55 +00005036 EVT VT = TLI->getValueType(I.getType());
Lang Hamese0231412012-06-22 01:09:09 +00005037 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
Stephen Line54885a2013-07-09 18:16:56 +00005038 TLI->isFMAFasterThanFMulAndFAdd(VT)) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005039 setValue(&I, DAG.getNode(ISD::FMA, sdl,
Lang Hames5afba6f2012-06-05 19:07:46 +00005040 getValue(I.getArgOperand(0)).getValueType(),
5041 getValue(I.getArgOperand(0)),
5042 getValue(I.getArgOperand(1)),
5043 getValue(I.getArgOperand(2))));
5044 } else {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005045 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
Lang Hames5afba6f2012-06-05 19:07:46 +00005046 getValue(I.getArgOperand(0)).getValueType(),
5047 getValue(I.getArgOperand(0)),
5048 getValue(I.getArgOperand(1)));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005049 SDValue Add = DAG.getNode(ISD::FADD, sdl,
Lang Hames5afba6f2012-06-05 19:07:46 +00005050 getValue(I.getArgOperand(0)).getValueType(),
5051 Mul,
5052 getValue(I.getArgOperand(2)));
5053 setValue(&I, Add);
5054 }
5055 return 0;
5056 }
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00005057 case Intrinsic::convert_to_fp16:
Andrew Trickac6d9be2013-05-25 02:42:55 +00005058 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, sdl,
Gabor Greif0635f352010-06-25 09:38:13 +00005059 MVT::i16, getValue(I.getArgOperand(0))));
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00005060 return 0;
5061 case Intrinsic::convert_from_fp16:
Andrew Trickac6d9be2013-05-25 02:42:55 +00005062 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, sdl,
Gabor Greif0635f352010-06-25 09:38:13 +00005063 MVT::f32, getValue(I.getArgOperand(0))));
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00005064 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005065 case Intrinsic::pcmarker: {
Gabor Greif0635f352010-06-25 09:38:13 +00005066 SDValue Tmp = getValue(I.getArgOperand(0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005067 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005068 return 0;
5069 }
5070 case Intrinsic::readcyclecounter: {
5071 SDValue Op = getRoot();
Andrew Trickac6d9be2013-05-25 02:42:55 +00005072 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005073 DAG.getVTList(MVT::i64, MVT::Other),
5074 &Op, 1);
5075 setValue(&I, Res);
5076 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005077 return 0;
5078 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005079 case Intrinsic::bswap:
Andrew Trickac6d9be2013-05-25 02:42:55 +00005080 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
Gabor Greif0635f352010-06-25 09:38:13 +00005081 getValue(I.getArgOperand(0)).getValueType(),
5082 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005083 return 0;
5084 case Intrinsic::cttz: {
Gabor Greif0635f352010-06-25 09:38:13 +00005085 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth63974b22011-12-13 01:56:10 +00005086 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00005087 EVT Ty = Arg.getValueType();
Chandler Carruth63974b22011-12-13 01:56:10 +00005088 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
Andrew Trickac6d9be2013-05-25 02:42:55 +00005089 sdl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005090 return 0;
5091 }
5092 case Intrinsic::ctlz: {
Gabor Greif0635f352010-06-25 09:38:13 +00005093 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth63974b22011-12-13 01:56:10 +00005094 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00005095 EVT Ty = Arg.getValueType();
Chandler Carruth63974b22011-12-13 01:56:10 +00005096 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
Andrew Trickac6d9be2013-05-25 02:42:55 +00005097 sdl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005098 return 0;
5099 }
5100 case Intrinsic::ctpop: {
Gabor Greif0635f352010-06-25 09:38:13 +00005101 SDValue Arg = getValue(I.getArgOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00005102 EVT Ty = Arg.getValueType();
Andrew Trickac6d9be2013-05-25 02:42:55 +00005103 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005104 return 0;
5105 }
5106 case Intrinsic::stacksave: {
5107 SDValue Op = getRoot();
Andrew Trickac6d9be2013-05-25 02:42:55 +00005108 Res = DAG.getNode(ISD::STACKSAVE, sdl,
Bill Wendlingba54bca2013-06-19 21:36:55 +00005109 DAG.getVTList(TLI->getPointerTy(), MVT::Other), &Op, 1);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005110 setValue(&I, Res);
5111 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005112 return 0;
5113 }
5114 case Intrinsic::stackrestore: {
Gabor Greif0635f352010-06-25 09:38:13 +00005115 Res = getValue(I.getArgOperand(0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005116 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005117 return 0;
5118 }
Bill Wendling57344502008-11-18 11:01:33 +00005119 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00005120 // Emit code into the DAG to store the stack guard onto the stack.
5121 MachineFunction &MF = DAG.getMachineFunction();
5122 MachineFrameInfo *MFI = MF.getFrameInfo();
Bill Wendlingba54bca2013-06-19 21:36:55 +00005123 EVT PtrTy = TLI->getPointerTy();
Bill Wendlingb2a42982008-11-06 02:29:10 +00005124
Gabor Greif0635f352010-06-25 09:38:13 +00005125 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
5126 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
Bill Wendlingb2a42982008-11-06 02:29:10 +00005127
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00005128 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00005129 MFI->setStackProtectorIndex(FI);
5130
5131 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5132
5133 // Store the stack protector onto the stack.
Andrew Trickac6d9be2013-05-25 02:42:55 +00005134 Res = DAG.getStore(getRoot(), sdl, Src, FIN,
Chris Lattner84bd98a2010-09-21 18:58:22 +00005135 MachinePointerInfo::getFixedStack(FI),
5136 true, false, 0);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005137 setValue(&I, Res);
5138 DAG.setRoot(Res);
Bill Wendlingb2a42982008-11-06 02:29:10 +00005139 return 0;
5140 }
Eric Christopher7b5e6172009-10-27 00:52:25 +00005141 case Intrinsic::objectsize: {
5142 // If we don't know by now, we're never going to know.
Gabor Greif0635f352010-06-25 09:38:13 +00005143 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
Eric Christopher7b5e6172009-10-27 00:52:25 +00005144
5145 assert(CI && "Non-constant type in __builtin_object_size?");
5146
Gabor Greif0635f352010-06-25 09:38:13 +00005147 SDValue Arg = getValue(I.getCalledValue());
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00005148 EVT Ty = Arg.getValueType();
5149
Dan Gohmane368b462010-06-18 14:22:04 +00005150 if (CI->isZero())
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005151 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7b5e6172009-10-27 00:52:25 +00005152 else
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005153 Res = DAG.getConstant(0, Ty);
5154
5155 setValue(&I, Res);
Eric Christopher7b5e6172009-10-27 00:52:25 +00005156 return 0;
5157 }
Justin Holewinskic2b7f5f2013-05-21 14:37:16 +00005158 case Intrinsic::annotation:
5159 case Intrinsic::ptr_annotation:
5160 // Drop the intrinsic, but forward the value
5161 setValue(&I, getValue(I.getOperand(0)));
5162 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005163 case Intrinsic::var_annotation:
5164 // Discard annotate attributes
5165 return 0;
5166
5167 case Intrinsic::init_trampoline: {
Gabor Greif0635f352010-06-25 09:38:13 +00005168 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005169
5170 SDValue Ops[6];
5171 Ops[0] = getRoot();
Gabor Greif0635f352010-06-25 09:38:13 +00005172 Ops[1] = getValue(I.getArgOperand(0));
5173 Ops[2] = getValue(I.getArgOperand(1));
5174 Ops[3] = getValue(I.getArgOperand(2));
5175 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005176 Ops[5] = DAG.getSrcValue(F);
5177
Andrew Trickac6d9be2013-05-25 02:42:55 +00005178 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005179
Duncan Sands4a544a72011-09-06 13:37:06 +00005180 DAG.setRoot(Res);
5181 return 0;
5182 }
5183 case Intrinsic::adjust_trampoline: {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005184 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
Bill Wendlingba54bca2013-06-19 21:36:55 +00005185 TLI->getPointerTy(),
Duncan Sands4a544a72011-09-06 13:37:06 +00005186 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005187 return 0;
5188 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005189 case Intrinsic::gcroot:
5190 if (GFI) {
Bill Wendling95dd4422012-05-01 22:50:45 +00005191 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
Gabor Greif0635f352010-06-25 09:38:13 +00005192 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005193
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005194 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5195 GFI->addStackRoot(FI->getIndex(), TypeMap);
5196 }
5197 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005198 case Intrinsic::gcread:
5199 case Intrinsic::gcwrite:
Torok Edwinc23197a2009-07-14 16:55:14 +00005200 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005201 case Intrinsic::flt_rounds:
Andrew Trickac6d9be2013-05-25 02:42:55 +00005202 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005203 return 0;
Jakub Staszak9da99342011-07-06 18:22:43 +00005204
5205 case Intrinsic::expect: {
5206 // Just replace __builtin_expect(exp, c) with EXP.
5207 setValue(&I, getValue(I.getArgOperand(0)));
5208 return 0;
5209 }
5210
Shuxin Yang970755e2012-10-19 20:11:16 +00005211 case Intrinsic::debugtrap:
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005212 case Intrinsic::trap: {
Nick Lewycky8a8d4792011-12-02 22:16:29 +00005213 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005214 if (TrapFuncName.empty()) {
Stephen Lin155615d2013-07-08 00:37:03 +00005215 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
Shuxin Yang970755e2012-10-19 20:11:16 +00005216 ISD::TRAP : ISD::DEBUGTRAP;
Andrew Trickac6d9be2013-05-25 02:42:55 +00005217 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005218 return 0;
5219 }
5220 TargetLowering::ArgListTy Args;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00005221 TargetLowering::
5222 CallLoweringInfo CLI(getRoot(), I.getType(),
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005223 false, false, false, false, 0, CallingConv::C,
Evan Cheng4bfcd4a2012-02-28 18:51:51 +00005224 /*isTailCall=*/false,
5225 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
Bill Wendlingba54bca2013-06-19 21:36:55 +00005226 DAG.getExternalSymbol(TrapFuncName.data(),
5227 TLI->getPointerTy()),
Andrew Trickac6d9be2013-05-25 02:42:55 +00005228 Args, DAG, sdl);
Bill Wendlingba54bca2013-06-19 21:36:55 +00005229 std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005230 DAG.setRoot(Result.second);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005231 return 0;
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005232 }
Shuxin Yang970755e2012-10-19 20:11:16 +00005233
Bill Wendlingef375462008-11-21 02:38:44 +00005234 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005235 case Intrinsic::sadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005236 case Intrinsic::usub_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005237 case Intrinsic::ssub_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005238 case Intrinsic::umul_with_overflow:
Craig Topperc42e6402012-04-11 04:34:11 +00005239 case Intrinsic::smul_with_overflow: {
5240 ISD::NodeType Op;
5241 switch (Intrinsic) {
5242 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5243 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5244 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5245 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5246 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5247 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5248 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5249 }
5250 SDValue Op1 = getValue(I.getArgOperand(0));
5251 SDValue Op2 = getValue(I.getArgOperand(1));
Bill Wendling7cdc3c82008-11-21 02:03:52 +00005252
Craig Topperc42e6402012-04-11 04:34:11 +00005253 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005254 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
Craig Topperc42e6402012-04-11 04:34:11 +00005255 return 0;
5256 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005257 case Intrinsic::prefetch: {
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005258 SDValue Ops[5];
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005259 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005260 Ops[0] = getRoot();
Gabor Greif0635f352010-06-25 09:38:13 +00005261 Ops[1] = getValue(I.getArgOperand(0));
5262 Ops[2] = getValue(I.getArgOperand(1));
5263 Ops[3] = getValue(I.getArgOperand(2));
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005264 Ops[4] = getValue(I.getArgOperand(3));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005265 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005266 DAG.getVTList(MVT::Other),
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005267 &Ops[0], 5,
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005268 EVT::getIntegerVT(*Context, 8),
5269 MachinePointerInfo(I.getArgOperand(0)),
5270 0, /* align */
5271 false, /* volatile */
5272 rw==0, /* read */
5273 rw==1)); /* write */
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005274 return 0;
5275 }
Duncan Sandsf07c9492009-11-10 09:08:09 +00005276 case Intrinsic::lifetime_start:
Nadav Rotemc05d3062012-09-06 09:17:37 +00005277 case Intrinsic::lifetime_end: {
Nadav Rotemc05d3062012-09-06 09:17:37 +00005278 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
Nadav Rotem9a2ae002012-09-10 08:43:23 +00005279 // Stack coloring is not enabled in O0, discard region information.
5280 if (TM.getOptLevel() == CodeGenOpt::None)
5281 return 0;
Nadav Rotemc05d3062012-09-06 09:17:37 +00005282
Nadav Rotem9a2ae002012-09-10 08:43:23 +00005283 SmallVector<Value *, 4> Allocas;
5284 GetUnderlyingObjects(I.getArgOperand(1), Allocas, TD);
5285
Craig Topperf22fd3f2013-07-03 05:11:49 +00005286 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5287 E = Allocas.end(); Object != E; ++Object) {
Nadav Rotem9a2ae002012-09-10 08:43:23 +00005288 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5289
5290 // Could not find an Alloca.
5291 if (!LifetimeObject)
5292 continue;
5293
5294 int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
5295
5296 SDValue Ops[2];
5297 Ops[0] = getRoot();
Bill Wendlingba54bca2013-06-19 21:36:55 +00005298 Ops[1] = DAG.getFrameIndex(FI, TLI->getPointerTy(), true);
Nadav Rotem9a2ae002012-09-10 08:43:23 +00005299 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5300
Andrew Trickac6d9be2013-05-25 02:42:55 +00005301 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops, 2);
Nadav Rotem9a2ae002012-09-10 08:43:23 +00005302 DAG.setRoot(Res);
5303 }
Nadav Rotem5882e562013-02-01 19:25:23 +00005304 return 0;
Nadav Rotemc05d3062012-09-06 09:17:37 +00005305 }
5306 case Intrinsic::invariant_start:
Duncan Sandsf07c9492009-11-10 09:08:09 +00005307 // Discard region information.
Bill Wendlingba54bca2013-06-19 21:36:55 +00005308 setValue(&I, DAG.getUNDEF(TLI->getPointerTy()));
Duncan Sandsf07c9492009-11-10 09:08:09 +00005309 return 0;
5310 case Intrinsic::invariant_end:
Duncan Sandsf07c9492009-11-10 09:08:09 +00005311 // Discard region information.
5312 return 0;
Michael Gottesman657484f2013-08-20 07:00:16 +00005313 case Intrinsic::stackprotectorcheck: {
5314 // Do not actually emit anything for this basic block. Instead we initialize
5315 // the stack protector descriptor and export the guard variable so we can
5316 // access it in FinishBasicBlock.
5317 const BasicBlock *BB = I.getParent();
5318 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5319 ExportFromCurrentBlock(SPDescriptor.getGuard());
5320
5321 // Flush our exports since we are going to process a terminator.
5322 (void)getControlRoot();
5323 return 0;
5324 }
Nuno Lopes85b40892012-06-28 22:30:12 +00005325 case Intrinsic::donothing:
5326 // ignore
5327 return 0;
Andrew Trick2343e3b2013-10-31 17:18:24 +00005328 case Intrinsic::experimental_stackmap: {
5329 visitStackmap(I);
5330 return 0;
5331 }
5332 case Intrinsic::experimental_patchpoint_void:
5333 case Intrinsic::experimental_patchpoint_i64: {
5334 visitPatchpoint(I);
5335 return 0;
5336 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005337 }
5338}
5339
Dan Gohman46510a72010-04-15 01:51:59 +00005340void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
Dan Gohman2048b852009-11-23 18:04:58 +00005341 bool isTailCall,
5342 MachineBasicBlock *LandingPad) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005343 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5344 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5345 Type *RetTy = FTy->getReturnType();
Chris Lattner512063d2010-04-05 06:19:28 +00005346 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Chris Lattner16112732010-03-14 01:41:15 +00005347 MCSymbol *BeginLabel = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005348
5349 TargetLowering::ArgListTy Args;
5350 TargetLowering::ArgListEntry Entry;
5351 Args.reserve(CS.arg_size());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005352
5353 // Check whether the function can return without sret-demotion.
Dan Gohman84023e02010-07-10 09:00:22 +00005354 SmallVector<ISD::OutputArg, 4> Outs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00005355 const TargetLowering *TLI = TM.getTargetLowering();
5356 GetReturnInfo(RetTy, CS.getAttributes(), Outs, *TLI);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005357
Bill Wendlingba54bca2013-06-19 21:36:55 +00005358 bool CanLowerReturn = TLI->CanLowerReturn(CS.getCallingConv(),
5359 DAG.getMachineFunction(),
5360 FTy->isVarArg(), Outs,
5361 FTy->getContext());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005362
5363 SDValue DemoteStackSlot;
Chris Lattnerecf42c42010-09-21 16:36:31 +00005364 int DemoteStackIdx = -100;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005365
5366 if (!CanLowerReturn) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00005367 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005368 FTy->getReturnType());
Bill Wendlingba54bca2013-06-19 21:36:55 +00005369 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005370 FTy->getReturnType());
5371 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerecf42c42010-09-21 16:36:31 +00005372 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005373 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005374
Bill Wendlingba54bca2013-06-19 21:36:55 +00005375 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI->getPointerTy());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005376 Entry.Node = DemoteStackSlot;
5377 Entry.Ty = StackSlotPtrType;
5378 Entry.isSExt = false;
5379 Entry.isZExt = false;
5380 Entry.isInReg = false;
5381 Entry.isSRet = true;
5382 Entry.isNest = false;
5383 Entry.isByVal = false;
Stephen Lin456ca042013-04-20 05:14:40 +00005384 Entry.isReturned = false;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005385 Entry.Alignment = Align;
5386 Args.push_back(Entry);
5387 RetTy = Type::getVoidTy(FTy->getContext());
5388 }
5389
Dan Gohman46510a72010-04-15 01:51:59 +00005390 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005391 i != e; ++i) {
Rafael Espindola3fa82832011-05-13 15:18:06 +00005392 const Value *V = *i;
5393
5394 // Skip empty types
5395 if (V->getType()->isEmptyTy())
5396 continue;
5397
5398 SDValue ArgNode = getValue(V);
5399 Entry.Node = ArgNode; Entry.Ty = V->getType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005400
Andrew Trick2343e3b2013-10-31 17:18:24 +00005401 // Skip the first return-type Attribute to get to params.
5402 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005403 Args.push_back(Entry);
5404 }
5405
Chris Lattner512063d2010-04-05 06:19:28 +00005406 if (LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005407 // Insert a label before the invoke call to mark the try range. This can be
5408 // used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattner512063d2010-04-05 06:19:28 +00005409 BeginLabel = MMI.getContext().CreateTempSymbol();
Jim Grosbach1b747ad2009-08-11 00:09:57 +00005410
Jim Grosbachca752c92010-01-28 01:45:32 +00005411 // For SjLj, keep track of which landing pads go with which invokes
5412 // so as to maintain the ordering of pads in the LSDA.
Chris Lattner512063d2010-04-05 06:19:28 +00005413 unsigned CallSiteIndex = MMI.getCurrentCallSite();
Jim Grosbachca752c92010-01-28 01:45:32 +00005414 if (CallSiteIndex) {
Chris Lattner512063d2010-04-05 06:19:28 +00005415 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
Bill Wendling30e67402011-10-05 22:24:35 +00005416 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
Bill Wendlinga8512ed2011-10-04 22:00:35 +00005417
Jim Grosbachca752c92010-01-28 01:45:32 +00005418 // Now that the call site is handled, stop tracking it.
Chris Lattner512063d2010-04-05 06:19:28 +00005419 MMI.setCurrentCallSite(0);
Jim Grosbachca752c92010-01-28 01:45:32 +00005420 }
5421
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005422 // Both PendingLoads and PendingExports must be flushed here;
5423 // this call might not return.
5424 (void)getRoot();
Andrew Trickac6d9be2013-05-25 02:42:55 +00005425 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005426 }
5427
Dan Gohman98ca4f22009-08-05 01:29:28 +00005428 // Check if target-independent constraints permit a tail call here.
Bill Wendlingba54bca2013-06-19 21:36:55 +00005429 // Target-dependent constraints are checked within TLI->LowerCallTo.
5430 if (isTailCall && !isInTailCallPosition(CS, *TLI))
Dan Gohman98ca4f22009-08-05 01:29:28 +00005431 isTailCall = false;
5432
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00005433 TargetLowering::
5434 CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG,
Andrew Trickac6d9be2013-05-25 02:42:55 +00005435 getCurSDLoc(), CS);
Bill Wendlingba54bca2013-06-19 21:36:55 +00005436 std::pair<SDValue,SDValue> Result = TLI->LowerCallTo(CLI);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005437 assert((isTailCall || Result.second.getNode()) &&
5438 "Non-null chain expected with non-tail call!");
5439 assert((Result.second.getNode() || !Result.first.getNode()) &&
5440 "Null value expected with tail call!");
Bill Wendlinge80ae832009-12-22 00:50:32 +00005441 if (Result.first.getNode()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005442 setValue(CS.getInstruction(), Result.first);
Bill Wendlinge80ae832009-12-22 00:50:32 +00005443 } else if (!CanLowerReturn && Result.second.getNode()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005444 // The instruction result is the result of loading from the
5445 // hidden sret parameter.
5446 SmallVector<EVT, 1> PVTs;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005447 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005448
Bill Wendlingba54bca2013-06-19 21:36:55 +00005449 ComputeValueVTs(*TLI, PtrRetTy, PVTs);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005450 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5451 EVT PtrVT = PVTs[0];
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005452
5453 SmallVector<EVT, 4> RetTys;
5454 SmallVector<uint64_t, 4> Offsets;
5455 RetTy = FTy->getReturnType();
Bill Wendlingba54bca2013-06-19 21:36:55 +00005456 ComputeValueVTs(*TLI, RetTy, RetTys, &Offsets);
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005457
5458 unsigned NumValues = RetTys.size();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005459 SmallVector<SDValue, 4> Values(NumValues);
5460 SmallVector<SDValue, 4> Chains(NumValues);
5461
5462 for (unsigned i = 0; i < NumValues; ++i) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00005463 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT,
Bill Wendlinge80ae832009-12-22 00:50:32 +00005464 DemoteStackSlot,
5465 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005466 SDValue L = DAG.getLoad(RetTys[i], getCurSDLoc(), Result.second, Add,
Chris Lattnerecf42c42010-09-21 16:36:31 +00005467 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
Pete Cooperd752e0f2011-11-08 18:42:53 +00005468 false, false, false, 1);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005469 Values[i] = L;
5470 Chains[i] = L.getValue(1);
5471 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00005472
Andrew Trickac6d9be2013-05-25 02:42:55 +00005473 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005474 MVT::Other, &Chains[0], NumValues);
5475 PendingLoads.push_back(Chain);
Michael J. Spencere70c5262010-10-16 08:25:21 +00005476
Bill Wendling4533cac2010-01-28 21:51:40 +00005477 setValue(CS.getInstruction(),
Andrew Trickac6d9be2013-05-25 02:42:55 +00005478 DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00005479 DAG.getVTList(&RetTys[0], RetTys.size()),
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005480 &Values[0], Values.size()));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005481 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00005482
Evan Cheng8380c032011-04-01 19:42:22 +00005483 if (!Result.second.getNode()) {
Andrew Trick2343e3b2013-10-31 17:18:24 +00005484 // As a special case, a null chain means that a tail call has been emitted
5485 // and the DAG root is already updated.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005486 HasTailCall = true;
Tim Northovere5a81a12013-07-06 12:58:45 +00005487
5488 // Since there's no actual continuation from this block, nothing can be
5489 // relying on us setting vregs for them.
5490 PendingExports.clear();
Evan Cheng8380c032011-04-01 19:42:22 +00005491 } else {
5492 DAG.setRoot(Result.second);
Evan Cheng8380c032011-04-01 19:42:22 +00005493 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005494
Chris Lattner512063d2010-04-05 06:19:28 +00005495 if (LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005496 // Insert a label at the end of the invoke call to mark the try range. This
5497 // can be used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattner512063d2010-04-05 06:19:28 +00005498 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
Andrew Trickac6d9be2013-05-25 02:42:55 +00005499 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005500
5501 // Inform MachineModuleInfo of range.
Chris Lattner512063d2010-04-05 06:19:28 +00005502 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005503 }
5504}
5505
Chris Lattner8047d9a2009-12-24 00:37:38 +00005506/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5507/// value is equal or not-equal to zero.
Dan Gohman46510a72010-04-15 01:51:59 +00005508static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5509 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Chris Lattner8047d9a2009-12-24 00:37:38 +00005510 UI != E; ++UI) {
Dan Gohman46510a72010-04-15 01:51:59 +00005511 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005512 if (IC->isEquality())
Dan Gohman46510a72010-04-15 01:51:59 +00005513 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005514 if (C->isNullValue())
5515 continue;
5516 // Unknown instruction.
5517 return false;
5518 }
5519 return true;
5520}
5521
Dan Gohman46510a72010-04-15 01:51:59 +00005522static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005523 Type *LoadTy,
Chris Lattner8047d9a2009-12-24 00:37:38 +00005524 SelectionDAGBuilder &Builder) {
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005525
Chris Lattner8047d9a2009-12-24 00:37:38 +00005526 // Check to see if this load can be trivially constant folded, e.g. if the
5527 // input is from a string literal.
Dan Gohman46510a72010-04-15 01:51:59 +00005528 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
Chris Lattner8047d9a2009-12-24 00:37:38 +00005529 // Cast pointer to the type we really want to load.
Dan Gohman46510a72010-04-15 01:51:59 +00005530 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
Chris Lattner8047d9a2009-12-24 00:37:38 +00005531 PointerType::getUnqual(LoadTy));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005532
Dan Gohman46510a72010-04-15 01:51:59 +00005533 if (const Constant *LoadCst =
5534 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5535 Builder.TD))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005536 return Builder.getValue(LoadCst);
5537 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005538
Chris Lattner8047d9a2009-12-24 00:37:38 +00005539 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5540 // still constant memory, the input chain can be the entry node.
5541 SDValue Root;
5542 bool ConstantMemory = false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005543
Chris Lattner8047d9a2009-12-24 00:37:38 +00005544 // Do not serialize (non-volatile) loads of constant memory with anything.
5545 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5546 Root = Builder.DAG.getEntryNode();
5547 ConstantMemory = true;
5548 } else {
5549 // Do not serialize non-volatile loads against each other.
5550 Root = Builder.DAG.getRoot();
5551 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005552
Chris Lattner8047d9a2009-12-24 00:37:38 +00005553 SDValue Ptr = Builder.getValue(PtrVal);
Andrew Trickac6d9be2013-05-25 02:42:55 +00005554 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
Chris Lattnerecf42c42010-09-21 16:36:31 +00005555 Ptr, MachinePointerInfo(PtrVal),
David Greene1e559442010-02-15 17:00:31 +00005556 false /*volatile*/,
Stephen Lin155615d2013-07-08 00:37:03 +00005557 false /*nontemporal*/,
Pete Cooperd752e0f2011-11-08 18:42:53 +00005558 false /*isinvariant*/, 1 /* align=1 */);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005559
Chris Lattner8047d9a2009-12-24 00:37:38 +00005560 if (!ConstantMemory)
5561 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5562 return LoadVal;
5563}
5564
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005565/// processIntegerCallValue - Record the value for an instruction that
5566/// produces an integer result, converting the type where necessary.
5567void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5568 SDValue Value,
5569 bool IsSigned) {
5570 EVT VT = TM.getTargetLowering()->getValueType(I.getType(), true);
5571 if (IsSigned)
5572 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5573 else
5574 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5575 setValue(&I, Value);
5576}
Chris Lattner8047d9a2009-12-24 00:37:38 +00005577
5578/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5579/// If so, return true and lower it, otherwise return false and it will be
5580/// lowered like a normal call.
Dan Gohman46510a72010-04-15 01:51:59 +00005581bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
Chris Lattner8047d9a2009-12-24 00:37:38 +00005582 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
Gabor Greif37387d52010-06-30 12:55:46 +00005583 if (I.getNumArgOperands() != 3)
Chris Lattner8047d9a2009-12-24 00:37:38 +00005584 return false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005585
Gabor Greif0635f352010-06-25 09:38:13 +00005586 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
Duncan Sands1df98592010-02-16 11:11:14 +00005587 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
Gabor Greif0635f352010-06-25 09:38:13 +00005588 !I.getArgOperand(2)->getType()->isIntegerTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00005589 !I.getType()->isIntegerTy())
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005590 return false;
5591
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005592 const Value *Size = I.getArgOperand(2);
5593 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5594 if (CSize && CSize->getZExtValue() == 0) {
Richard Sandifordac168b82013-08-12 10:28:10 +00005595 EVT CallVT = TM.getTargetLowering()->getValueType(I.getType(), true);
5596 setValue(&I, DAG.getConstant(0, CallVT));
5597 return true;
5598 }
5599
Richard Sandifordac168b82013-08-12 10:28:10 +00005600 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5601 std::pair<SDValue, SDValue> Res =
5602 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005603 getValue(LHS), getValue(RHS), getValue(Size),
5604 MachinePointerInfo(LHS),
5605 MachinePointerInfo(RHS));
Richard Sandifordac168b82013-08-12 10:28:10 +00005606 if (Res.first.getNode()) {
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005607 processIntegerCallValue(I, Res.first, true);
5608 PendingLoads.push_back(Res.second);
Richard Sandifordac168b82013-08-12 10:28:10 +00005609 return true;
5610 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005611
Chris Lattner8047d9a2009-12-24 00:37:38 +00005612 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5613 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005614 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
Chris Lattner04b091a2009-12-24 01:07:17 +00005615 bool ActuallyDoIt = true;
5616 MVT LoadVT;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005617 Type *LoadTy;
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005618 switch (CSize->getZExtValue()) {
Chris Lattner04b091a2009-12-24 01:07:17 +00005619 default:
5620 LoadVT = MVT::Other;
5621 LoadTy = 0;
5622 ActuallyDoIt = false;
5623 break;
5624 case 2:
5625 LoadVT = MVT::i16;
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005626 LoadTy = Type::getInt16Ty(CSize->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005627 break;
5628 case 4:
5629 LoadVT = MVT::i32;
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005630 LoadTy = Type::getInt32Ty(CSize->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005631 break;
5632 case 8:
5633 LoadVT = MVT::i64;
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005634 LoadTy = Type::getInt64Ty(CSize->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005635 break;
5636 /*
5637 case 16:
5638 LoadVT = MVT::v4i32;
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005639 LoadTy = Type::getInt32Ty(CSize->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005640 LoadTy = VectorType::get(LoadTy, 4);
5641 break;
5642 */
5643 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005644
Chris Lattner04b091a2009-12-24 01:07:17 +00005645 // This turns into unaligned loads. We only do this if the target natively
5646 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5647 // we'll only produce a small number of byte loads.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005648
Chris Lattner04b091a2009-12-24 01:07:17 +00005649 // Require that we can find a legal MVT, and only do this if the target
5650 // supports unaligned loads of that type. Expanding into byte loads would
5651 // bloat the code.
Bill Wendlingba54bca2013-06-19 21:36:55 +00005652 const TargetLowering *TLI = TM.getTargetLowering();
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005653 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
Chris Lattner04b091a2009-12-24 01:07:17 +00005654 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5655 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
Bill Wendlingba54bca2013-06-19 21:36:55 +00005656 if (!TLI->isTypeLegal(LoadVT) ||!TLI->allowsUnalignedMemoryAccesses(LoadVT))
Chris Lattner04b091a2009-12-24 01:07:17 +00005657 ActuallyDoIt = false;
5658 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005659
Chris Lattner04b091a2009-12-24 01:07:17 +00005660 if (ActuallyDoIt) {
5661 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5662 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005663
Andrew Trickac6d9be2013-05-25 02:42:55 +00005664 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
Chris Lattner04b091a2009-12-24 01:07:17 +00005665 ISD::SETNE);
Richard Sandiford6a079fe2013-08-16 10:55:47 +00005666 processIntegerCallValue(I, Res, false);
Chris Lattner04b091a2009-12-24 01:07:17 +00005667 return true;
5668 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00005669 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005670
5671
Chris Lattner8047d9a2009-12-24 00:37:38 +00005672 return false;
5673}
5674
Richard Sandiford8c201582013-08-20 09:38:48 +00005675/// visitMemChrCall -- See if we can lower a memchr call into an optimized
5676/// form. If so, return true and lower it, otherwise return false and it
5677/// will be lowered like a normal call.
5678bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5679 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5680 if (I.getNumArgOperands() != 3)
5681 return false;
5682
5683 const Value *Src = I.getArgOperand(0);
5684 const Value *Char = I.getArgOperand(1);
5685 const Value *Length = I.getArgOperand(2);
5686 if (!Src->getType()->isPointerTy() ||
5687 !Char->getType()->isIntegerTy() ||
5688 !Length->getType()->isIntegerTy() ||
5689 !I.getType()->isPointerTy())
5690 return false;
5691
5692 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5693 std::pair<SDValue, SDValue> Res =
5694 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5695 getValue(Src), getValue(Char), getValue(Length),
5696 MachinePointerInfo(Src));
5697 if (Res.first.getNode()) {
5698 setValue(&I, Res.first);
5699 PendingLoads.push_back(Res.second);
5700 return true;
5701 }
5702
5703 return false;
5704}
5705
Richard Sandiford4fc73552013-08-16 11:29:37 +00005706/// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5707/// optimized form. If so, return true and lower it, otherwise return false
5708/// and it will be lowered like a normal call.
5709bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5710 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5711 if (I.getNumArgOperands() != 2)
5712 return false;
5713
5714 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5715 if (!Arg0->getType()->isPointerTy() ||
5716 !Arg1->getType()->isPointerTy() ||
5717 !I.getType()->isPointerTy())
5718 return false;
5719
5720 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5721 std::pair<SDValue, SDValue> Res =
5722 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5723 getValue(Arg0), getValue(Arg1),
5724 MachinePointerInfo(Arg0),
5725 MachinePointerInfo(Arg1), isStpcpy);
5726 if (Res.first.getNode()) {
5727 setValue(&I, Res.first);
5728 DAG.setRoot(Res.second);
5729 return true;
5730 }
5731
5732 return false;
5733}
5734
Richard Sandiforde1b2af72013-08-16 11:21:54 +00005735/// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5736/// If so, return true and lower it, otherwise return false and it will be
5737/// lowered like a normal call.
5738bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5739 // Verify that the prototype makes sense. int strcmp(void*,void*)
5740 if (I.getNumArgOperands() != 2)
5741 return false;
5742
5743 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5744 if (!Arg0->getType()->isPointerTy() ||
5745 !Arg1->getType()->isPointerTy() ||
5746 !I.getType()->isIntegerTy())
5747 return false;
5748
5749 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5750 std::pair<SDValue, SDValue> Res =
5751 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5752 getValue(Arg0), getValue(Arg1),
5753 MachinePointerInfo(Arg0),
5754 MachinePointerInfo(Arg1));
5755 if (Res.first.getNode()) {
5756 processIntegerCallValue(I, Res.first, true);
5757 PendingLoads.push_back(Res.second);
5758 return true;
5759 }
5760
5761 return false;
5762}
5763
Richard Sandiford19262ee2013-08-16 11:41:43 +00005764/// visitStrLenCall -- See if we can lower a strlen call into an optimized
5765/// form. If so, return true and lower it, otherwise return false and it
5766/// will be lowered like a normal call.
5767bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5768 // Verify that the prototype makes sense. size_t strlen(char *)
5769 if (I.getNumArgOperands() != 1)
5770 return false;
5771
5772 const Value *Arg0 = I.getArgOperand(0);
5773 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5774 return false;
5775
5776 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5777 std::pair<SDValue, SDValue> Res =
5778 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5779 getValue(Arg0), MachinePointerInfo(Arg0));
5780 if (Res.first.getNode()) {
5781 processIntegerCallValue(I, Res.first, false);
5782 PendingLoads.push_back(Res.second);
5783 return true;
5784 }
5785
5786 return false;
5787}
5788
5789/// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5790/// form. If so, return true and lower it, otherwise return false and it
5791/// will be lowered like a normal call.
5792bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5793 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5794 if (I.getNumArgOperands() != 2)
5795 return false;
5796
5797 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5798 if (!Arg0->getType()->isPointerTy() ||
5799 !Arg1->getType()->isIntegerTy() ||
5800 !I.getType()->isIntegerTy())
5801 return false;
5802
5803 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5804 std::pair<SDValue, SDValue> Res =
5805 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5806 getValue(Arg0), getValue(Arg1),
5807 MachinePointerInfo(Arg0));
5808 if (Res.first.getNode()) {
5809 processIntegerCallValue(I, Res.first, false);
5810 PendingLoads.push_back(Res.second);
5811 return true;
5812 }
5813
5814 return false;
5815}
5816
Bob Wilson53624a22012-08-03 23:29:17 +00005817/// visitUnaryFloatCall - If a call instruction is a unary floating-point
5818/// operation (as expected), translate it to an SDNode with the specified opcode
5819/// and return true.
5820bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5821 unsigned Opcode) {
5822 // Sanity check that it really is a unary floating-point call.
5823 if (I.getNumArgOperands() != 1 ||
5824 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5825 I.getType() != I.getArgOperand(0)->getType() ||
5826 !I.onlyReadsMemory())
5827 return false;
5828
5829 SDValue Tmp = getValue(I.getArgOperand(0));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005830 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
Bob Wilson53624a22012-08-03 23:29:17 +00005831 return true;
5832}
Chris Lattner8047d9a2009-12-24 00:37:38 +00005833
Dan Gohman46510a72010-04-15 01:51:59 +00005834void SelectionDAGBuilder::visitCall(const CallInst &I) {
Chris Lattner598751e2010-07-05 05:36:21 +00005835 // Handle inline assembly differently.
5836 if (isa<InlineAsm>(I.getCalledValue())) {
5837 visitInlineAsm(&I);
5838 return;
5839 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00005840
Michael J. Spencer391b43b2010-10-21 20:49:23 +00005841 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Michael J. Spencerc9c137b2012-02-22 19:06:13 +00005842 ComputeUsesVAFloatArgument(I, &MMI);
Michael J. Spencer391b43b2010-10-21 20:49:23 +00005843
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005844 const char *RenameFn = 0;
5845 if (Function *F = I.getCalledFunction()) {
5846 if (F->isDeclaration()) {
Chris Lattner598751e2010-07-05 05:36:21 +00005847 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00005848 if (unsigned IID = II->getIntrinsicID(F)) {
5849 RenameFn = visitIntrinsicCall(I, IID);
5850 if (!RenameFn)
5851 return;
5852 }
5853 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005854 if (unsigned IID = F->getIntrinsicID()) {
5855 RenameFn = visitIntrinsicCall(I, IID);
5856 if (!RenameFn)
5857 return;
5858 }
5859 }
5860
5861 // Check for well-known libc/libm calls. If the function is internal, it
5862 // can't be a library call.
Bob Wilson982dc842012-08-03 21:26:24 +00005863 LibFunc::Func Func;
5864 if (!F->hasLocalLinkage() && F->hasName() &&
5865 LibInfo->getLibFunc(F->getName(), Func) &&
5866 LibInfo->hasOptimizedCodeGen(Func)) {
5867 switch (Func) {
5868 default: break;
5869 case LibFunc::copysign:
5870 case LibFunc::copysignf:
5871 case LibFunc::copysignl:
Gabor Greif37387d52010-06-30 12:55:46 +00005872 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
Gabor Greif0635f352010-06-25 09:38:13 +00005873 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5874 I.getType() == I.getArgOperand(0)->getType() &&
Bob Wilson53624a22012-08-03 23:29:17 +00005875 I.getType() == I.getArgOperand(1)->getType() &&
5876 I.onlyReadsMemory()) {
Gabor Greif0635f352010-06-25 09:38:13 +00005877 SDValue LHS = getValue(I.getArgOperand(0));
5878 SDValue RHS = getValue(I.getArgOperand(1));
Andrew Trickac6d9be2013-05-25 02:42:55 +00005879 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
Bill Wendling0d580132009-12-23 01:28:19 +00005880 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005881 return;
5882 }
Bob Wilson982dc842012-08-03 21:26:24 +00005883 break;
5884 case LibFunc::fabs:
5885 case LibFunc::fabsf:
5886 case LibFunc::fabsl:
Bob Wilson53624a22012-08-03 23:29:17 +00005887 if (visitUnaryFloatCall(I, ISD::FABS))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005888 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005889 break;
5890 case LibFunc::sin:
5891 case LibFunc::sinf:
5892 case LibFunc::sinl:
Bob Wilson53624a22012-08-03 23:29:17 +00005893 if (visitUnaryFloatCall(I, ISD::FSIN))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005894 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005895 break;
5896 case LibFunc::cos:
5897 case LibFunc::cosf:
5898 case LibFunc::cosl:
Bob Wilson53624a22012-08-03 23:29:17 +00005899 if (visitUnaryFloatCall(I, ISD::FCOS))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005900 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005901 break;
5902 case LibFunc::sqrt:
5903 case LibFunc::sqrtf:
5904 case LibFunc::sqrtl:
Preston Gurdb704d232013-05-27 15:44:35 +00005905 case LibFunc::sqrt_finite:
5906 case LibFunc::sqrtf_finite:
5907 case LibFunc::sqrtl_finite:
Bob Wilson53624a22012-08-03 23:29:17 +00005908 if (visitUnaryFloatCall(I, ISD::FSQRT))
Dale Johannesen52fb79b2009-09-25 17:23:22 +00005909 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005910 break;
5911 case LibFunc::floor:
5912 case LibFunc::floorf:
5913 case LibFunc::floorl:
Bob Wilson53624a22012-08-03 23:29:17 +00005914 if (visitUnaryFloatCall(I, ISD::FFLOOR))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005915 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005916 break;
5917 case LibFunc::nearbyint:
5918 case LibFunc::nearbyintf:
5919 case LibFunc::nearbyintl:
Bob Wilson53624a22012-08-03 23:29:17 +00005920 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005921 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005922 break;
5923 case LibFunc::ceil:
5924 case LibFunc::ceilf:
5925 case LibFunc::ceill:
Bob Wilson53624a22012-08-03 23:29:17 +00005926 if (visitUnaryFloatCall(I, ISD::FCEIL))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005927 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005928 break;
5929 case LibFunc::rint:
5930 case LibFunc::rintf:
5931 case LibFunc::rintl:
Bob Wilson53624a22012-08-03 23:29:17 +00005932 if (visitUnaryFloatCall(I, ISD::FRINT))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005933 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005934 break;
Hal Finkel41418d12013-08-07 22:49:12 +00005935 case LibFunc::round:
5936 case LibFunc::roundf:
5937 case LibFunc::roundl:
5938 if (visitUnaryFloatCall(I, ISD::FROUND))
5939 return;
5940 break;
Bob Wilson982dc842012-08-03 21:26:24 +00005941 case LibFunc::trunc:
5942 case LibFunc::truncf:
5943 case LibFunc::truncl:
Bob Wilson53624a22012-08-03 23:29:17 +00005944 if (visitUnaryFloatCall(I, ISD::FTRUNC))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005945 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005946 break;
5947 case LibFunc::log2:
5948 case LibFunc::log2f:
5949 case LibFunc::log2l:
Bob Wilson53624a22012-08-03 23:29:17 +00005950 if (visitUnaryFloatCall(I, ISD::FLOG2))
Owen Anderson4e0adfa2011-12-15 00:54:12 +00005951 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005952 break;
5953 case LibFunc::exp2:
5954 case LibFunc::exp2f:
5955 case LibFunc::exp2l:
Bob Wilson53624a22012-08-03 23:29:17 +00005956 if (visitUnaryFloatCall(I, ISD::FEXP2))
Owen Anderson4e0adfa2011-12-15 00:54:12 +00005957 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005958 break;
5959 case LibFunc::memcmp:
Chris Lattner8047d9a2009-12-24 00:37:38 +00005960 if (visitMemCmpCall(I))
5961 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005962 break;
Richard Sandiford8c201582013-08-20 09:38:48 +00005963 case LibFunc::memchr:
5964 if (visitMemChrCall(I))
5965 return;
5966 break;
Richard Sandiford4fc73552013-08-16 11:29:37 +00005967 case LibFunc::strcpy:
5968 if (visitStrCpyCall(I, false))
5969 return;
5970 break;
5971 case LibFunc::stpcpy:
5972 if (visitStrCpyCall(I, true))
5973 return;
5974 break;
Richard Sandiforde1b2af72013-08-16 11:21:54 +00005975 case LibFunc::strcmp:
5976 if (visitStrCmpCall(I))
5977 return;
5978 break;
Richard Sandiford19262ee2013-08-16 11:41:43 +00005979 case LibFunc::strlen:
5980 if (visitStrLenCall(I))
5981 return;
5982 break;
5983 case LibFunc::strnlen:
5984 if (visitStrNLenCall(I))
5985 return;
5986 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005987 }
5988 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005989 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00005990
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005991 SDValue Callee;
5992 if (!RenameFn)
Gabor Greif0635f352010-06-25 09:38:13 +00005993 Callee = getValue(I.getCalledValue());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005994 else
Bill Wendlingba54bca2013-06-19 21:36:55 +00005995 Callee = DAG.getExternalSymbol(RenameFn,
5996 TM.getTargetLowering()->getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005997
Bill Wendling0d580132009-12-23 01:28:19 +00005998 // Check if we can potentially perform a tail call. More detailed checking is
5999 // be done within LowerCallTo, after more information about the call is known.
Evan Cheng11e67932010-01-26 23:13:04 +00006000 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006001}
6002
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00006003namespace {
Dan Gohman462f6b52010-05-29 17:53:24 +00006004
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006005/// AsmOperandInfo - This contains information for each constraint that we are
6006/// lowering.
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00006007class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00006008public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006009 /// CallOperand - If this is the result output operand or a clobber
6010 /// this is null, otherwise it is the incoming operand to the CallInst.
6011 /// This gets modified as the asm is processed.
6012 SDValue CallOperand;
6013
6014 /// AssignedRegs - If this is a register or register class operand, this
6015 /// contains the set of register corresponding to the operand.
6016 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006017
John Thompsoneac6e1d2010-09-13 18:15:37 +00006018 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006019 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
6020 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006021
Owen Andersone50ed302009-08-10 22:56:29 +00006022 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner81249c92008-10-17 17:05:25 +00006023 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson825b72b2009-08-11 20:47:22 +00006024 /// MVT::Other.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00006025 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson1d0be152009-08-13 21:58:54 +00006026 const TargetLowering &TLI,
Micah Villmow3574eca2012-10-08 16:38:25 +00006027 const DataLayout *TD) const {
Owen Anderson825b72b2009-08-11 20:47:22 +00006028 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006029
Chris Lattner81249c92008-10-17 17:05:25 +00006030 if (isa<BasicBlock>(CallOperandVal))
6031 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006032
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006033 llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006034
Eric Christophercef81b72011-05-09 20:04:43 +00006035 // FIXME: code duplicated from TargetLowering::ParseConstraints().
Chris Lattner81249c92008-10-17 17:05:25 +00006036 // If this is an indirect operand, the operand is a pointer to the
6037 // accessed type.
Bob Wilsone261b0c2009-12-22 18:34:19 +00006038 if (isIndirect) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006039 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
Bob Wilsone261b0c2009-12-22 18:34:19 +00006040 if (!PtrTy)
Chris Lattner75361b62010-04-07 22:58:41 +00006041 report_fatal_error("Indirect operand for inline asm not a pointer!");
Bob Wilsone261b0c2009-12-22 18:34:19 +00006042 OpTy = PtrTy->getElementType();
6043 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006044
Eric Christophercef81b72011-05-09 20:04:43 +00006045 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006046 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christophercef81b72011-05-09 20:04:43 +00006047 if (STy->getNumElements() == 1)
6048 OpTy = STy->getElementType(0);
6049
Chris Lattner81249c92008-10-17 17:05:25 +00006050 // If OpTy is not a single value, it may be a struct/union that we
6051 // can tile with integers.
6052 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6053 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
6054 switch (BitSize) {
6055 default: break;
6056 case 1:
6057 case 8:
6058 case 16:
6059 case 32:
6060 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00006061 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00006062 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner81249c92008-10-17 17:05:25 +00006063 break;
6064 }
6065 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006066
Chris Lattner81249c92008-10-17 17:05:25 +00006067 return TLI.getValueType(OpTy, true);
6068 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006069};
Dan Gohman462f6b52010-05-29 17:53:24 +00006070
John Thompson44ab89e2010-10-29 17:29:13 +00006071typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6072
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00006073} // end anonymous namespace
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006074
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006075/// GetRegistersForValue - Assign registers (virtual or physical) for the
6076/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson266d9452009-12-17 05:07:36 +00006077/// register allocator to handle the assignment process. However, if the asm
6078/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006079/// allocation. This produces generally horrible, but correct, code.
6080///
6081/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006082///
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00006083static void GetRegistersForValue(SelectionDAG &DAG,
6084 const TargetLowering &TLI,
Andrew Trickac6d9be2013-05-25 02:42:55 +00006085 SDLoc DL,
Benjamin Kramer8b93ff22012-02-24 14:01:17 +00006086 SDISelAsmOperandInfo &OpInfo) {
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00006087 LLVMContext &Context = *DAG.getContext();
Owen Anderson23b9b192009-08-12 00:36:31 +00006088
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006089 MachineFunction &MF = DAG.getMachineFunction();
6090 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006091
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006092 // If this is a constraint for a single physreg, or a constraint for a
6093 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006094 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006095 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6096 OpInfo.ConstraintVT);
6097
6098 unsigned NumRegs = 1;
Owen Anderson825b72b2009-08-11 20:47:22 +00006099 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner01426e12008-10-21 00:45:36 +00006100 // If this is a FP input in an integer register (or visa versa) insert a bit
6101 // cast of the input value. More generally, handle any case where the input
6102 // value disagrees with the register class we plan to stick this in.
6103 if (OpInfo.Type == InlineAsm::isInput &&
6104 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Andersone50ed302009-08-10 22:56:29 +00006105 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner01426e12008-10-21 00:45:36 +00006106 // types are identical size, use a bitcast to convert (e.g. two differing
6107 // vector types).
Patrik Hagglund8963fec2012-12-19 12:23:01 +00006108 MVT RegVT = *PhysReg.second->vt_begin();
Chris Lattner01426e12008-10-21 00:45:36 +00006109 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00006110 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00006111 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00006112 OpInfo.ConstraintVT = RegVT;
6113 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6114 // If the input is a FP value and we want it in FP registers, do a
6115 // bitcast to the corresponding integer type. This turns an f64 value
6116 // into i64, which can be passed with two i32 values on a 32-bit
6117 // machine.
Patrik Hagglund8963fec2012-12-19 12:23:01 +00006118 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00006119 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00006120 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00006121 OpInfo.ConstraintVT = RegVT;
6122 }
6123 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006124
Owen Anderson23b9b192009-08-12 00:36:31 +00006125 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00006126 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006127
Patrik Hagglund8963fec2012-12-19 12:23:01 +00006128 MVT RegVT;
Owen Andersone50ed302009-08-10 22:56:29 +00006129 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006130
6131 // If this is a constraint for a specific physical register, like {r17},
6132 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00006133 if (unsigned AssignedReg = PhysReg.first) {
6134 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson825b72b2009-08-11 20:47:22 +00006135 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00006136 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006137
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006138 // Get the actual register value type. This is important, because the user
6139 // may have asked for (e.g.) the AX register in i32 type. We need to
6140 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00006141 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006142
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006143 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00006144 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006145
6146 // If this is an expanded reference, add the rest of the regs to Regs.
6147 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00006148 TargetRegisterClass::iterator I = RC->begin();
6149 for (; *I != AssignedReg; ++I)
6150 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006151
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006152 // Already added the first reg.
6153 --NumRegs; ++I;
6154 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00006155 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006156 Regs.push_back(*I);
6157 }
6158 }
Bill Wendling651ad132009-12-22 01:25:10 +00006159
Dan Gohman7451d3e2010-05-29 17:03:36 +00006160 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006161 return;
6162 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006163
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006164 // Otherwise, if this was a reference to an LLVM register class, create vregs
6165 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00006166 if (const TargetRegisterClass *RC = PhysReg.second) {
6167 RegVT = *RC->vt_begin();
Owen Anderson825b72b2009-08-11 20:47:22 +00006168 if (OpInfo.ConstraintVT == MVT::Other)
Evan Chengfb112882009-03-23 08:01:15 +00006169 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006170
Evan Chengfb112882009-03-23 08:01:15 +00006171 // Create the appropriate number of virtual registers.
6172 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6173 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00006174 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006175
Dan Gohman7451d3e2010-05-29 17:03:36 +00006176 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Evan Chengfb112882009-03-23 08:01:15 +00006177 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006178 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00006179
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006180 // Otherwise, we couldn't allocate enough registers for this.
6181}
6182
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006183/// visitInlineAsm - Handle a call to an InlineAsm object.
6184///
Dan Gohman46510a72010-04-15 01:51:59 +00006185void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6186 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006187
6188 /// ConstraintOperands - Information about all of the constraints.
John Thompson44ab89e2010-10-29 17:29:13 +00006189 SDISelAsmOperandInfoVector ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006190
Bill Wendlingba54bca2013-06-19 21:36:55 +00006191 const TargetLowering *TLI = TM.getTargetLowering();
Evan Chengce1cdac2011-05-06 20:52:23 +00006192 TargetLowering::AsmOperandInfoVector
Bill Wendlingba54bca2013-06-19 21:36:55 +00006193 TargetConstraints = TLI->ParseConstraints(CS);
Evan Chengce1cdac2011-05-06 20:52:23 +00006194
John Thompsoneac6e1d2010-09-13 18:15:37 +00006195 bool hasMemory = false;
Michael J. Spencere70c5262010-10-16 08:25:21 +00006196
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006197 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6198 unsigned ResNo = 0; // ResNo - The result number of the next output.
John Thompsoneac6e1d2010-09-13 18:15:37 +00006199 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6200 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006201 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Michael J. Spencere70c5262010-10-16 08:25:21 +00006202
Patrik Hagglundc698d3a2012-12-19 15:19:11 +00006203 MVT OpVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006204
6205 // Compute the value type for each operand.
6206 switch (OpInfo.Type) {
6207 case InlineAsm::isOutput:
6208 // Indirect outputs just consume an argument.
6209 if (OpInfo.isIndirect) {
Dan Gohman46510a72010-04-15 01:51:59 +00006210 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006211 break;
6212 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006213
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006214 // The return value of the call is this value. As such, there is no
6215 // corresponding argument.
Nick Lewycky8de34002011-09-30 22:19:53 +00006216 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006217 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00006218 OpVT = TLI->getSimpleValueType(STy->getElementType(ResNo));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006219 } else {
6220 assert(ResNo == 0 && "Asm only has one result!");
Bill Wendlingba54bca2013-06-19 21:36:55 +00006221 OpVT = TLI->getSimpleValueType(CS.getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006222 }
6223 ++ResNo;
6224 break;
6225 case InlineAsm::isInput:
Dan Gohman46510a72010-04-15 01:51:59 +00006226 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006227 break;
6228 case InlineAsm::isClobber:
6229 // Nothing to do.
6230 break;
6231 }
6232
6233 // If this is an input or an indirect output, process the call argument.
6234 // BasicBlocks are labels, currently appearing only in asm's.
6235 if (OpInfo.CallOperandVal) {
Dan Gohman46510a72010-04-15 01:51:59 +00006236 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006237 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00006238 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006239 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006240 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006241
Bill Wendlingba54bca2013-06-19 21:36:55 +00006242 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), *TLI, TD).
Patrik Hagglundc698d3a2012-12-19 15:19:11 +00006243 getSimpleVT();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006244 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006245
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006246 OpInfo.ConstraintVT = OpVT;
Michael J. Spencere70c5262010-10-16 08:25:21 +00006247
John Thompsoneac6e1d2010-09-13 18:15:37 +00006248 // Indirect operand accesses access memory.
6249 if (OpInfo.isIndirect)
6250 hasMemory = true;
6251 else {
6252 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
Evan Chengce1cdac2011-05-06 20:52:23 +00006253 TargetLowering::ConstraintType
Bill Wendlingba54bca2013-06-19 21:36:55 +00006254 CType = TLI->getConstraintType(OpInfo.Codes[j]);
John Thompsoneac6e1d2010-09-13 18:15:37 +00006255 if (CType == TargetLowering::C_Memory) {
6256 hasMemory = true;
6257 break;
6258 }
6259 }
6260 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006261 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006262
John Thompsoneac6e1d2010-09-13 18:15:37 +00006263 SDValue Chain, Flag;
6264
6265 // We won't need to flush pending loads if this asm doesn't touch
6266 // memory and is nonvolatile.
6267 if (hasMemory || IA->hasSideEffects())
6268 Chain = getRoot();
6269 else
6270 Chain = DAG.getRoot();
6271
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006272 // Second pass over the constraints: compute which constraint option to use
6273 // and assign registers to constraints that want a specific physreg.
John Thompsoneac6e1d2010-09-13 18:15:37 +00006274 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006275 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006276
John Thompson54584742010-09-24 22:24:05 +00006277 // If this is an output operand with a matching input operand, look up the
6278 // matching input. If their types mismatch, e.g. one is an integer, the
6279 // other is floating point, or their sizes are different, flag it as an
6280 // error.
6281 if (OpInfo.hasMatchingInput()) {
6282 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
Michael J. Spencere70c5262010-10-16 08:25:21 +00006283
John Thompson54584742010-09-24 22:24:05 +00006284 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Bill Wendling96cb1122012-07-19 00:04:14 +00006285 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
Bill Wendlingba54bca2013-06-19 21:36:55 +00006286 TLI->getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6287 OpInfo.ConstraintVT);
Bill Wendling96cb1122012-07-19 00:04:14 +00006288 std::pair<unsigned, const TargetRegisterClass*> InputRC =
Bill Wendlingba54bca2013-06-19 21:36:55 +00006289 TLI->getRegForInlineAsmConstraint(Input.ConstraintCode,
6290 Input.ConstraintVT);
John Thompson54584742010-09-24 22:24:05 +00006291 if ((OpInfo.ConstraintVT.isInteger() !=
6292 Input.ConstraintVT.isInteger()) ||
Eric Christopher5427ede2011-07-14 20:13:52 +00006293 (MatchRC.second != InputRC.second)) {
John Thompson54584742010-09-24 22:24:05 +00006294 report_fatal_error("Unsupported asm: input constraint"
6295 " with a matching output constraint of"
6296 " incompatible type!");
6297 }
6298 Input.ConstraintVT = OpInfo.ConstraintVT;
6299 }
6300 }
6301
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006302 // Compute the constraint code and ConstraintType to use.
Bill Wendlingba54bca2013-06-19 21:36:55 +00006303 TLI->ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006304
Eric Christopherfffe3632013-01-11 18:12:39 +00006305 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6306 OpInfo.Type == InlineAsm::isClobber)
6307 continue;
6308
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006309 // If this is a memory input, and if the operand is not indirect, do what we
6310 // need to to provide an address for the memory input.
6311 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6312 !OpInfo.isIndirect) {
Evan Chengce1cdac2011-05-06 20:52:23 +00006313 assert((OpInfo.isMultipleAlternative ||
6314 (OpInfo.Type == InlineAsm::isInput)) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006315 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006316
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006317 // Memory operands really want the address of the value. If we don't have
6318 // an indirect input, put it in the constpool if we can, otherwise spill
6319 // it to a stack slot.
Eric Christophere0b42c02011-06-03 17:21:23 +00006320 // TODO: This isn't quite right. We need to handle these according to
6321 // the addressing mode that the constraint wants. Also, this may take
6322 // an additional register for the computation and we don't want that
6323 // either.
Eric Christopher471e4222011-06-08 23:55:35 +00006324
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006325 // If the operand is a float, integer, or vector constant, spill to a
6326 // constant pool entry to get its address.
Dan Gohman46510a72010-04-15 01:51:59 +00006327 const Value *OpVal = OpInfo.CallOperandVal;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006328 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
Chris Lattnera78fa8c2012-01-27 03:08:05 +00006329 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006330 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
Bill Wendlingba54bca2013-06-19 21:36:55 +00006331 TLI->getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006332 } else {
6333 // Otherwise, create a stack slot and emit a store to it before the
6334 // asm.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006335 Type *Ty = OpVal->getType();
Bill Wendlingba54bca2013-06-19 21:36:55 +00006336 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
6337 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006338 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00006339 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Bill Wendlingba54bca2013-06-19 21:36:55 +00006340 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI->getPointerTy());
Andrew Trickac6d9be2013-05-25 02:42:55 +00006341 Chain = DAG.getStore(Chain, getCurSDLoc(),
Chris Lattnerecf42c42010-09-21 16:36:31 +00006342 OpInfo.CallOperand, StackSlot,
6343 MachinePointerInfo::getFixedStack(SSFI),
David Greene1e559442010-02-15 17:00:31 +00006344 false, false, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006345 OpInfo.CallOperand = StackSlot;
6346 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006347
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006348 // There is no longer a Value* corresponding to this operand.
6349 OpInfo.CallOperandVal = 0;
Bill Wendling651ad132009-12-22 01:25:10 +00006350
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006351 // It is now an indirect operand.
6352 OpInfo.isIndirect = true;
6353 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006354
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006355 // If this constraint is for a specific register, allocate it before
6356 // anything else.
6357 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Bill Wendlingba54bca2013-06-19 21:36:55 +00006358 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006359 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006360
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006361 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00006362 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006363 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6364 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006365
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006366 // C_Register operands have already been allocated, Other/Memory don't need
6367 // to be.
6368 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Bill Wendlingba54bca2013-06-19 21:36:55 +00006369 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006370 }
6371
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006372 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6373 std::vector<SDValue> AsmNodeOperands;
6374 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6375 AsmNodeOperands.push_back(
Dan Gohmanf2d7fb32010-01-04 21:00:54 +00006376 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
Bill Wendlingba54bca2013-06-19 21:36:55 +00006377 TLI->getPointerTy()));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006378
Chris Lattnerdecc2672010-04-07 05:20:54 +00006379 // If we have a !srcloc metadata node associated with it, we want to attach
6380 // this to the ultimately generated inline asm machineinstr. To do this, we
6381 // pass in the third operand as this (potentially null) inline asm MDNode.
6382 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6383 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006384
Chad Rosier3d716882012-10-30 19:11:54 +00006385 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6386 // bits as operand 3.
Evan Chengc36b7062011-01-07 23:50:32 +00006387 unsigned ExtraInfo = 0;
6388 if (IA->hasSideEffects())
6389 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6390 if (IA->isAlignStack())
6391 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
Chad Rosier77fffa62012-09-05 22:17:43 +00006392 // Set the asm dialect.
Chad Rosier2f1d8152012-09-05 22:40:13 +00006393 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
Chad Rosier3d716882012-10-30 19:11:54 +00006394
6395 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6396 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6397 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6398
6399 // Compute the constraint code and ConstraintType to use.
Bill Wendlingba54bca2013-06-19 21:36:55 +00006400 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chad Rosier3d716882012-10-30 19:11:54 +00006401
Chad Rosierdfa4cec2012-10-30 20:01:12 +00006402 // Ideally, we would only check against memory constraints. However, the
6403 // meaning of an other constraint can be target-specific and we can't easily
6404 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6405 // for other constriants as well.
Chad Rosier3d716882012-10-30 19:11:54 +00006406 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6407 OpInfo.ConstraintType == TargetLowering::C_Other) {
6408 if (OpInfo.Type == InlineAsm::isInput)
6409 ExtraInfo |= InlineAsm::Extra_MayLoad;
6410 else if (OpInfo.Type == InlineAsm::isOutput)
6411 ExtraInfo |= InlineAsm::Extra_MayStore;
Eric Christopherfffe3632013-01-11 18:12:39 +00006412 else if (OpInfo.Type == InlineAsm::isClobber)
6413 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
Chad Rosier3d716882012-10-30 19:11:54 +00006414 }
6415 }
6416
Evan Chengc36b7062011-01-07 23:50:32 +00006417 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
Bill Wendlingba54bca2013-06-19 21:36:55 +00006418 TLI->getPointerTy()));
Dale Johannesenf1e309e2010-07-02 20:16:09 +00006419
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006420 // Loop over all of the inputs, copying the operand values into the
6421 // appropriate registers and processing the output regs.
6422 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006423
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006424 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6425 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006426
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006427 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6428 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6429
6430 switch (OpInfo.Type) {
6431 case InlineAsm::isOutput: {
6432 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6433 OpInfo.ConstraintType != TargetLowering::C_Register) {
6434 // Memory output, or 'other' output (e.g. 'X' constraint).
6435 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6436
6437 // Add information to the INLINEASM node to know about this output.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006438 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6439 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
Bill Wendlingba54bca2013-06-19 21:36:55 +00006440 TLI->getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006441 AsmNodeOperands.push_back(OpInfo.CallOperand);
6442 break;
6443 }
6444
6445 // Otherwise, this is a register or register class output.
6446
6447 // Copy the output from the appropriate register. Find a register that
6448 // we can use.
Chris Lattnerfcd70902012-01-03 23:51:01 +00006449 if (OpInfo.AssignedRegs.Regs.empty()) {
6450 LLVMContext &Ctx = *DAG.getContext();
Stephen Lin155615d2013-07-08 00:37:03 +00006451 Ctx.emitError(CS.getInstruction(),
Chris Lattnerfcd70902012-01-03 23:51:01 +00006452 "couldn't allocate output register for constraint '" +
Eric Christopher1a54c572013-07-31 01:26:24 +00006453 Twine(OpInfo.ConstraintCode) + "'");
6454 return;
Chris Lattnerfcd70902012-01-03 23:51:01 +00006455 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006456
6457 // If this is an indirect operand, store through the pointer after the
6458 // asm.
6459 if (OpInfo.isIndirect) {
6460 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6461 OpInfo.CallOperandVal));
6462 } else {
6463 // This is the result value of the call.
Benjamin Kramerf0127052010-01-05 13:12:22 +00006464 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006465 // Concatenate this output onto the outputs list.
6466 RetValRegs.append(OpInfo.AssignedRegs);
6467 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006468
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006469 // Add information to the INLINEASM node to know that this register is
6470 // set.
Eric Christopherb0bee812013-07-30 22:50:44 +00006471 OpInfo.AssignedRegs
6472 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6473 ? InlineAsm::Kind_RegDefEarlyClobber
6474 : InlineAsm::Kind_RegDef,
6475 false, 0, DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006476 break;
6477 }
6478 case InlineAsm::isInput: {
6479 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006480
Chris Lattner6bdcda32008-10-17 16:47:46 +00006481 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006482 // If this is required to match an output register we have already set,
6483 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00006484 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006485
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006486 // Scan until we find the definition we already emitted of this operand.
6487 // When we find it, create a RegsForValue operand.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006488 unsigned CurOp = InlineAsm::Op_FirstOperand;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006489 for (; OperandNo; --OperandNo) {
6490 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00006491 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00006492 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00006493 assert((InlineAsm::isRegDefKind(OpFlag) ||
6494 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6495 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00006496 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006497 }
6498
Evan Cheng697cbbf2009-03-20 18:03:34 +00006499 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00006500 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00006501 if (InlineAsm::isRegDefKind(OpFlag) ||
6502 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
Evan Cheng697cbbf2009-03-20 18:03:34 +00006503 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Chris Lattner6129c372010-04-08 00:09:16 +00006504 if (OpInfo.isIndirect) {
6505 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
Dan Gohman99be8ae2010-04-19 22:41:47 +00006506 LLVMContext &Ctx = *DAG.getContext();
Eric Christopher1a54c572013-07-31 01:26:24 +00006507 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6508 " don't know how to handle tied "
6509 "indirect register inputs");
6510 return;
Chris Lattner6129c372010-04-08 00:09:16 +00006511 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006512
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006513 RegsForValue MatchedRegs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006514 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Patrik Hagglunda61b17c2012-12-13 06:34:11 +00006515 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
Evan Chengfb112882009-03-23 08:01:15 +00006516 MatchedRegs.RegVTs.push_back(RegVT);
6517 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00006518 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Chad Rosier2871ba92013-04-24 22:53:10 +00006519 i != e; ++i) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00006520 if (const TargetRegisterClass *RC = TLI->getRegClassFor(RegVT))
Chad Rosier2871ba92013-04-24 22:53:10 +00006521 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6522 else {
6523 LLVMContext &Ctx = *DAG.getContext();
Eric Christopher1a54c572013-07-31 01:26:24 +00006524 Ctx.emitError(CS.getInstruction(),
6525 "inline asm error: This value"
Chad Rosier2871ba92013-04-24 22:53:10 +00006526 " type register class is not natively supported!");
Eric Christopher1a54c572013-07-31 01:26:24 +00006527 return;
Chad Rosier2871ba92013-04-24 22:53:10 +00006528 }
6529 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006530 // Use the produced MatchedRegs object to
Andrew Trickac6d9be2013-05-25 02:42:55 +00006531 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
Bill Wendlingf18eb582012-09-26 06:16:18 +00006532 Chain, &Flag, CS.getInstruction());
Chris Lattnerdecc2672010-04-07 05:20:54 +00006533 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
Evan Chengfb112882009-03-23 08:01:15 +00006534 true, OpInfo.getMatchedOperand(),
Bill Wendling46ada192010-03-02 01:55:18 +00006535 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006536 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006537 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006538
Chris Lattnerdecc2672010-04-07 05:20:54 +00006539 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6540 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6541 "Unexpected number of operands");
6542 // Add information to the INLINEASM node to know about this input.
6543 // See InlineAsm.h isUseOperandTiedToDef.
6544 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6545 OpInfo.getMatchedOperand());
6546 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Bill Wendlingba54bca2013-06-19 21:36:55 +00006547 TLI->getPointerTy()));
Chris Lattnerdecc2672010-04-07 05:20:54 +00006548 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6549 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006550 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006551
Dale Johannesenb5611a62010-07-13 20:17:05 +00006552 // Treat indirect 'X' constraint as memory.
Michael J. Spencere70c5262010-10-16 08:25:21 +00006553 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6554 OpInfo.isIndirect)
Dale Johannesenb5611a62010-07-13 20:17:05 +00006555 OpInfo.ConstraintType = TargetLowering::C_Memory;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006556
Dale Johannesenb5611a62010-07-13 20:17:05 +00006557 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006558 std::vector<SDValue> Ops;
Bill Wendlingba54bca2013-06-19 21:36:55 +00006559 TLI->LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6560 Ops, DAG);
Chris Lattnerfcd70902012-01-03 23:51:01 +00006561 if (Ops.empty()) {
6562 LLVMContext &Ctx = *DAG.getContext();
6563 Ctx.emitError(CS.getInstruction(),
6564 "invalid operand for inline asm constraint '" +
Eric Christopher1a54c572013-07-31 01:26:24 +00006565 Twine(OpInfo.ConstraintCode) + "'");
6566 return;
Chris Lattnerfcd70902012-01-03 23:51:01 +00006567 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006568
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006569 // Add information to the INLINEASM node to know about this input.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006570 unsigned ResOpType =
6571 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006572 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Bill Wendlingba54bca2013-06-19 21:36:55 +00006573 TLI->getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006574 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6575 break;
Chris Lattnerdecc2672010-04-07 05:20:54 +00006576 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006577
Chris Lattnerdecc2672010-04-07 05:20:54 +00006578 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006579 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Bill Wendlingba54bca2013-06-19 21:36:55 +00006580 assert(InOperandVal.getValueType() == TLI->getPointerTy() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006581 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006582
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006583 // Add information to the INLINEASM node to know about this input.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006584 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
Dale Johannesen86b49f82008-09-24 01:07:17 +00006585 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Bill Wendlingba54bca2013-06-19 21:36:55 +00006586 TLI->getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006587 AsmNodeOperands.push_back(InOperandVal);
6588 break;
6589 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006590
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006591 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6592 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6593 "Unknown constraint type!");
Eric Christopher9eb4f8a2012-07-02 21:16:43 +00006594
6595 // TODO: Support this.
6596 if (OpInfo.isIndirect) {
6597 LLVMContext &Ctx = *DAG.getContext();
6598 Ctx.emitError(CS.getInstruction(),
6599 "Don't know how to handle indirect register inputs yet "
Eric Christopher1a54c572013-07-31 01:26:24 +00006600 "for constraint '" +
6601 Twine(OpInfo.ConstraintCode) + "'");
6602 return;
Eric Christopher9eb4f8a2012-07-02 21:16:43 +00006603 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006604
6605 // Copy the input into the appropriate registers.
Chris Lattnerfcd70902012-01-03 23:51:01 +00006606 if (OpInfo.AssignedRegs.Regs.empty()) {
6607 LLVMContext &Ctx = *DAG.getContext();
Stephen Lin155615d2013-07-08 00:37:03 +00006608 Ctx.emitError(CS.getInstruction(),
Chris Lattnerfcd70902012-01-03 23:51:01 +00006609 "couldn't allocate input reg for constraint '" +
Eric Christopher1a54c572013-07-31 01:26:24 +00006610 Twine(OpInfo.ConstraintCode) + "'");
6611 return;
Chris Lattnerfcd70902012-01-03 23:51:01 +00006612 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006613
Andrew Trickac6d9be2013-05-25 02:42:55 +00006614 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
Bill Wendlingf18eb582012-09-26 06:16:18 +00006615 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006616
Chris Lattnerdecc2672010-04-07 05:20:54 +00006617 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
Bill Wendling46ada192010-03-02 01:55:18 +00006618 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006619 break;
6620 }
6621 case InlineAsm::isClobber: {
6622 // Add the clobbered value to the operand list, so that the register
6623 // allocator is aware that the physreg got clobbered.
6624 if (!OpInfo.AssignedRegs.Regs.empty())
Jakob Stoklund Olesenf792fa92011-06-27 04:08:33 +00006625 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
Bill Wendling46ada192010-03-02 01:55:18 +00006626 false, 0, DAG,
Bill Wendling651ad132009-12-22 01:25:10 +00006627 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006628 break;
6629 }
6630 }
6631 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006632
Chris Lattnerdecc2672010-04-07 05:20:54 +00006633 // Finish up input operands. Set the input chain and add the flag last.
Dale Johannesenf1e309e2010-07-02 20:16:09 +00006634 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006635 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006636
Andrew Trickac6d9be2013-05-25 02:42:55 +00006637 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00006638 DAG.getVTList(MVT::Other, MVT::Glue),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006639 &AsmNodeOperands[0], AsmNodeOperands.size());
6640 Flag = Chain.getValue(1);
6641
6642 // If this asm returns a register value, copy the result from that register
6643 // and set it as the value of the call.
6644 if (!RetValRegs.Regs.empty()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006645 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
Bill Wendling12931302012-09-26 04:04:19 +00006646 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006647
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006648 // FIXME: Why don't we do this for inline asms with MRVs?
6649 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00006650 EVT ResultType = TLI->getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006651
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006652 // If any of the results of the inline asm is a vector, it may have the
6653 // wrong width/num elts. This can happen for register classes that can
6654 // contain multiple different value types. The preg or vreg allocated may
6655 // not have the same VT as was expected. Convert it to the right type
6656 // with bit_convert.
6657 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006658 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00006659 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00006660
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006661 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006662 ResultType.isInteger() && Val.getValueType().isInteger()) {
6663 // If a result value was tied to an input value, the computed result may
6664 // have a wider width than the expected result. Extract the relevant
6665 // portion.
Andrew Trickac6d9be2013-05-25 02:42:55 +00006666 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00006667 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006668
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006669 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00006670 }
Dan Gohman95915732008-10-18 01:03:45 +00006671
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006672 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00006673 // Don't need to use this as a chain in this case.
6674 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6675 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006676 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006677
Dan Gohman46510a72010-04-15 01:51:59 +00006678 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006679
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006680 // Process indirect outputs, first output all of the flagged copies out of
6681 // physregs.
6682 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6683 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Dan Gohman46510a72010-04-15 01:51:59 +00006684 const Value *Ptr = IndirectStoresToEmit[i].second;
Andrew Trickac6d9be2013-05-25 02:42:55 +00006685 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
Bill Wendling12931302012-09-26 04:04:19 +00006686 Chain, &Flag, IA);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006687 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6688 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006689
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006690 // Emit the non-flagged stores from the physregs.
6691 SmallVector<SDValue, 8> OutChains;
Bill Wendling651ad132009-12-22 01:25:10 +00006692 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006693 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
Bill Wendling651ad132009-12-22 01:25:10 +00006694 StoresToEmit[i].first,
6695 getValue(StoresToEmit[i].second),
Chris Lattner84bd98a2010-09-21 18:58:22 +00006696 MachinePointerInfo(StoresToEmit[i].second),
David Greene1e559442010-02-15 17:00:31 +00006697 false, false, 0);
Bill Wendling651ad132009-12-22 01:25:10 +00006698 OutChains.push_back(Val);
Bill Wendling651ad132009-12-22 01:25:10 +00006699 }
6700
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006701 if (!OutChains.empty())
Andrew Trickac6d9be2013-05-25 02:42:55 +00006702 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006703 &OutChains[0], OutChains.size());
Bill Wendling651ad132009-12-22 01:25:10 +00006704
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006705 DAG.setRoot(Chain);
6706}
6707
Dan Gohman46510a72010-04-15 01:51:59 +00006708void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006709 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006710 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006711 getValue(I.getArgOperand(0)),
6712 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006713}
6714
Dan Gohman46510a72010-04-15 01:51:59 +00006715void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
Bill Wendlingba54bca2013-06-19 21:36:55 +00006716 const TargetLowering *TLI = TM.getTargetLowering();
6717 const DataLayout &TD = *TLI->getDataLayout();
6718 SDValue V = DAG.getVAArg(TLI->getValueType(I.getType()), getCurSDLoc(),
Dale Johannesena04b7572009-02-03 23:04:43 +00006719 getRoot(), getValue(I.getOperand(0)),
Rafael Espindolacbeeae22010-07-11 04:01:49 +00006720 DAG.getSrcValue(I.getOperand(0)),
Rafael Espindola9d544d02010-07-12 18:11:17 +00006721 TD.getABITypeAlignment(I.getType()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006722 setValue(&I, V);
6723 DAG.setRoot(V.getValue(1));
6724}
6725
Dan Gohman46510a72010-04-15 01:51:59 +00006726void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006727 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006728 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006729 getValue(I.getArgOperand(0)),
6730 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006731}
6732
Dan Gohman46510a72010-04-15 01:51:59 +00006733void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
Andrew Trickac6d9be2013-05-25 02:42:55 +00006734 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006735 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006736 getValue(I.getArgOperand(0)),
6737 getValue(I.getArgOperand(1)),
6738 DAG.getSrcValue(I.getArgOperand(0)),
6739 DAG.getSrcValue(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006740}
6741
Andrew Trick2343e3b2013-10-31 17:18:24 +00006742/// \brief Lower an argument list according to the target calling convention.
6743///
6744/// \return A tuple of <return-value, token-chain>
6745///
6746/// This is a helper for lowering intrinsics that follow a target calling
6747/// convention or require stack pointer adjustment. Only a subset of the
6748/// intrinsic's operands need to participate in the calling convention.
6749std::pair<SDValue, SDValue>
6750SelectionDAGBuilder::LowerCallOperands(const CallInst &CI, unsigned ArgIdx,
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006751 unsigned NumArgs, SDValue Callee,
6752 bool useVoidTy) {
Andrew Trick2343e3b2013-10-31 17:18:24 +00006753 TargetLowering::ArgListTy Args;
6754 Args.reserve(NumArgs);
6755
6756 // Populate the argument list.
6757 // Attributes for args start at offset 1, after the return attribute.
6758 ImmutableCallSite CS(&CI);
6759 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6760 ArgI != ArgE; ++ArgI) {
6761 const Value *V = CI.getOperand(ArgI);
6762
6763 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6764
6765 TargetLowering::ArgListEntry Entry;
6766 Entry.Node = getValue(V);
6767 Entry.Ty = V->getType();
6768 Entry.setAttributes(&CS, AttrI);
6769 Args.push_back(Entry);
6770 }
6771
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006772 Type *retTy = useVoidTy ? Type::getVoidTy(*DAG.getContext()) : CI.getType();
6773 TargetLowering::CallLoweringInfo CLI(getRoot(), retTy, /*retSExt*/ false,
6774 /*retZExt*/ false, /*isVarArg*/ false, /*isInReg*/ false, NumArgs,
6775 CI.getCallingConv(), /*isTailCall*/ false, /*doesNotReturn*/ false,
Andrew Trick2343e3b2013-10-31 17:18:24 +00006776 /*isReturnValueUsed*/ CI.use_empty(), Callee, Args, DAG, getCurSDLoc());
6777
6778 const TargetLowering *TLI = TM.getTargetLowering();
6779 return TLI->LowerCallTo(CLI);
6780}
6781
6782/// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6783void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6784 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6785 // [live variables...])
6786
6787 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6788
6789 SDValue Callee = getValue(CI.getCalledValue());
6790
6791 // Lower into a call sequence with no args and no return value.
6792 std::pair<SDValue, SDValue> Result = LowerCallOperands(CI, 0, 0, Callee);
6793 // Set the root to the target-lowered call chain.
6794 SDValue Chain = Result.second;
6795 DAG.setRoot(Chain);
6796
6797 /// Get a call instruction from the call sequence chain.
6798 /// Tail calls are not allowed.
6799 SDNode *CallEnd = Chain.getNode();
6800 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6801 "Expected a callseq node.");
6802 SDNode *Call = CallEnd->getOperand(0).getNode();
6803 bool hasGlue = Call->getGluedNode();
6804
Andrew Trick2343e3b2013-10-31 17:18:24 +00006805 // Replace the target specific call node with the stackmap intrinsic.
6806 SmallVector<SDValue, 8> Ops;
6807
6808 // Add the <id> and <numShadowBytes> constants.
6809 for (unsigned i = 0; i < 2; ++i) {
6810 SDValue tmp = getValue(CI.getOperand(i));
6811 Ops.push_back(DAG.getTargetConstant(
6812 cast<ConstantSDNode>(tmp)->getZExtValue(), MVT::i32));
6813 }
6814 // Push live variables for the stack map.
6815 for (unsigned i = 2, e = CI.getNumArgOperands(); i != e; ++i)
6816 Ops.push_back(getValue(CI.getArgOperand(i)));
6817
6818 // Push the chain (this is originally the first operand of the call, but
6819 // becomes now the last or second to last operand).
6820 Ops.push_back(*(Call->op_begin()));
6821
6822 // Push the glue flag (last operand).
6823 if (hasGlue)
6824 Ops.push_back(*(Call->op_end()-1));
6825
Andrew Trick2343e3b2013-10-31 17:18:24 +00006826 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Andrew Trickdc8224d2013-11-05 22:44:04 +00006827
6828 // Replace the target specific call node with a STACKMAP node.
6829 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::STACKMAP, getCurSDLoc(),
6830 NodeTys, Ops);
6831
6832 // StackMap generates no value, so nothing goes in the NodeMap.
6833
6834 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
6835 // call sequence.
6836 DAG.ReplaceAllUsesWith(Call, MN);
6837
6838 DAG.DeleteNode(Call);
Andrew Trick2343e3b2013-10-31 17:18:24 +00006839}
6840
6841/// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
6842void SelectionDAGBuilder::visitPatchpoint(const CallInst &CI) {
6843 // void|i64 @llvm.experimental.patchpoint.void|i64(i32 <id>,
Andrew Trick72cf01c2013-11-14 06:54:10 +00006844 // i32 <numBytes>,
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006845 // i8* <target>,
6846 // i32 <numArgs>,
6847 // [Args...],
6848 // [live variables...])
Andrew Trick2343e3b2013-10-31 17:18:24 +00006849
Juergen Ributzkad4f5a612013-11-09 01:51:33 +00006850 CallingConv::ID CC = CI.getCallingConv();
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006851 bool isAnyRegCC = CC == CallingConv::AnyReg;
6852 bool hasDef = !CI.getType()->isVoidTy();
Andrew Trick2343e3b2013-10-31 17:18:24 +00006853 SDValue Callee = getValue(CI.getOperand(2)); // <target>
6854
6855 // Get the real number of arguments participating in the call <numArgs>
6856 unsigned NumArgs =
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006857 cast<ConstantSDNode>(getValue(CI.getArgOperand(3)))->getZExtValue();
Andrew Trick2343e3b2013-10-31 17:18:24 +00006858
6859 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
6860 assert(CI.getNumArgOperands() >= NumArgs + 4 &&
6861 "Not enough arguments provided to the patchpoint intrinsic");
6862
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006863 // For AnyRegCC the arguments are lowered later on manually.
6864 unsigned NumCallArgs = isAnyRegCC ? 0 : NumArgs;
Andrew Trick2343e3b2013-10-31 17:18:24 +00006865 std::pair<SDValue, SDValue> Result =
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006866 LowerCallOperands(CI, 4, NumCallArgs, Callee, isAnyRegCC);
6867
Andrew Trick2343e3b2013-10-31 17:18:24 +00006868 // Set the root to the target-lowered call chain.
6869 SDValue Chain = Result.second;
6870 DAG.setRoot(Chain);
6871
6872 SDNode *CallEnd = Chain.getNode();
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006873 if (hasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
6874 CallEnd = CallEnd->getOperand(0).getNode();
6875
Andrew Trick2343e3b2013-10-31 17:18:24 +00006876 /// Get a call instruction from the call sequence chain.
6877 /// Tail calls are not allowed.
6878 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6879 "Expected a callseq node.");
6880 SDNode *Call = CallEnd->getOperand(0).getNode();
6881 bool hasGlue = Call->getGluedNode();
6882
6883 // Replace the target specific call node with the patchable intrinsic.
6884 SmallVector<SDValue, 8> Ops;
6885
6886 // Add the <id> and <numNopBytes> constants.
6887 for (unsigned i = 0; i < 2; ++i) {
6888 SDValue tmp = getValue(CI.getOperand(i));
6889 Ops.push_back(DAG.getTargetConstant(
6890 cast<ConstantSDNode>(tmp)->getZExtValue(), MVT::i32));
6891 }
6892 // Assume that the Callee is a constant address.
6893 Ops.push_back(
Juergen Ributzkad4f5a612013-11-09 01:51:33 +00006894 DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
6895 /*isTarget=*/true));
Andrew Trick2343e3b2013-10-31 17:18:24 +00006896
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006897 // Adjust <numArgs> to account for any arguments that have been passed on the
6898 // stack instead.
Andrew Trick2343e3b2013-10-31 17:18:24 +00006899 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006900 unsigned NumCallRegArgs = Call->getNumOperands() - (hasGlue ? 4 : 3);
6901 NumCallRegArgs = isAnyRegCC ? NumArgs : NumCallRegArgs;
6902 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
6903
6904 // Add the calling convention
Juergen Ributzkad4f5a612013-11-09 01:51:33 +00006905 Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006906
6907 // Add the arguments we omitted previously. The register allocator should
6908 // place these in any free register.
6909 if (isAnyRegCC)
6910 for (unsigned i = 4, e = NumArgs + 4; i != e; ++i)
6911 Ops.push_back(getValue(CI.getArgOperand(i)));
Andrew Trick2343e3b2013-10-31 17:18:24 +00006912
6913 // Push the arguments from the call instruction.
6914 SDNode::op_iterator e = hasGlue ? Call->op_end()-2 : Call->op_end()-1;
6915 for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
6916 Ops.push_back(*i);
6917
6918 // Push live variables for the stack map.
6919 for (unsigned i = NumArgs + 4, e = CI.getNumArgOperands(); i != e; ++i) {
6920 SDValue OpVal = getValue(CI.getArgOperand(i));
6921 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6922 Ops.push_back(
Andrew Trick3d74dea2013-10-31 22:11:56 +00006923 DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
6924 Ops.push_back(
Andrew Trick2343e3b2013-10-31 17:18:24 +00006925 DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
6926 } else
6927 Ops.push_back(OpVal);
6928 }
6929
6930 // Push the register mask info.
6931 if (hasGlue)
6932 Ops.push_back(*(Call->op_end()-2));
6933 else
6934 Ops.push_back(*(Call->op_end()-1));
6935
6936 // Push the chain (this is originally the first operand of the call, but
6937 // becomes now the last or second to last operand).
6938 Ops.push_back(*(Call->op_begin()));
6939
6940 // Push the glue flag (last operand).
6941 if (hasGlue)
6942 Ops.push_back(*(Call->op_end()-1));
6943
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006944 SDVTList NodeTys;
6945 if (isAnyRegCC && hasDef) {
6946 // Create the return types based on the intrinsic definition
6947 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6948 SmallVector<EVT, 3> ValueVTs;
6949 ComputeValueVTs(TLI, CI.getType(), ValueVTs);
6950 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
Andrew Trickdc8224d2013-11-05 22:44:04 +00006951
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006952 // There is always a chain and a glue type at the end
6953 ValueVTs.push_back(MVT::Other);
6954 ValueVTs.push_back(MVT::Glue);
6955 NodeTys = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
6956 } else
6957 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6958
6959 // Replace the target specific call node with a PATCHPOINT node.
Andrew Trickdc8224d2013-11-05 22:44:04 +00006960 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
6961 getCurSDLoc(), NodeTys, Ops);
6962
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006963 // Update the NodeMap.
6964 if (hasDef) {
6965 if (isAnyRegCC)
6966 setValue(&CI, SDValue(MN, 0));
6967 else
6968 setValue(&CI, Result.first);
6969 }
Andrew Trickdc8224d2013-11-05 22:44:04 +00006970
6971 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
Juergen Ributzka623d2e62013-11-08 23:28:16 +00006972 // call sequence. Furthermore the location of the chain and glue can change
6973 // when the AnyReg calling convention is used and the intrinsic returns a
6974 // value.
6975 if (isAnyRegCC && hasDef) {
6976 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
6977 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
6978 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
6979 } else
6980 DAG.ReplaceAllUsesWith(Call, MN);
Andrew Trickdc8224d2013-11-05 22:44:04 +00006981 DAG.DeleteNode(Call);
Andrew Trick2343e3b2013-10-31 17:18:24 +00006982}
6983
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006984/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohman98ca4f22009-08-05 01:29:28 +00006985/// implementation, which just calls LowerCall.
6986/// FIXME: When all targets are
6987/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006988std::pair<SDValue, SDValue>
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006989TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
Stephen Lin3484da92013-04-30 22:49:28 +00006990 // Handle the incoming return values from the call.
6991 CLI.Ins.clear();
6992 SmallVector<EVT, 4> RetTys;
6993 ComputeValueVTs(*this, CLI.RetTy, RetTys);
6994 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6995 EVT VT = RetTys[I];
6996 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6997 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
6998 for (unsigned i = 0; i != NumRegs; ++i) {
6999 ISD::InputArg MyFlags;
7000 MyFlags.VT = RegisterVT;
Tom Stellardd0716b02013-10-23 00:44:24 +00007001 MyFlags.ArgVT = VT;
Stephen Lin3484da92013-04-30 22:49:28 +00007002 MyFlags.Used = CLI.IsReturnValueUsed;
7003 if (CLI.RetSExt)
7004 MyFlags.Flags.setSExt();
7005 if (CLI.RetZExt)
7006 MyFlags.Flags.setZExt();
7007 if (CLI.IsInReg)
7008 MyFlags.Flags.setInReg();
7009 CLI.Ins.push_back(MyFlags);
7010 }
7011 }
7012
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007013 // Handle all of the outgoing arguments.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007014 CLI.Outs.clear();
7015 CLI.OutVals.clear();
7016 ArgListTy &Args = CLI.Args;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007017 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00007018 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007019 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
7020 for (unsigned Value = 0, NumValues = ValueVTs.size();
7021 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00007022 EVT VT = ValueVTs[Value];
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007023 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
Chris Lattner2a0b96c2008-10-18 18:49:30 +00007024 SDValue Op = SDValue(Args[i].Node.getNode(),
7025 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007026 ISD::ArgFlagsTy Flags;
7027 unsigned OriginalAlignment =
Micah Villmow3574eca2012-10-08 16:38:25 +00007028 getDataLayout()->getABITypeAlignment(ArgTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007029
7030 if (Args[i].isZExt)
7031 Flags.setZExt();
7032 if (Args[i].isSExt)
7033 Flags.setSExt();
7034 if (Args[i].isInReg)
7035 Flags.setInReg();
7036 if (Args[i].isSRet)
7037 Flags.setSRet();
7038 if (Args[i].isByVal) {
7039 Flags.setByVal();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00007040 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7041 Type *ElementTy = Ty->getElementType();
Micah Villmow3574eca2012-10-08 16:38:25 +00007042 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007043 // For ByVal, alignment should come from FE. BE will guess if this
7044 // info is not there but there are cases it cannot get right.
Chris Lattner9db20f32011-05-22 23:23:02 +00007045 unsigned FrameAlign;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007046 if (Args[i].Alignment)
7047 FrameAlign = Args[i].Alignment;
Chris Lattner9db20f32011-05-22 23:23:02 +00007048 else
7049 FrameAlign = getByValTypeAlignment(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007050 Flags.setByValAlign(FrameAlign);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007051 }
7052 if (Args[i].isNest)
7053 Flags.setNest();
7054 Flags.setOrigAlign(OriginalAlignment);
7055
Patrik Hagglunddfcf33a2012-12-19 11:48:16 +00007056 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007057 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007058 SmallVector<SDValue, 4> Parts(NumParts);
7059 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7060
7061 if (Args[i].isSExt)
7062 ExtendKind = ISD::SIGN_EXTEND;
7063 else if (Args[i].isZExt)
7064 ExtendKind = ISD::ZERO_EXTEND;
7065
Stephen Lin3484da92013-04-30 22:49:28 +00007066 // Conservatively only handle 'returned' on non-vectors for now
7067 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7068 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7069 "unexpected use of 'returned'");
7070 // Before passing 'returned' to the target lowering code, ensure that
7071 // either the register MVT and the actual EVT are the same size or that
7072 // the return value and argument are extended in the same way; in these
7073 // cases it's safe to pass the argument register value unchanged as the
7074 // return register value (although it's at the target's option whether
7075 // to do so)
7076 // TODO: allow code generation to take advantage of partially preserved
7077 // registers rather than clobbering the entire register when the
7078 // parameter extension method is not compatible with the return
7079 // extension method
7080 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7081 (ExtendKind != ISD::ANY_EXTEND &&
7082 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7083 Flags.setReturned();
7084 }
7085
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007086 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts,
Bill Wendlingf18eb582012-09-26 06:16:18 +00007087 PartVT, CLI.CS ? CLI.CS->getInstruction() : 0, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007088
Dan Gohman98ca4f22009-08-05 01:29:28 +00007089 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007090 // if it isn't first piece, alignment must be 1
Tom Stellardd0716b02013-10-23 00:44:24 +00007091 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
Manman Ren0a1544d2012-11-01 23:49:58 +00007092 i < CLI.NumFixedArgs,
7093 i, j*Parts[j].getValueType().getStoreSize());
Dan Gohman98ca4f22009-08-05 01:29:28 +00007094 if (NumParts > 1 && j == 0)
7095 MyFlags.Flags.setSplit();
7096 else if (j != 0)
7097 MyFlags.Flags.setOrigAlign(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007098
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007099 CLI.Outs.push_back(MyFlags);
7100 CLI.OutVals.push_back(Parts[j]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007101 }
7102 }
7103 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00007104
Dan Gohman98ca4f22009-08-05 01:29:28 +00007105 SmallVector<SDValue, 4> InVals;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007106 CLI.Chain = LowerCall(CLI, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00007107
7108 // Verify that the target's LowerCall behaved as expected.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007109 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00007110 "LowerCall didn't return a valid chain!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007111 assert((!CLI.IsTailCall || InVals.empty()) &&
Dan Gohman5e866062009-08-06 15:37:27 +00007112 "LowerCall emitted a return value for a tail call!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007113 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
Dan Gohman5e866062009-08-06 15:37:27 +00007114 "LowerCall didn't emit the correct number of values!");
Dan Gohman98ca4f22009-08-05 01:29:28 +00007115
7116 // For a tail call, the return value is merely live-out and there aren't
7117 // any nodes in the DAG representing it. Return a special value to
7118 // indicate that a tail call has been emitted and no more Instructions
7119 // should be processed in the current block.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007120 if (CLI.IsTailCall) {
7121 CLI.DAG.setRoot(CLI.Chain);
Dan Gohman98ca4f22009-08-05 01:29:28 +00007122 return std::make_pair(SDValue(), SDValue());
7123 }
7124
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007125 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
Evan Chengaf1871f2010-03-11 19:38:18 +00007126 assert(InVals[i].getNode() &&
7127 "LowerCall emitted a null value!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007128 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
Evan Chengaf1871f2010-03-11 19:38:18 +00007129 "LowerCall emitted a value with the wrong type!");
7130 });
7131
Dan Gohman98ca4f22009-08-05 01:29:28 +00007132 // Collect the legal value parts into potentially illegal values
7133 // that correspond to the original function's return values.
7134 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007135 if (CLI.RetSExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00007136 AssertOp = ISD::AssertSext;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007137 else if (CLI.RetZExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00007138 AssertOp = ISD::AssertZext;
7139 SmallVector<SDValue, 4> ReturnValues;
7140 unsigned CurReg = 0;
7141 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00007142 EVT VT = RetTys[I];
Patrik Hagglunddfcf33a2012-12-19 11:48:16 +00007143 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007144 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00007145
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007146 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
Bill Wendling12931302012-09-26 04:04:19 +00007147 NumRegs, RegisterVT, VT, NULL,
Bill Wendling4533cac2010-01-28 21:51:40 +00007148 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00007149 CurReg += NumRegs;
7150 }
7151
7152 // For a function returning void, there is no return value. We can't create
7153 // such a node, so we just return a null return value in that case. In
Chris Lattner7a2bdde2011-04-15 05:18:47 +00007154 // that case, nothing will actually look at the value.
Dan Gohman98ca4f22009-08-05 01:29:28 +00007155 if (ReturnValues.empty())
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007156 return std::make_pair(SDValue(), CLI.Chain);
Dan Gohman98ca4f22009-08-05 01:29:28 +00007157
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007158 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7159 CLI.DAG.getVTList(&RetTys[0], RetTys.size()),
Dan Gohman98ca4f22009-08-05 01:29:28 +00007160 &ReturnValues[0], ReturnValues.size());
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00007161 return std::make_pair(Res, CLI.Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007162}
7163
Duncan Sands9fbc7e22009-01-21 09:00:29 +00007164void TargetLowering::LowerOperationWrapper(SDNode *N,
7165 SmallVectorImpl<SDValue> &Results,
Dan Gohmand858e902010-04-17 15:26:15 +00007166 SelectionDAG &DAG) const {
Duncan Sands9fbc7e22009-01-21 09:00:29 +00007167 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00007168 if (Res.getNode())
7169 Results.push_back(Res);
7170}
7171
Dan Gohmand858e902010-04-17 15:26:15 +00007172SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
Torok Edwinc23197a2009-07-14 16:55:14 +00007173 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007174}
7175
Dan Gohman46510a72010-04-15 01:51:59 +00007176void
7177SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
Dan Gohman28a17352010-07-01 01:59:43 +00007178 SDValue Op = getNonRegisterValue(V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007179 assert((Op.getOpcode() != ISD::CopyFromReg ||
7180 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7181 "Copy from a reg to the same reg!");
7182 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7183
Bill Wendlingba54bca2013-06-19 21:36:55 +00007184 const TargetLowering *TLI = TM.getTargetLowering();
7185 RegsForValue RFV(V->getContext(), *TLI, Reg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007186 SDValue Chain = DAG.getEntryNode();
Andrew Trickac6d9be2013-05-25 02:42:55 +00007187 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, 0, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007188 PendingExports.push_back(Chain);
7189}
7190
7191#include "llvm/CodeGen/SelectionDAGISel.h"
7192
Eli Friedman23d32432011-05-05 16:53:34 +00007193/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7194/// entry block, return true. This includes arguments used by switches, since
7195/// the switch may expand into multiple basic blocks.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00007196static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
Eli Friedman23d32432011-05-05 16:53:34 +00007197 // With FastISel active, we may be splitting blocks, so force creation
7198 // of virtual registers for all non-dead arguments.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00007199 if (FastISel)
Eli Friedman23d32432011-05-05 16:53:34 +00007200 return A->use_empty();
7201
7202 const BasicBlock *Entry = A->getParent()->begin();
7203 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
7204 UI != E; ++UI) {
7205 const User *U = *UI;
7206 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7207 return false; // Use not in entry block.
7208 }
7209 return true;
7210}
7211
Eli Bendersky6437d382013-02-28 23:09:18 +00007212void SelectionDAGISel::LowerArguments(const Function &F) {
Dan Gohman2048b852009-11-23 18:04:58 +00007213 SelectionDAG &DAG = SDB->DAG;
Andrew Trickac6d9be2013-05-25 02:42:55 +00007214 SDLoc dl = SDB->getCurSDLoc();
Bill Wendlingba54bca2013-06-19 21:36:55 +00007215 const TargetLowering *TLI = getTargetLowering();
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00007216 const DataLayout *TD = TLI->getDataLayout();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00007217 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007218
Dan Gohman7451d3e2010-05-29 17:03:36 +00007219 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00007220 // Put in an sret pointer parameter before all the other parameters.
7221 SmallVector<EVT, 1> ValueVTs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00007222 ComputeValueVTs(*getTargetLowering(),
7223 PointerType::getUnqual(F.getReturnType()), ValueVTs);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00007224
7225 // NOTE: Assuming that a pointer will never break down to more than one VT
7226 // or one register.
7227 ISD::ArgFlagsTy Flags;
7228 Flags.setSRet();
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00007229 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
Tom Stellardd0716b02013-10-23 00:44:24 +00007230 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00007231 Ins.push_back(RetArg);
7232 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00007233
Dan Gohman98ca4f22009-08-05 01:29:28 +00007234 // Set up the incoming argument description vector.
Dan Gohman98ca4f22009-08-05 01:29:28 +00007235 unsigned Idx = 1;
Dan Gohman46510a72010-04-15 01:51:59 +00007236 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
Dan Gohman98ca4f22009-08-05 01:29:28 +00007237 I != E; ++I, ++Idx) {
Owen Andersone50ed302009-08-10 22:56:29 +00007238 SmallVector<EVT, 4> ValueVTs;
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00007239 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
Dan Gohman98ca4f22009-08-05 01:29:28 +00007240 bool isArgValueUsed = !I->use_empty();
Tom Stellardd0716b02013-10-23 00:44:24 +00007241 unsigned PartBase = 0;
Dan Gohman98ca4f22009-08-05 01:29:28 +00007242 for (unsigned Value = 0, NumValues = ValueVTs.size();
7243 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00007244 EVT VT = ValueVTs[Value];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00007245 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohman98ca4f22009-08-05 01:29:28 +00007246 ISD::ArgFlagsTy Flags;
7247 unsigned OriginalAlignment =
7248 TD->getABITypeAlignment(ArgTy);
7249
Bill Wendling39cd0c82012-12-30 12:45:13 +00007250 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00007251 Flags.setZExt();
Bill Wendling39cd0c82012-12-30 12:45:13 +00007252 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00007253 Flags.setSExt();
Bill Wendling39cd0c82012-12-30 12:45:13 +00007254 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
Dan Gohman98ca4f22009-08-05 01:29:28 +00007255 Flags.setInReg();
Bill Wendling39cd0c82012-12-30 12:45:13 +00007256 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
Dan Gohman98ca4f22009-08-05 01:29:28 +00007257 Flags.setSRet();
Bill Wendling39cd0c82012-12-30 12:45:13 +00007258 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) {
Dan Gohman98ca4f22009-08-05 01:29:28 +00007259 Flags.setByVal();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00007260 PointerType *Ty = cast<PointerType>(I->getType());
7261 Type *ElementTy = Ty->getElementType();
Chris Lattner9db20f32011-05-22 23:23:02 +00007262 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
Dan Gohman98ca4f22009-08-05 01:29:28 +00007263 // For ByVal, alignment should be passed from FE. BE will guess if
7264 // this info is not there but there are cases it cannot get right.
Chris Lattner9db20f32011-05-22 23:23:02 +00007265 unsigned FrameAlign;
Dan Gohman98ca4f22009-08-05 01:29:28 +00007266 if (F.getParamAlignment(Idx))
7267 FrameAlign = F.getParamAlignment(Idx);
Chris Lattner9db20f32011-05-22 23:23:02 +00007268 else
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00007269 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
Dan Gohman98ca4f22009-08-05 01:29:28 +00007270 Flags.setByValAlign(FrameAlign);
Dan Gohman98ca4f22009-08-05 01:29:28 +00007271 }
Bill Wendling39cd0c82012-12-30 12:45:13 +00007272 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
Dan Gohman98ca4f22009-08-05 01:29:28 +00007273 Flags.setNest();
7274 Flags.setOrigAlign(OriginalAlignment);
7275
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00007276 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7277 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00007278 for (unsigned i = 0; i != NumRegs; ++i) {
Tom Stellardd0716b02013-10-23 00:44:24 +00007279 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7280 Idx-1, PartBase+i*RegisterVT.getStoreSize());
Dan Gohman98ca4f22009-08-05 01:29:28 +00007281 if (NumRegs > 1 && i == 0)
7282 MyFlags.Flags.setSplit();
7283 // if it isn't first piece, alignment must be 1
7284 else if (i > 0)
7285 MyFlags.Flags.setOrigAlign(1);
7286 Ins.push_back(MyFlags);
7287 }
Tom Stellardd0716b02013-10-23 00:44:24 +00007288 PartBase += VT.getStoreSize();
Dan Gohman98ca4f22009-08-05 01:29:28 +00007289 }
7290 }
7291
7292 // Call the target to set up the argument values.
7293 SmallVector<SDValue, 8> InVals;
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00007294 SDValue NewRoot = TLI->LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
7295 F.isVarArg(), Ins,
7296 dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00007297
7298 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00007299 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00007300 "LowerFormalArguments didn't return a valid chain!");
7301 assert(InVals.size() == Ins.size() &&
7302 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendling3ea58b62009-12-22 21:35:02 +00007303 DEBUG({
7304 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7305 assert(InVals[i].getNode() &&
7306 "LowerFormalArguments emitted a null value!");
Duncan Sands1440e8b2010-11-03 11:35:31 +00007307 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
Bill Wendling3ea58b62009-12-22 21:35:02 +00007308 "LowerFormalArguments emitted a value with the wrong type!");
7309 }
7310 });
Bill Wendling3ea3c242009-12-22 02:10:19 +00007311
Dan Gohman5e866062009-08-06 15:37:27 +00007312 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00007313 DAG.setRoot(NewRoot);
7314
7315 // Set up the argument values.
7316 unsigned i = 0;
7317 Idx = 1;
Dan Gohman7451d3e2010-05-29 17:03:36 +00007318 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00007319 // Create a virtual register for the sret pointer, and put in a copy
7320 // from the sret argument into it.
7321 SmallVector<EVT, 1> ValueVTs;
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00007322 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
Patrik Hagglunda61b17c2012-12-13 06:34:11 +00007323 MVT VT = ValueVTs[0].getSimpleVT();
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00007324 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00007325 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling46ada192010-03-02 01:55:18 +00007326 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
Bill Wendling12931302012-09-26 04:04:19 +00007327 RegVT, VT, NULL, AssertOp);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00007328
Dan Gohman2048b852009-11-23 18:04:58 +00007329 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00007330 MachineRegisterInfo& RegInfo = MF.getRegInfo();
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00007331 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
Dan Gohman7451d3e2010-05-29 17:03:36 +00007332 FuncInfo->DemoteRegister = SRetReg;
Andrew Trickac6d9be2013-05-25 02:42:55 +00007333 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(),
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00007334 SRetReg, ArgValue);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00007335 DAG.setRoot(NewRoot);
Bill Wendling3ea3c242009-12-22 02:10:19 +00007336
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00007337 // i indexes lowered arguments. Bump it past the hidden sret argument.
7338 // Idx indexes LLVM arguments. Don't touch it.
7339 ++i;
7340 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00007341
Dan Gohman46510a72010-04-15 01:51:59 +00007342 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohman98ca4f22009-08-05 01:29:28 +00007343 ++I, ++Idx) {
7344 SmallVector<SDValue, 4> ArgValues;
Owen Andersone50ed302009-08-10 22:56:29 +00007345 SmallVector<EVT, 4> ValueVTs;
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00007346 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007347 unsigned NumValues = ValueVTs.size();
Devang Patel9126c0d2010-06-01 19:59:01 +00007348
7349 // If this argument is unused then remember its value. It is used to generate
7350 // debugging information.
Adrian Prantldf688032013-05-16 23:44:12 +00007351 if (I->use_empty() && NumValues) {
Devang Patel9126c0d2010-06-01 19:59:01 +00007352 SDB->setUnusedArgValue(I, InVals[i]);
7353
Adrian Prantldf688032013-05-16 23:44:12 +00007354 // Also remember any frame index for use in FastISel.
7355 if (FrameIndexSDNode *FI =
7356 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7357 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7358 }
7359
Eli Friedman23d32432011-05-05 16:53:34 +00007360 for (unsigned Val = 0; Val != NumValues; ++Val) {
7361 EVT VT = ValueVTs[Val];
Bill Wendling6a2e7ac2013-06-06 00:43:09 +00007362 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7363 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00007364
7365 if (!I->use_empty()) {
7366 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling39cd0c82012-12-30 12:45:13 +00007367 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00007368 AssertOp = ISD::AssertSext;
Bill Wendling39cd0c82012-12-30 12:45:13 +00007369 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00007370 AssertOp = ISD::AssertZext;
7371
Bill Wendling46ada192010-03-02 01:55:18 +00007372 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
Bill Wendling3ea3c242009-12-22 02:10:19 +00007373 NumParts, PartVT, VT,
Bill Wendling12931302012-09-26 04:04:19 +00007374 NULL, AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00007375 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00007376
Dan Gohman98ca4f22009-08-05 01:29:28 +00007377 i += NumParts;
7378 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00007379
Eli Friedman23d32432011-05-05 16:53:34 +00007380 // We don't need to do anything else for unused arguments.
7381 if (ArgValues.empty())
7382 continue;
7383
Devang Patel9aee3352011-09-08 22:59:09 +00007384 // Note down frame index.
7385 if (FrameIndexSDNode *FI =
Bill Wendling96cb1122012-07-19 00:04:14 +00007386 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
Devang Patel9aee3352011-09-08 22:59:09 +00007387 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
Devang Patel0b48ead2010-08-31 22:22:42 +00007388
Eli Friedman23d32432011-05-05 16:53:34 +00007389 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
Andrew Trickac6d9be2013-05-25 02:42:55 +00007390 SDB->getCurSDLoc());
Devang Patel9aee3352011-09-08 22:59:09 +00007391
Eli Friedman23d32432011-05-05 16:53:34 +00007392 SDB->setValue(I, Res);
Nick Lewycky8a8d4792011-12-02 22:16:29 +00007393 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
Stephen Lin155615d2013-07-08 00:37:03 +00007394 if (LoadSDNode *LNode =
Devang Patel9aee3352011-09-08 22:59:09 +00007395 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7396 if (FrameIndexSDNode *FI =
7397 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7398 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7399 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00007400
Eli Friedman23d32432011-05-05 16:53:34 +00007401 // If this argument is live outside of the entry block, insert a copy from
7402 // wherever we got it to the vreg that other BB's will reference it as.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00007403 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
Eli Friedman23d32432011-05-05 16:53:34 +00007404 // If we can, though, try to skip creating an unnecessary vreg.
7405 // FIXME: This isn't very clean... it would be nice to make this more
Eli Friedman7f33d672011-05-10 21:50:58 +00007406 // general. It's also subtly incompatible with the hacks FastISel
7407 // uses with vregs.
Eli Friedman23d32432011-05-05 16:53:34 +00007408 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7409 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7410 FuncInfo->ValueMap[I] = Reg;
7411 continue;
7412 }
7413 }
Nick Lewycky8a8d4792011-12-02 22:16:29 +00007414 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
Eli Friedman23d32432011-05-05 16:53:34 +00007415 FuncInfo->InitializeRegForValue(I);
Dan Gohman2048b852009-11-23 18:04:58 +00007416 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007417 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007418 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00007419
Dan Gohman98ca4f22009-08-05 01:29:28 +00007420 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007421
7422 // Finally, if the target has anything special to do, allow it to do so.
7423 // FIXME: this should insert code into the DAG!
Dan Gohman64652652010-04-14 20:17:22 +00007424 EmitFunctionEntryCode();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007425}
7426
7427/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7428/// ensure constants are generated when needed. Remember the virtual registers
7429/// that need to be added to the Machine PHI nodes as input. We cannot just
7430/// directly add them, because expansion might result in multiple MBB's for one
7431/// BB. As such, the start of the BB might correspond to a different MBB than
7432/// the end.
7433///
7434void
Dan Gohmanf81eca02010-04-22 20:46:50 +00007435SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
Dan Gohman46510a72010-04-15 01:51:59 +00007436 const TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007437
7438 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7439
7440 // Check successor nodes' PHI nodes that expect a constant to be available
7441 // from this block.
7442 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
Dan Gohman46510a72010-04-15 01:51:59 +00007443 const BasicBlock *SuccBB = TI->getSuccessor(succ);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007444 if (!isa<PHINode>(SuccBB->begin())) continue;
Dan Gohmanf81eca02010-04-22 20:46:50 +00007445 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00007446
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007447 // If this terminator has multiple identical successors (common for
7448 // switches), only handle each succ once.
7449 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00007450
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007451 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007452
7453 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7454 // nodes and Machine PHI nodes, but the incoming operands have not been
7455 // emitted yet.
Dan Gohman46510a72010-04-15 01:51:59 +00007456 for (BasicBlock::const_iterator I = SuccBB->begin();
7457 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007458 // Ignore dead phi's.
7459 if (PN->use_empty()) continue;
7460
Rafael Espindola3fa82832011-05-13 15:18:06 +00007461 // Skip empty types
7462 if (PN->getType()->isEmptyTy())
7463 continue;
7464
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007465 unsigned Reg;
Dan Gohman46510a72010-04-15 01:51:59 +00007466 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007467
Dan Gohman46510a72010-04-15 01:51:59 +00007468 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohmanf81eca02010-04-22 20:46:50 +00007469 unsigned &RegOut = ConstantsOut[C];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007470 if (RegOut == 0) {
Dan Gohman89496d02010-07-02 00:10:16 +00007471 RegOut = FuncInfo.CreateRegs(C->getType());
Dan Gohmanf81eca02010-04-22 20:46:50 +00007472 CopyValueToVirtualRegister(C, RegOut);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007473 }
7474 Reg = RegOut;
7475 } else {
Dan Gohmanc25ad632010-07-01 01:33:21 +00007476 DenseMap<const Value *, unsigned>::iterator I =
7477 FuncInfo.ValueMap.find(PHIOp);
7478 if (I != FuncInfo.ValueMap.end())
7479 Reg = I->second;
7480 else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007481 assert(isa<AllocaInst>(PHIOp) &&
Dan Gohmanf81eca02010-04-22 20:46:50 +00007482 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007483 "Didn't codegen value into a register!??");
Dan Gohman89496d02010-07-02 00:10:16 +00007484 Reg = FuncInfo.CreateRegs(PHIOp->getType());
Dan Gohmanf81eca02010-04-22 20:46:50 +00007485 CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007486 }
7487 }
7488
7489 // Remember that this register needs to added to the machine PHI node as
7490 // the input for this MBB.
Owen Andersone50ed302009-08-10 22:56:29 +00007491 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingba54bca2013-06-19 21:36:55 +00007492 const TargetLowering *TLI = TM.getTargetLowering();
7493 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007494 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +00007495 EVT VT = ValueVTs[vti];
Bill Wendlingba54bca2013-06-19 21:36:55 +00007496 unsigned NumRegisters = TLI->getNumRegisters(*DAG.getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007497 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohmanf81eca02010-04-22 20:46:50 +00007498 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00007499 Reg += NumRegisters;
7500 }
7501 }
7502 }
Bill Wendlingba54bca2013-06-19 21:36:55 +00007503
Dan Gohmanf81eca02010-04-22 20:46:50 +00007504 ConstantsOut.clear();
Dan Gohman3df24e62008-09-03 23:12:08 +00007505}
Michael Gottesman657484f2013-08-20 07:00:16 +00007506
7507/// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7508/// is 0.
7509MachineBasicBlock *
7510SelectionDAGBuilder::StackProtectorDescriptor::
7511AddSuccessorMBB(const BasicBlock *BB,
7512 MachineBasicBlock *ParentMBB,
7513 MachineBasicBlock *SuccMBB) {
7514 // If SuccBB has not been created yet, create it.
7515 if (!SuccMBB) {
7516 MachineFunction *MF = ParentMBB->getParent();
7517 MachineFunction::iterator BBI = ParentMBB;
7518 SuccMBB = MF->CreateMachineBasicBlock(BB);
7519 MF->insert(++BBI, SuccMBB);
7520 }
7521 // Add it as a successor of ParentMBB.
7522 ParentMBB->addSuccessor(SuccMBB);
7523 return SuccMBB;
7524}