blob: 639ff82ffd3aa3b65800510983fcfaed5234fd42 [file] [log] [blame]
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001//===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
Dan Gohman575fad32008-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 Gohman1a6c47f2009-11-23 18:04:58 +000015#include "SelectionDAGBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "SDNodeDbgValue.h"
Dan Gohman575fad32008-09-03 16:12:24 +000017#include "llvm/ADT/BitVector.h"
David Blaikie0252265b2013-06-16 20:34:15 +000018#include "llvm/ADT/Optional.h"
Dan Gohman5eba3bc2008-09-04 20:49:27 +000019#include "llvm/ADT/SmallSet.h"
Dan Gohman575fad32008-09-03 16:12:24 +000020#include "llvm/Analysis/AliasAnalysis.h"
Jakub Staszaka9286e92013-01-10 22:13:13 +000021#include "llvm/Analysis/BranchProbabilityInfo.h"
Chris Lattner1a32ede2009-12-24 00:37:38 +000022#include "llvm/Analysis/ConstantFolding.h"
Nadav Rotem7c277da2012-09-06 09:17:37 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthed0881b2012-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 Trick153ebe62013-10-31 22:11:56 +000036#include "llvm/CodeGen/StackMaps.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/CallingConv.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000040#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#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 Carruthed0881b2012-12-03 16:50:05 +000050#include "llvm/Support/CommandLine.h"
51#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000053#include "llvm/Support/MathExtras.h"
54#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov2f931282011-01-10 12:39:04 +000055#include "llvm/Target/TargetFrameLowering.h"
Dan Gohman575fad32008-09-03 16:12:24 +000056#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesenb842d522009-02-05 01:49:45 +000057#include "llvm/Target/TargetIntrinsicInfo.h"
Owen Andersonbb15fec2011-12-08 22:15:21 +000058#include "llvm/Target/TargetLibraryInfo.h"
Dan Gohman575fad32008-09-03 16:12:24 +000059#include "llvm/Target/TargetLowering.h"
Dan Gohman575fad32008-09-03 16:12:24 +000060#include "llvm/Target/TargetOptions.h"
Richard Sandiford564681c2013-08-12 10:28:10 +000061#include "llvm/Target/TargetSelectionDAGInfo.h"
Dan Gohman575fad32008-09-03 16:12:24 +000062#include <algorithm>
63using namespace llvm;
64
Dale Johannesenf2a52bb2008-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 Trick116efac2010-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 Trickcf7fefb2010-11-20 07:26:51 +000081// the safe approach, and will be especially important with global DAGs.
Andrew Trick116efac2010-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 Trickcf7fefb2010-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 Trick710d5da2011-03-11 17:46:59 +000090static const unsigned MaxParallelChains = 64;
Andrew Trick116efac2010-11-12 17:50:46 +000091
Andrew Trickef9de2a2013-05-25 02:42:55 +000092static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner05bcb482010-08-24 23:20:40 +000093 const SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +000094 MVT PartVT, EVT ValueVT, const Value *V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +000095
Dan Gohman575fad32008-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 Trickef9de2a2013-05-25 02:42:55 +0000101static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
Dale Johannesendb7c5f62009-01-31 02:22:37 +0000102 const SDValue *Parts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000103 unsigned NumParts, MVT PartVT, EVT ValueVT,
Bill Wendling81406f62012-09-26 04:04:19 +0000104 const Value *V,
Duncan Sandsba21b7d2009-01-28 14:42:54 +0000105 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000106 if (ValueVT.isVector())
Bill Wendling81406f62012-09-26 04:04:19 +0000107 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
108 PartVT, ValueVT, V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000109
Dan Gohman575fad32008-09-03 16:12:24 +0000110 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohman91febd12009-01-15 16:58:17 +0000111 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +0000112 SDValue Val = Parts[0];
113
114 if (NumParts > 1) {
115 // Assemble the value from multiple parts.
Chris Lattner05bcb482010-08-24 23:20:40 +0000116 if (ValueVT.isInteger()) {
Dan Gohman575fad32008-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 Anderson53aa7a92009-08-10 22:56:29 +0000124 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson117c9e82009-08-12 00:36:31 +0000125 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohman575fad32008-09-03 16:12:24 +0000126 SDValue Lo, Hi;
127
Owen Anderson117c9e82009-08-12 00:36:31 +0000128 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sands17e678b2008-10-29 14:22:20 +0000129
Dan Gohman575fad32008-09-03 16:12:24 +0000130 if (RoundParts > 2) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000131 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
Bill Wendling81406f62012-09-26 04:04:19 +0000132 PartVT, HalfVT, V);
Chris Lattner05bcb482010-08-24 23:20:40 +0000133 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
Bill Wendling81406f62012-09-26 04:04:19 +0000134 RoundParts / 2, PartVT, HalfVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000135 } else {
Wesley Peck527da1b2010-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 Gohman575fad32008-09-03 16:12:24 +0000138 }
Bill Wendling919b7aa2009-12-22 02:10:19 +0000139
Dan Gohman575fad32008-09-03 16:12:24 +0000140 if (TLI.isBigEndian())
141 std::swap(Lo, Hi);
Bill Wendling919b7aa2009-12-22 02:10:19 +0000142
Chris Lattner05bcb482010-08-24 23:20:40 +0000143 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
Dan Gohman575fad32008-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 Anderson117c9e82009-08-12 00:36:31 +0000148 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Chris Lattner05bcb482010-08-24 23:20:40 +0000149 Hi = getCopyFromParts(DAG, DL,
Bill Wendling81406f62012-09-26 04:04:19 +0000150 Parts + RoundParts, OddParts, PartVT, OddVT, V);
Dan Gohman575fad32008-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 Anderson117c9e82009-08-12 00:36:31 +0000156 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Chris Lattner05bcb482010-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 Gohman575fad32008-09-03 16:12:24 +0000159 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands41826032009-01-31 15:50:11 +0000160 TLI.getPointerTy()));
Chris Lattner05bcb482010-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 Gohman575fad32008-09-03 16:12:24 +0000163 }
Eli Friedman9030c352009-05-20 06:02:09 +0000164 } else if (PartVT.isFloatingPoint()) {
165 // FP split into multiple FP parts (for ppcf128)
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000166 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
Eli Friedman9030c352009-05-20 06:02:09 +0000167 "Unexpected split");
168 SDValue Lo, Hi;
Wesley Peck527da1b2010-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 Friedman9030c352009-05-20 06:02:09 +0000171 if (TLI.isBigEndian())
172 std::swap(Lo, Hi);
Chris Lattner05bcb482010-08-24 23:20:40 +0000173 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
Eli Friedman9030c352009-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 Anderson117c9e82009-08-12 00:36:31 +0000178 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Bill Wendling81406f62012-09-26 04:04:19 +0000179 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000180 }
181 }
182
183 // There is now one part, held in Val. Correct it to match ValueVT.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000184 EVT PartEVT = Val.getValueType();
Dan Gohman575fad32008-09-03 16:12:24 +0000185
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000186 if (PartEVT == ValueVT)
Dan Gohman575fad32008-09-03 16:12:24 +0000187 return Val;
188
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000189 if (PartEVT.isInteger() && ValueVT.isInteger()) {
190 if (ValueVT.bitsLT(PartEVT)) {
Dan Gohman575fad32008-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 Hagglund00e7a112012-12-19 12:33:30 +0000195 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
Dan Gohman575fad32008-09-03 16:12:24 +0000196 DAG.getValueType(ValueVT));
Chris Lattner05bcb482010-08-24 23:20:40 +0000197 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000198 }
Chris Lattner05bcb482010-08-24 23:20:40 +0000199 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000200 }
201
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000202 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Chris Lattner05bcb482010-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 Coopere3d305a2012-01-17 01:54:07 +0000206 DAG.getTargetConstant(1, TLI.getPointerTy()));
Bill Wendling919b7aa2009-12-22 02:10:19 +0000207
Chris Lattner05bcb482010-08-24 23:20:40 +0000208 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000209 }
210
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000211 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
Wesley Peck527da1b2010-11-23 03:31:01 +0000212 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000213
Torok Edwinfbcc6632009-07-14 16:55:14 +0000214 llvm_unreachable("Unknown mismatch!");
Dan Gohman575fad32008-09-03 16:12:24 +0000215}
216
Bill Wendling81406f62012-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 Trickef9de2a2013-05-25 02:42:55 +0000222static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner05bcb482010-08-24 23:20:40 +0000223 const SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000224 MVT PartVT, EVT ValueVT, const Value *V) {
Chris Lattner05bcb482010-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. Spencerd3ea25e2010-10-16 08:25:21 +0000229
Chris Lattner05bcb482010-08-24 23:20:40 +0000230 // Handle a multi-element vector.
231 if (NumParts > 1) {
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000232 EVT IntermediateVT;
233 MVT RegisterVT;
Chris Lattner05bcb482010-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 Hagglund00e7a112012-12-19 12:33:30 +0000240 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000241 assert(RegisterVT == Parts[0].getSimpleValueType() &&
Chris Lattner05bcb482010-08-24 23:20:40 +0000242 "Part type doesn't match part!");
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000243
Chris Lattner05bcb482010-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 Wendling81406f62012-09-26 04:04:19 +0000251 PartVT, IntermediateVT, V);
Chris Lattner05bcb482010-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 Wendling81406f62012-09-26 04:04:19 +0000260 PartVT, IntermediateVT, V);
Chris Lattner05bcb482010-08-24 23:20:40 +0000261 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000262
Chris Lattner05bcb482010-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. Spencerd3ea25e2010-10-16 08:25:21 +0000269
Chris Lattner05bcb482010-08-24 23:20:40 +0000270 // There is now one part, held in Val. Correct it to match ValueVT.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000271 EVT PartEVT = Val.getValueType();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000272
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000273 if (PartEVT == ValueVT)
Chris Lattner05bcb482010-08-24 23:20:40 +0000274 return Val;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000275
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000276 if (PartEVT.isVector()) {
Chris Lattner75ff0532010-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 Hagglund00e7a112012-12-19 12:33:30 +0000281 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
282 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
Chris Lattner75ff0532010-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 Stellardd42c5942013-08-05 22:22:01 +0000285 DAG.getConstant(0, TLI.getVectorIdxTy()));
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000286 }
287
Chris Lattner75ff0532010-08-25 22:49:25 +0000288 // Vector/Vector bitcast.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000289 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000290 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
291
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000292 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000293 "Cannot handle this kind of promotion");
294 // Promoted vector extract
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000295 bool Smaller = ValueVT.bitsLE(PartEVT);
Nadav Rotem083837e2011-06-12 14:49:38 +0000296 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
297 DL, ValueVT, Val);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000298
Chris Lattner75ff0532010-08-25 22:49:25 +0000299 }
Eric Christopher0713a9d2011-06-08 23:55:35 +0000300
Eric Christopher690030c2011-06-01 19:55:10 +0000301 // Trivial bitcast if the types are the same size and the destination
302 // vector type is legal.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000303 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
Eric Christopher690030c2011-06-01 19:55:10 +0000304 TLI.isTypeLegal(ValueVT))
305 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000306
Nadav Rotem083837e2011-06-12 14:49:38 +0000307 // Handle cases such as i8 -> <1 x i1>
Bill Wendling81406f62012-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 Rosier8e4824f2013-05-01 19:49:26 +0000319 return DAG.getUNDEF(ValueVT);
Bill Wendling81406f62012-09-26 04:04:19 +0000320 }
Nadav Rotem083837e2011-06-12 14:49:38 +0000321
322 if (ValueVT.getVectorNumElements() == 1 &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000323 ValueVT.getVectorElementType() != PartEVT) {
324 bool Smaller = ValueVT.bitsLE(PartEVT);
Nadav Rotem083837e2011-06-12 14:49:38 +0000325 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
326 DL, ValueVT.getScalarType(), Val);
327 }
328
Chris Lattner05bcb482010-08-24 23:20:40 +0000329 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
330}
331
Andrew Trickef9de2a2013-05-25 02:42:55 +0000332static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
Chris Lattner96a77eb2010-08-24 23:10:06 +0000333 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000334 MVT PartVT, const Value *V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000335
Dan Gohman575fad32008-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 Trickef9de2a2013-05-25 02:42:55 +0000339static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
Bill Wendling919b7aa2009-12-22 02:10:19 +0000340 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000341 MVT PartVT, const Value *V,
Dan Gohman575fad32008-09-03 16:12:24 +0000342 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000343 EVT ValueVT = Val.getValueType();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000344
Chris Lattner96a77eb2010-08-24 23:10:06 +0000345 // Handle the vector case separately.
346 if (ValueVT.isVector())
Bill Wendling5def8912012-09-26 06:16:18 +0000347 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000348
Chris Lattner96a77eb2010-08-24 23:10:06 +0000349 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +0000350 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen7d12ea02009-02-25 22:39:13 +0000351 unsigned OrigNumParts = NumParts;
Dan Gohman575fad32008-09-03 16:12:24 +0000352 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
353
Chris Lattner96a77eb2010-08-24 23:10:06 +0000354 if (NumParts == 0)
Dan Gohman575fad32008-09-03 16:12:24 +0000355 return;
356
Chris Lattner96a77eb2010-08-24 23:10:06 +0000357 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000358 EVT PartEVT = PartVT;
359 if (PartEVT == ValueVT) {
Chris Lattner96a77eb2010-08-24 23:10:06 +0000360 assert(NumParts == 1 && "No-op copy with multiple parts!");
Dan Gohman575fad32008-09-03 16:12:24 +0000361 Parts[0] = Val;
362 return;
363 }
364
Chris Lattner96a77eb2010-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 Wendling38b31612012-02-23 23:25:25 +0000371 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
372 ValueVT.isInteger() &&
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000373 "Unknown mismatch!");
Chris Lattner96a77eb2010-08-24 23:10:06 +0000374 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
375 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
Bill Wendling38b31612012-02-23 23:25:25 +0000376 if (PartVT == MVT::x86mmx)
377 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000378 }
379 } else if (PartBits == ValueVT.getSizeInBits()) {
380 // Different types of the same size.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000381 assert(NumParts == 1 && PartEVT != ValueVT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000382 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-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 Wendling38b31612012-02-23 23:25:25 +0000385 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
386 ValueVT.isInteger() &&
Chris Lattner96a77eb2010-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 Wendling38b31612012-02-23 23:25:25 +0000390 if (PartVT == MVT::x86mmx)
391 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-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 Hagglund00e7a112012-12-19 12:33:30 +0000400 if (PartEVT != ValueVT) {
Bill Wendling5def8912012-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 Lattner96a77eb2010-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 Wendling5def8912012-09-26 06:16:18 +0000427 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
Chris Lattner96a77eb2010-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 Peck527da1b2010-11-23 03:31:01 +0000440 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
Chris Lattner96a77eb2010-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 Peck527da1b2010-11-23 03:31:01 +0000458 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
459 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
Chris Lattner96a77eb2010-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 Trickef9de2a2013-05-25 02:42:55 +0000471static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner96a77eb2010-08-24 23:10:06 +0000472 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000473 MVT PartVT, const Value *V) {
Chris Lattner96a77eb2010-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. Spencerd3ea25e2010-10-16 08:25:21 +0000477
Chris Lattner96a77eb2010-08-24 23:10:06 +0000478 if (NumParts == 1) {
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000479 EVT PartEVT = PartVT;
480 if (PartEVT == ValueVT) {
Chris Lattner75ff0532010-08-25 22:49:25 +0000481 // Nothing to do.
482 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
483 // Bitconvert vector->vector case.
Wesley Peck527da1b2010-11-23 03:31:01 +0000484 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner75ff0532010-08-25 22:49:25 +0000485 } else if (PartVT.isVector() &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000486 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
487 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
Chris Lattner75ff0532010-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 Stellardd42c5942013-08-05 22:22:01 +0000494 ElementVT, Val, DAG.getConstant(i,
495 TLI.getVectorIdxTy())));
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000496
Chris Lattner75ff0532010-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. Spencerd3ea25e2010-10-16 08:25:21 +0000504
Chris Lattner75ff0532010-08-25 22:49:25 +0000505 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
506 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000507 } else if (PartVT.isVector() &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000508 PartEVT.getVectorElementType().bitsGE(
Nadav Rotem083837e2011-06-12 14:49:38 +0000509 ValueVT.getVectorElementType()) &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000510 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000511
512 // Promoted vector extract
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000513 bool Smaller = PartEVT.bitsLE(ValueVT);
Nadav Rotem36896bf2011-06-19 08:49:38 +0000514 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
515 DL, PartVT, Val);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000516 } else{
Chris Lattner75ff0532010-08-25 22:49:25 +0000517 // Vector -> scalar conversion.
Nadav Rotem083837e2011-06-12 14:49:38 +0000518 assert(ValueVT.getVectorNumElements() == 1 &&
Chris Lattner75ff0532010-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 Stellardd42c5942013-08-05 22:22:01 +0000521 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
Nadav Rotem083837e2011-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 Lattner96a77eb2010-08-24 23:10:06 +0000526 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000527
Chris Lattner96a77eb2010-08-24 23:10:06 +0000528 Parts[0] = Val;
529 return;
530 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000531
Dan Gohman575fad32008-09-03 16:12:24 +0000532 // Handle a multi-element vector.
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000533 EVT IntermediateVT;
534 MVT RegisterVT;
Dan Gohman575fad32008-09-03 16:12:24 +0000535 unsigned NumIntermediates;
Owen Anderson117c9e82009-08-12 00:36:31 +0000536 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
Devang Patel977057f2010-08-26 20:32:32 +0000537 IntermediateVT,
538 NumIntermediates, RegisterVT);
Dan Gohman575fad32008-09-03 16:12:24 +0000539 unsigned NumElements = ValueVT.getVectorNumElements();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000540
Dan Gohman575fad32008-09-03 16:12:24 +0000541 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
542 NumParts = NumRegs; // Silence a compiler warning.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000543 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000544
Dan Gohman575fad32008-09-03 16:12:24 +0000545 // Split the vector into intermediate operands.
546 SmallVector<SDValue, 8> Ops(NumIntermediates);
Bill Wendling919b7aa2009-12-22 02:10:19 +0000547 for (unsigned i = 0; i != NumIntermediates; ++i) {
Dan Gohman575fad32008-09-03 16:12:24 +0000548 if (IntermediateVT.isVector())
Chris Lattner96a77eb2010-08-24 23:10:06 +0000549 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
Dan Gohman575fad32008-09-03 16:12:24 +0000550 IntermediateVT, Val,
Tom Stellardd42c5942013-08-05 22:22:01 +0000551 DAG.getConstant(i * (NumElements / NumIntermediates),
552 TLI.getVectorIdxTy()));
Dan Gohman575fad32008-09-03 16:12:24 +0000553 else
Chris Lattner96a77eb2010-08-24 23:10:06 +0000554 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellardd42c5942013-08-05 22:22:01 +0000555 IntermediateVT, Val,
556 DAG.getConstant(i, TLI.getVectorIdxTy()));
Bill Wendling919b7aa2009-12-22 02:10:19 +0000557 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000558
Dan Gohman575fad32008-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 Wendling5def8912012-09-26 06:16:18 +0000564 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
Dan Gohman575fad32008-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 Wendling5def8912012-09-26 06:16:18 +0000572 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000573 }
574}
575
Dan Gohman4db93c92010-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 Hagglund4e0f8282012-12-19 12:23:01 +0000601 SmallVector<MVT, 4> RegVTs;
Dan Gohman4db93c92010-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 Hagglund4e0f8282012-12-19 12:23:01 +0000612 MVT regvt, EVT valuevt)
Dan Gohman4db93c92010-05-29 17:53:24 +0000613 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
614
Dan Gohman4db93c92010-05-29 17:53:24 +0000615 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
Chris Lattner229907c2011-07-18 04:54:35 +0000616 unsigned Reg, Type *Ty) {
Dan Gohman4db93c92010-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 Hagglundbad545c2012-12-19 11:48:16 +0000622 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
Dan Gohman4db93c92010-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
Dan Gohman4db93c92010-05-29 17:53:24 +0000630 /// append - Add the specified values to this one.
631 void append(const RegsForValue &RHS) {
632 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
633 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
634 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
635 }
636
637 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
638 /// this value and returns the result as a ValueVTs value. This uses
639 /// Chain/Flag as the input and updates them for the output Chain/Flag.
640 /// If the Flag pointer is NULL, no flag is used.
641 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000642 SDLoc dl,
Bill Wendling81406f62012-09-26 04:04:19 +0000643 SDValue &Chain, SDValue *Flag,
644 const Value *V = 0) const;
Dan Gohman4db93c92010-05-29 17:53:24 +0000645
646 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
647 /// specified value into the registers specified by this object. This uses
648 /// Chain/Flag as the input and updates them for the output Chain/Flag.
649 /// If the Flag pointer is NULL, no flag is used.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000650 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
Bill Wendling5def8912012-09-26 06:16:18 +0000651 SDValue &Chain, SDValue *Flag, const Value *V) const;
Dan Gohman4db93c92010-05-29 17:53:24 +0000652
653 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
654 /// operand list. This adds the code marker, matching input operand index
655 /// (if applicable), and includes the number of values added into it.
656 void AddInlineAsmOperands(unsigned Kind,
657 bool HasMatching, unsigned MatchingIdx,
658 SelectionDAG &DAG,
659 std::vector<SDValue> &Ops) const;
660 };
661}
662
663/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
664/// this value and returns the result as a ValueVT value. This uses
665/// Chain/Flag as the input and updates them for the output Chain/Flag.
666/// If the Flag pointer is NULL, no flag is used.
667SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
668 FunctionLoweringInfo &FuncInfo,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000669 SDLoc dl,
Bill Wendling81406f62012-09-26 04:04:19 +0000670 SDValue &Chain, SDValue *Flag,
671 const Value *V) const {
Dan Gohman2810bac2010-07-26 18:15:41 +0000672 // A Value with type {} or [0 x %t] needs no registers.
673 if (ValueVTs.empty())
674 return SDValue();
675
Dan Gohman4db93c92010-05-29 17:53:24 +0000676 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
677
678 // Assemble the legal parts into the final values.
679 SmallVector<SDValue, 4> Values(ValueVTs.size());
680 SmallVector<SDValue, 8> Parts;
681 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
682 // Copy the legal parts from the registers.
683 EVT ValueVT = ValueVTs[Value];
684 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000685 MVT RegisterVT = RegVTs[Value];
Dan Gohman4db93c92010-05-29 17:53:24 +0000686
687 Parts.resize(NumRegs);
688 for (unsigned i = 0; i != NumRegs; ++i) {
689 SDValue P;
690 if (Flag == 0) {
691 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
692 } else {
693 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
694 *Flag = P.getValue(2);
695 }
696
697 Chain = P.getValue(1);
Chris Lattnercb404362010-12-13 01:11:17 +0000698 Parts[i] = P;
Dan Gohman4db93c92010-05-29 17:53:24 +0000699
700 // If the source register was virtual and if we know something about it,
701 // add an assert node.
Chris Lattnercb404362010-12-13 01:11:17 +0000702 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
Cameron Zwarich64706472011-02-24 10:00:08 +0000703 !RegisterVT.isInteger() || RegisterVT.isVector())
Chris Lattnercb404362010-12-13 01:11:17 +0000704 continue;
Cameron Zwarich64706472011-02-24 10:00:08 +0000705
706 const FunctionLoweringInfo::LiveOutInfo *LOI =
707 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
708 if (!LOI)
709 continue;
Dan Gohman4db93c92010-05-29 17:53:24 +0000710
Chris Lattnercb404362010-12-13 01:11:17 +0000711 unsigned RegSize = RegisterVT.getSizeInBits();
Cameron Zwarich64706472011-02-24 10:00:08 +0000712 unsigned NumSignBits = LOI->NumSignBits;
713 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
Dan Gohman4db93c92010-05-29 17:53:24 +0000714
Quentin Colombetb51a6862013-06-18 20:14:39 +0000715 if (NumZeroBits == RegSize) {
716 // The current value is a zero.
717 // Explicitly express that as it would be easier for
718 // optimizations to kick in.
719 Parts[i] = DAG.getConstant(0, RegisterVT);
720 continue;
721 }
722
Chris Lattnercb404362010-12-13 01:11:17 +0000723 // FIXME: We capture more information than the dag can represent. For
724 // now, just use the tightest assertzext/assertsext possible.
725 bool isSExt = true;
726 EVT FromVT(MVT::Other);
727 if (NumSignBits == RegSize)
728 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
729 else if (NumZeroBits >= RegSize-1)
730 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
731 else if (NumSignBits > RegSize-8)
732 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
733 else if (NumZeroBits >= RegSize-8)
734 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
735 else if (NumSignBits > RegSize-16)
736 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
737 else if (NumZeroBits >= RegSize-16)
738 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
739 else if (NumSignBits > RegSize-32)
740 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
741 else if (NumZeroBits >= RegSize-32)
742 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
743 else
744 continue;
Dan Gohman4db93c92010-05-29 17:53:24 +0000745
Chris Lattnercb404362010-12-13 01:11:17 +0000746 // Add an assertion node.
747 assert(FromVT != MVT::Other);
748 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
749 RegisterVT, P, DAG.getValueType(FromVT));
Dan Gohman4db93c92010-05-29 17:53:24 +0000750 }
751
752 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Bill Wendling81406f62012-09-26 04:04:19 +0000753 NumRegs, RegisterVT, ValueVT, V);
Dan Gohman4db93c92010-05-29 17:53:24 +0000754 Part += NumRegs;
755 Parts.clear();
756 }
757
758 return DAG.getNode(ISD::MERGE_VALUES, dl,
759 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
760 &Values[0], ValueVTs.size());
761}
762
763/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
764/// specified value into the registers specified by this object. This uses
765/// Chain/Flag as the input and updates them for the output Chain/Flag.
766/// If the Flag pointer is NULL, no flag is used.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000767void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
Bill Wendling5def8912012-09-26 06:16:18 +0000768 SDValue &Chain, SDValue *Flag,
769 const Value *V) const {
Dan Gohman4db93c92010-05-29 17:53:24 +0000770 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
771
772 // Get the list of the values's legal parts.
773 unsigned NumRegs = Regs.size();
774 SmallVector<SDValue, 8> Parts(NumRegs);
775 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
776 EVT ValueVT = ValueVTs[Value];
777 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000778 MVT RegisterVT = RegVTs[Value];
Evan Cheng9ec512d2012-12-06 19:13:27 +0000779 ISD::NodeType ExtendKind =
780 TLI.isZExtFree(Val, RegisterVT)? ISD::ZERO_EXTEND: ISD::ANY_EXTEND;
Dan Gohman4db93c92010-05-29 17:53:24 +0000781
Chris Lattner05bcb482010-08-24 23:20:40 +0000782 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Evan Cheng9ec512d2012-12-06 19:13:27 +0000783 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
Dan Gohman4db93c92010-05-29 17:53:24 +0000784 Part += NumParts;
785 }
786
787 // Copy the parts into the registers.
788 SmallVector<SDValue, 8> Chains(NumRegs);
789 for (unsigned i = 0; i != NumRegs; ++i) {
790 SDValue Part;
791 if (Flag == 0) {
792 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
793 } else {
794 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
795 *Flag = Part.getValue(1);
796 }
797
798 Chains[i] = Part.getValue(0);
799 }
800
801 if (NumRegs == 1 || Flag)
802 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
803 // flagged to it. That is the CopyToReg nodes and the user are considered
804 // a single scheduling unit. If we create a TokenFactor and return it as
805 // chain, then the TokenFactor is both a predecessor (operand) of the
806 // user as well as a successor (the TF operands are flagged to the user).
807 // c1, f1 = CopyToReg
808 // c2, f2 = CopyToReg
809 // c3 = TokenFactor c1, c2
810 // ...
811 // = op c3, ..., f2
812 Chain = Chains[NumRegs-1];
813 else
814 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
815}
816
817/// AddInlineAsmOperands - Add this value to the specified inlineasm node
818/// operand list. This adds the code marker and includes the number of
819/// values added into it.
820void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
821 unsigned MatchingIdx,
822 SelectionDAG &DAG,
823 std::vector<SDValue> &Ops) const {
824 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
825
826 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
827 if (HasMatching)
828 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
Jakob Stoklund Olesen24abd9d2011-10-12 23:37:29 +0000829 else if (!Regs.empty() &&
830 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
831 // Put the register class of the virtual registers in the flag word. That
832 // way, later passes can recompute register class constraints for inline
833 // assembly as well as normal instructions.
834 // Don't do this for tied operands that can use the regclass information
835 // from the def.
836 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
837 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
838 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
839 }
840
Dan Gohman4db93c92010-05-29 17:53:24 +0000841 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
842 Ops.push_back(Res);
843
Reid Kleckneree088972013-12-10 18:27:32 +0000844 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
Dan Gohman4db93c92010-05-29 17:53:24 +0000845 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
846 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000847 MVT RegisterVT = RegVTs[Value];
Dan Gohman4db93c92010-05-29 17:53:24 +0000848 for (unsigned i = 0; i != NumRegs; ++i) {
849 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Reid Kleckneree088972013-12-10 18:27:32 +0000850 unsigned TheReg = Regs[Reg++];
851 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
852
Reid Kleckneree088972013-12-10 18:27:32 +0000853 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000854 // If we clobbered the stack pointer, MFI should know about it.
855 assert(DAG.getMachineFunction().getFrameInfo()->
856 hasInlineAsmWithSPAdjust());
Reid Kleckneree088972013-12-10 18:27:32 +0000857 }
Dan Gohman4db93c92010-05-29 17:53:24 +0000858 }
859 }
860}
Dan Gohman575fad32008-09-03 16:12:24 +0000861
Owen Andersonbb15fec2011-12-08 22:15:21 +0000862void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
863 const TargetLibraryInfo *li) {
Dan Gohman575fad32008-09-03 16:12:24 +0000864 AA = &aa;
865 GFI = gfi;
Owen Andersonbb15fec2011-12-08 22:15:21 +0000866 LibInfo = li;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000867 DL = DAG.getTarget().getDataLayout();
Richard Smith3fb20472012-08-22 00:42:39 +0000868 Context = DAG.getContext();
Bill Wendling2730a002011-10-15 01:00:26 +0000869 LPadToCallSiteMap.clear();
Dan Gohman575fad32008-09-03 16:12:24 +0000870}
871
Dan Gohmanf5cca352010-04-14 18:24:06 +0000872/// clear - Clear out the current SelectionDAG and the associated
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000873/// state and prepare this SelectionDAGBuilder object to be used
Dan Gohman575fad32008-09-03 16:12:24 +0000874/// for a new block. This doesn't clear out information about
875/// additional blocks that are needed to complete switch lowering
876/// or PHI node updating; that information is cleared out as it is
877/// consumed.
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000878void SelectionDAGBuilder::clear() {
Dan Gohman575fad32008-09-03 16:12:24 +0000879 NodeMap.clear();
Devang Patelb0c76392010-06-01 19:59:01 +0000880 UnusedArgNodeMap.clear();
Dan Gohman575fad32008-09-03 16:12:24 +0000881 PendingLoads.clear();
882 PendingExports.clear();
Andrew Trick175143b2013-05-25 02:20:36 +0000883 CurInst = NULL;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +0000884 HasTailCall = false;
Nico Rieckb5262d62014-01-12 14:09:17 +0000885 SDNodeOrder = LowestSDNodeOrder;
Dan Gohman575fad32008-09-03 16:12:24 +0000886}
887
Devang Patel799288382011-05-23 17:44:13 +0000888/// clearDanglingDebugInfo - Clear the dangling debug information
Benjamin Kramerbde91762012-06-02 10:20:22 +0000889/// map. This function is separated from the clear so that debug
Devang Patel799288382011-05-23 17:44:13 +0000890/// information that is dangling in a basic block can be properly
891/// resolved in a different basic block. This allows the
892/// SelectionDAG to resolve dangling debug information attached
893/// to PHI nodes.
894void SelectionDAGBuilder::clearDanglingDebugInfo() {
895 DanglingDebugInfoMap.clear();
896}
897
Dan Gohman575fad32008-09-03 16:12:24 +0000898/// getRoot - Return the current virtual root of the Selection DAG,
899/// flushing any PendingLoad items. This must be done before emitting
900/// a store or any other node that may need to be ordered after any
901/// prior load instructions.
902///
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000903SDValue SelectionDAGBuilder::getRoot() {
Dan Gohman575fad32008-09-03 16:12:24 +0000904 if (PendingLoads.empty())
905 return DAG.getRoot();
906
907 if (PendingLoads.size() == 1) {
908 SDValue Root = PendingLoads[0];
909 DAG.setRoot(Root);
910 PendingLoads.clear();
911 return Root;
912 }
913
914 // Otherwise, we have to make a token factor node.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000915 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Dan Gohman575fad32008-09-03 16:12:24 +0000916 &PendingLoads[0], PendingLoads.size());
917 PendingLoads.clear();
918 DAG.setRoot(Root);
919 return Root;
920}
921
922/// getControlRoot - Similar to getRoot, but instead of flushing all the
923/// PendingLoad items, flush all the PendingExports items. It is necessary
924/// to do this before emitting a terminator instruction.
925///
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000926SDValue SelectionDAGBuilder::getControlRoot() {
Dan Gohman575fad32008-09-03 16:12:24 +0000927 SDValue Root = DAG.getRoot();
928
929 if (PendingExports.empty())
930 return Root;
931
932 // Turn all of the CopyToReg chains into one factored node.
933 if (Root.getOpcode() != ISD::EntryToken) {
934 unsigned i = 0, e = PendingExports.size();
935 for (; i != e; ++i) {
936 assert(PendingExports[i].getNode()->getNumOperands() > 1);
937 if (PendingExports[i].getNode()->getOperand(0) == Root)
938 break; // Don't add the root if we already indirectly depend on it.
939 }
940
941 if (i == e)
942 PendingExports.push_back(Root);
943 }
944
Andrew Trickef9de2a2013-05-25 02:42:55 +0000945 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Dan Gohman575fad32008-09-03 16:12:24 +0000946 &PendingExports[0],
947 PendingExports.size());
948 PendingExports.clear();
949 DAG.setRoot(Root);
950 return Root;
951}
952
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000953void SelectionDAGBuilder::visit(const Instruction &I) {
Dan Gohman5b43aa02010-04-22 20:55:53 +0000954 // Set up outgoing PHI node register values before emitting the terminator.
955 if (isa<TerminatorInst>(&I))
956 HandlePHINodesInSuccessorBlocks(I.getParent());
957
Andrew Tricke2431c62013-05-25 03:08:10 +0000958 ++SDNodeOrder;
959
Andrew Trick175143b2013-05-25 02:20:36 +0000960 CurInst = &I;
Dan Gohmane450d742010-04-20 00:48:35 +0000961
Dan Gohman575fad32008-09-03 16:12:24 +0000962 visit(I.getOpcode(), I);
Dan Gohmane450d742010-04-20 00:48:35 +0000963
Dan Gohman950fe782010-04-20 15:03:56 +0000964 if (!isa<TerminatorInst>(&I) && !HasTailCall)
965 CopyToExportRegsIfNeeded(&I);
966
Andrew Trick175143b2013-05-25 02:20:36 +0000967 CurInst = NULL;
Dan Gohman575fad32008-09-03 16:12:24 +0000968}
969
Dan Gohmanf41ad472010-04-20 15:00:41 +0000970void SelectionDAGBuilder::visitPHI(const PHINode &) {
971 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
972}
973
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000974void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +0000975 // Note: this doesn't use InstVisitor, because it has to work with
976 // ConstantExpr's in addition to instructions.
977 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000978 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohman575fad32008-09-03 16:12:24 +0000979 // Build the switch statement using the Instruction.def file.
980#define HANDLE_INST(NUM, OPCODE, CLASS) \
Galina Kistanovaaaf97352012-07-19 04:50:12 +0000981 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000982#include "llvm/IR/Instruction.def"
Dan Gohman575fad32008-09-03 16:12:24 +0000983 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +0000984}
Dan Gohman575fad32008-09-03 16:12:24 +0000985
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000986// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
987// generate the debug data structures now that we've seen its definition.
988void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
989 SDValue Val) {
990 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
Devang Patelb12ff592010-08-26 23:35:15 +0000991 if (DDI.getDI()) {
992 const DbgValueInst *DI = DDI.getDI();
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000993 DebugLoc dl = DDI.getdl();
994 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
Devang Patelb12ff592010-08-26 23:35:15 +0000995 MDNode *Variable = DI->getVariable();
996 uint64_t Offset = DI->getOffset();
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000997 SDDbgValue *SDV;
998 if (Val.getNode()) {
Devang Patel3f53d6e2010-08-25 20:39:26 +0000999 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001000 SDV = DAG.getDbgValue(Variable, Val.getNode(),
1001 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
1002 DAG.AddDbgValue(SDV, Val.getNode(), false);
1003 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00001004 } else
Adrian Prantl0d1e5592013-05-22 18:02:19 +00001005 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001006 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1007 }
1008}
1009
Nick Lewyckyf40df1d2011-09-30 22:19:53 +00001010/// getValue - Return an SDValue for the given Value.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001011SDValue SelectionDAGBuilder::getValue(const Value *V) {
Dan Gohmand4322232010-07-01 01:59:43 +00001012 // If we already have an SDValue for this value, use it. It's important
1013 // to do this first, so that we don't create a CopyFromReg if we already
1014 // have a regular SDValue.
Dan Gohman575fad32008-09-03 16:12:24 +00001015 SDValue &N = NodeMap[V];
1016 if (N.getNode()) return N;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001017
Dan Gohmand4322232010-07-01 01:59:43 +00001018 // If there's a virtual register allocated and initialized for this
1019 // value, use it.
1020 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1021 if (It != FuncInfo.ValueMap.end()) {
1022 unsigned InReg = It->second;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001023 RegsForValue RFV(*DAG.getContext(), *TM.getTargetLowering(),
1024 InReg, V->getType());
Dan Gohmand4322232010-07-01 01:59:43 +00001025 SDValue Chain = DAG.getEntryNode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001026 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
Devang Patel70f8e592011-01-25 18:09:58 +00001027 resolveDanglingDebugInfo(V, N);
1028 return N;
Dan Gohmand4322232010-07-01 01:59:43 +00001029 }
1030
1031 // Otherwise create a new SDValue and remember it.
1032 SDValue Val = getValueImpl(V);
1033 NodeMap[V] = Val;
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001034 resolveDanglingDebugInfo(V, Val);
Dan Gohmand4322232010-07-01 01:59:43 +00001035 return Val;
1036}
1037
1038/// getNonRegisterValue - Return an SDValue for the given Value, but
1039/// don't look in FuncInfo.ValueMap for a virtual register.
1040SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1041 // If we already have an SDValue for this value, use it.
1042 SDValue &N = NodeMap[V];
1043 if (N.getNode()) return N;
1044
1045 // Otherwise create a new SDValue and remember it.
1046 SDValue Val = getValueImpl(V);
1047 NodeMap[V] = Val;
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001048 resolveDanglingDebugInfo(V, Val);
Dan Gohmand4322232010-07-01 01:59:43 +00001049 return Val;
1050}
1051
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001052/// getValueImpl - Helper function for getValue and getNonRegisterValue.
Dan Gohmand4322232010-07-01 01:59:43 +00001053/// Create an SDValue for the given value.
1054SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001055 const TargetLowering *TLI = TM.getTargetLowering();
1056
Dan Gohman8422e572010-04-17 15:32:28 +00001057 if (const Constant *C = dyn_cast<Constant>(V)) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001058 EVT VT = TLI->getValueType(V->getType(), true);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001059
Dan Gohman8422e572010-04-17 15:32:28 +00001060 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohmand4322232010-07-01 01:59:43 +00001061 return DAG.getConstant(*CI, VT);
Dan Gohman575fad32008-09-03 16:12:24 +00001062
Dan Gohman8422e572010-04-17 15:32:28 +00001063 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001064 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001065
Matt Arsenault19231e62013-11-16 20:24:41 +00001066 if (isa<ConstantPointerNull>(C)) {
1067 unsigned AS = V->getType()->getPointerAddressSpace();
1068 return DAG.getConstant(0, TLI->getPointerTy(AS));
1069 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001070
Dan Gohman8422e572010-04-17 15:32:28 +00001071 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohmand4322232010-07-01 01:59:43 +00001072 return DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001073
Nate Begeman8d6d4b92009-04-27 18:41:29 +00001074 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dan Gohmand4322232010-07-01 01:59:43 +00001075 return DAG.getUNDEF(VT);
Dan Gohman575fad32008-09-03 16:12:24 +00001076
Dan Gohman8422e572010-04-17 15:32:28 +00001077 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Dan Gohman575fad32008-09-03 16:12:24 +00001078 visit(CE->getOpcode(), *CE);
1079 SDValue N1 = NodeMap[V];
Dan Gohman5664b9f2010-04-16 16:55:18 +00001080 assert(N1.getNode() && "visit didn't populate the NodeMap!");
Dan Gohman575fad32008-09-03 16:12:24 +00001081 return N1;
1082 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001083
Dan Gohman575fad32008-09-03 16:12:24 +00001084 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1085 SmallVector<SDValue, 4> Constants;
1086 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1087 OI != OE; ++OI) {
1088 SDNode *Val = getValue(*OI).getNode();
Dan Gohmanf4a0f0f2009-09-08 01:44:02 +00001089 // If the operand is an empty aggregate, there are no values.
1090 if (!Val) continue;
1091 // Add each leaf value from the operand to the Constants list
1092 // to form a flattened list of all the values.
Dan Gohman575fad32008-09-03 16:12:24 +00001093 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1094 Constants.push_back(SDValue(Val, i));
1095 }
Bill Wendlingc6b47342009-12-21 23:47:40 +00001096
Bill Wendling954cb182010-01-28 21:51:40 +00001097 return DAG.getMergeValues(&Constants[0], Constants.size(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001098 getCurSDLoc());
Dan Gohman575fad32008-09-03 16:12:24 +00001099 }
Stephen Lincfe7f352013-07-08 00:37:03 +00001100
Chris Lattner00245f42012-01-24 13:41:11 +00001101 if (const ConstantDataSequential *CDS =
1102 dyn_cast<ConstantDataSequential>(C)) {
1103 SmallVector<SDValue, 4> Ops;
Chris Lattner9be59592012-01-25 01:27:20 +00001104 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +00001105 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1106 // Add each leaf value from the operand to the Constants list
1107 // to form a flattened list of all the values.
1108 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1109 Ops.push_back(SDValue(Val, i));
1110 }
1111
1112 if (isa<ArrayType>(CDS->getType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001113 return DAG.getMergeValues(&Ops[0], Ops.size(), getCurSDLoc());
1114 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
Chris Lattner00245f42012-01-24 13:41:11 +00001115 VT, &Ops[0], Ops.size());
1116 }
Dan Gohman575fad32008-09-03 16:12:24 +00001117
Duncan Sands19d0b472010-02-16 11:11:14 +00001118 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
Dan Gohman575fad32008-09-03 16:12:24 +00001119 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1120 "Unknown struct or array constant!");
1121
Owen Anderson53aa7a92009-08-10 22:56:29 +00001122 SmallVector<EVT, 4> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001123 ComputeValueVTs(*TLI, C->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00001124 unsigned NumElts = ValueVTs.size();
1125 if (NumElts == 0)
1126 return SDValue(); // empty struct
1127 SmallVector<SDValue, 4> Constants(NumElts);
1128 for (unsigned i = 0; i != NumElts; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001129 EVT EltVT = ValueVTs[i];
Dan Gohman575fad32008-09-03 16:12:24 +00001130 if (isa<UndefValue>(C))
Dale Johannesen84935752009-02-06 23:05:02 +00001131 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohman575fad32008-09-03 16:12:24 +00001132 else if (EltVT.isFloatingPoint())
1133 Constants[i] = DAG.getConstantFP(0, EltVT);
1134 else
1135 Constants[i] = DAG.getConstant(0, EltVT);
1136 }
Bill Wendlingc6b47342009-12-21 23:47:40 +00001137
Bill Wendling954cb182010-01-28 21:51:40 +00001138 return DAG.getMergeValues(&Constants[0], NumElts,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001139 getCurSDLoc());
Dan Gohman575fad32008-09-03 16:12:24 +00001140 }
1141
Dan Gohman8422e572010-04-17 15:32:28 +00001142 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
Dan Gohman7a6611792009-11-20 23:18:13 +00001143 return DAG.getBlockAddress(BA, VT);
Dan Gohman6c938802009-10-30 01:27:03 +00001144
Chris Lattner229907c2011-07-18 04:54:35 +00001145 VectorType *VecTy = cast<VectorType>(V->getType());
Dan Gohman575fad32008-09-03 16:12:24 +00001146 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001147
Dan Gohman575fad32008-09-03 16:12:24 +00001148 // Now that we know the number and type of the elements, get that number of
1149 // elements into the Ops array based on what kind of constant it is.
1150 SmallVector<SDValue, 16> Ops;
Chris Lattner00245f42012-01-24 13:41:11 +00001151 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
Dan Gohman575fad32008-09-03 16:12:24 +00001152 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner00245f42012-01-24 13:41:11 +00001153 Ops.push_back(getValue(CV->getOperand(i)));
Dan Gohman575fad32008-09-03 16:12:24 +00001154 } else {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00001155 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001156 EVT EltVT = TLI->getValueType(VecTy->getElementType());
Dan Gohman575fad32008-09-03 16:12:24 +00001157
1158 SDValue Op;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00001159 if (EltVT.isFloatingPoint())
Dan Gohman575fad32008-09-03 16:12:24 +00001160 Op = DAG.getConstantFP(0, EltVT);
1161 else
1162 Op = DAG.getConstant(0, EltVT);
1163 Ops.assign(NumElements, Op);
1164 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001165
Dan Gohman575fad32008-09-03 16:12:24 +00001166 // Create a BUILD_VECTOR node.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001167 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00001168 VT, &Ops[0], Ops.size());
Dan Gohman575fad32008-09-03 16:12:24 +00001169 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001170
Dan Gohman575fad32008-09-03 16:12:24 +00001171 // If this is a static alloca, generate it as the frameindex instead of
1172 // computation.
1173 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1174 DenseMap<const AllocaInst*, int>::iterator SI =
1175 FuncInfo.StaticAllocaMap.find(AI);
1176 if (SI != FuncInfo.StaticAllocaMap.end())
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001177 return DAG.getFrameIndex(SI->second, TLI->getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00001178 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001179
Dan Gohmand4322232010-07-01 01:59:43 +00001180 // If this is an instruction which fast-isel has deferred, select it now.
1181 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001182 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001183 RegsForValue RFV(*DAG.getContext(), *TLI, InReg, Inst->getType());
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001184 SDValue Chain = DAG.getEntryNode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001185 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
Dan Gohmand4322232010-07-01 01:59:43 +00001186 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001187
Dan Gohmand4322232010-07-01 01:59:43 +00001188 llvm_unreachable("Can't get register for value!");
Dan Gohman575fad32008-09-03 16:12:24 +00001189}
1190
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001191void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001192 const TargetLowering *TLI = TM.getTargetLowering();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001193 SDValue Chain = getControlRoot();
1194 SmallVector<ISD::OutputArg, 8> Outs;
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001195 SmallVector<SDValue, 8> OutVals;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00001196
Dan Gohmand16aa542010-05-29 17:03:36 +00001197 if (!FuncInfo.CanLowerReturn) {
1198 unsigned DemoteReg = FuncInfo.DemoteRegister;
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001199 const Function *F = I.getParent()->getParent();
1200
1201 // Emit a store of the return value through the virtual register.
1202 // Leave Outs empty so that LowerReturn won't try to load return
1203 // registers the usual way.
1204 SmallVector<EVT, 1> PtrValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001205 ComputeValueVTs(*TLI, PointerType::getUnqual(F->getReturnType()),
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001206 PtrValueVTs);
1207
1208 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1209 SDValue RetOp = getValue(I.getOperand(0));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00001210
Owen Anderson53aa7a92009-08-10 22:56:29 +00001211 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001212 SmallVector<uint64_t, 4> Offsets;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001213 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman8b44b882008-10-21 20:00:42 +00001214 unsigned NumValues = ValueVTs.size();
Dan Gohman8b44b882008-10-21 20:00:42 +00001215
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001216 SmallVector<SDValue, 4> Chains(NumValues);
Bill Wendlingc6b47342009-12-21 23:47:40 +00001217 for (unsigned i = 0; i != NumValues; ++i) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001218 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
Chris Lattner96a77eb2010-08-24 23:10:06 +00001219 RetPtr.getValueType(), RetPtr,
1220 DAG.getIntPtrConstant(Offsets[i]));
Bill Wendlingc6b47342009-12-21 23:47:40 +00001221 Chains[i] =
Andrew Trickef9de2a2013-05-25 02:42:55 +00001222 DAG.getStore(Chain, getCurSDLoc(),
Bill Wendlingc6b47342009-12-21 23:47:40 +00001223 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
Chris Lattnera4f19972010-09-21 18:58:22 +00001224 // FIXME: better loc info would be nice.
1225 Add, MachinePointerInfo(), false, false, 0);
Bill Wendlingc6b47342009-12-21 23:47:40 +00001226 }
1227
Andrew Trickef9de2a2013-05-25 02:42:55 +00001228 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001229 MVT::Other, &Chains[0], NumValues);
Chris Lattnerb1af8652010-02-28 18:53:13 +00001230 } else if (I.getNumOperands() != 0) {
1231 SmallVector<EVT, 4> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001232 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs);
Chris Lattnerb1af8652010-02-28 18:53:13 +00001233 unsigned NumValues = ValueVTs.size();
1234 if (NumValues) {
1235 SDValue RetOp = getValue(I.getOperand(0));
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001236 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1237 EVT VT = ValueVTs[j];
Dan Gohman575fad32008-09-03 16:12:24 +00001238
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001239 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001240
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001241 const Function *F = I.getParent()->getParent();
Bill Wendling74dba872012-12-30 13:01:51 +00001242 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1243 Attribute::SExt))
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001244 ExtendKind = ISD::SIGN_EXTEND;
Bill Wendling74dba872012-12-30 13:01:51 +00001245 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1246 Attribute::ZExt))
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001247 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohman575fad32008-09-03 16:12:24 +00001248
Cameron Zwarich2ef0c692011-03-17 14:53:37 +00001249 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001250 VT = TLI->getTypeForExtArgOrReturn(VT.getSimpleVT(), ExtendKind);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001251
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001252 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), VT);
1253 MVT PartVT = TLI->getRegisterType(*DAG.getContext(), VT);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001254 SmallVector<SDValue, 4> Parts(NumParts);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001255 getCopyToParts(DAG, getCurSDLoc(),
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001256 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Bill Wendling5def8912012-09-26 06:16:18 +00001257 &Parts[0], NumParts, PartVT, &I, ExtendKind);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001258
1259 // 'inreg' on function refers to return value
1260 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Bill Wendling74dba872012-12-30 13:01:51 +00001261 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1262 Attribute::InReg))
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001263 Flags.setInReg();
1264
1265 // Propagate extension type if any
Cameron Zwarichd1ad9bc2011-03-16 22:20:07 +00001266 if (ExtendKind == ISD::SIGN_EXTEND)
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001267 Flags.setSExt();
Cameron Zwarichd1ad9bc2011-03-16 22:20:07 +00001268 else if (ExtendKind == ISD::ZERO_EXTEND)
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001269 Flags.setZExt();
1270
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001271 for (unsigned i = 0; i < NumParts; ++i) {
1272 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
Tom Stellard8d7d4de2013-10-23 00:44:24 +00001273 VT, /*isfixed=*/true, 0, 0));
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001274 OutVals.push_back(Parts[i]);
1275 }
Evan Cheng2e9f42b2009-03-25 20:20:11 +00001276 }
Dan Gohman575fad32008-09-03 16:12:24 +00001277 }
1278 }
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001279
1280 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel68c5f472009-09-02 08:44:58 +00001281 CallingConv::ID CallConv =
1282 DAG.getMachineFunction().getFunction()->getCallingConv();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001283 Chain = TM.getTargetLowering()->LowerReturn(Chain, CallConv, isVarArg,
1284 Outs, OutVals, getCurSDLoc(),
1285 DAG);
Dan Gohman695d8112009-08-06 15:37:27 +00001286
1287 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson9f944592009-08-11 20:47:22 +00001288 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00001289 "LowerReturn didn't return a valid chain!");
1290
1291 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001292 DAG.setRoot(Chain);
Dan Gohman575fad32008-09-03 16:12:24 +00001293}
1294
Dan Gohman9478c3f2009-04-23 23:13:24 +00001295/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1296/// created for it, emit nodes to copy the value into the virtual
1297/// registers.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001298void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
Rafael Espindolae53b7d12011-05-13 15:18:06 +00001299 // Skip empty types
1300 if (V->getType()->isEmptyTy())
1301 return;
1302
Dan Gohman3a7ee8e2010-04-16 17:15:02 +00001303 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1304 if (VMI != FuncInfo.ValueMap.end()) {
1305 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1306 CopyValueToVirtualRegister(V, VMI->second);
Dan Gohman9478c3f2009-04-23 23:13:24 +00001307 }
1308}
1309
Dan Gohman575fad32008-09-03 16:12:24 +00001310/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1311/// the current basic block, add it to ValueMap now so that we'll get a
1312/// CopyTo/FromReg.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001313void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
Dan Gohman575fad32008-09-03 16:12:24 +00001314 // No need to export constants.
1315 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001316
Dan Gohman575fad32008-09-03 16:12:24 +00001317 // Already exported?
1318 if (FuncInfo.isExportedInst(V)) return;
1319
1320 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1321 CopyValueToVirtualRegister(V, Reg);
1322}
1323
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001324bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001325 const BasicBlock *FromBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001326 // The operands of the setcc have to be in this block. We don't know
1327 // how to export them from some other block.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001328 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
Dan Gohman575fad32008-09-03 16:12:24 +00001329 // Can export from current BB.
1330 if (VI->getParent() == FromBB)
1331 return true;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001332
Dan Gohman575fad32008-09-03 16:12:24 +00001333 // Is already exported, noop.
1334 return FuncInfo.isExportedInst(V);
1335 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001336
Dan Gohman575fad32008-09-03 16:12:24 +00001337 // If this is an argument, we can export it if the BB is the entry block or
1338 // if it is already exported.
1339 if (isa<Argument>(V)) {
1340 if (FromBB == &FromBB->getParent()->getEntryBlock())
1341 return true;
1342
1343 // Otherwise, can only export this if it is already exported.
1344 return FuncInfo.isExportedInst(V);
1345 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001346
Dan Gohman575fad32008-09-03 16:12:24 +00001347 // Otherwise, constants can always be exported.
1348 return true;
1349}
1350
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001351/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
Jakub Staszak96f8c552011-12-20 20:03:10 +00001352uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1353 const MachineBasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001354 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1355 if (!BPI)
1356 return 0;
Jakub Staszak539db982011-07-29 20:05:36 +00001357 const BasicBlock *SrcBB = Src->getBasicBlock();
1358 const BasicBlock *DstBB = Dst->getBasicBlock();
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001359 return BPI->getEdgeWeight(SrcBB, DstBB);
1360}
1361
Jakub Staszak0480a8f2011-07-29 22:25:21 +00001362void SelectionDAGBuilder::
1363addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1364 uint32_t Weight /* = 0 */) {
1365 if (!Weight)
1366 Weight = getEdgeWeight(Src, Dst);
1367 Src->addSuccessor(Dst, Weight);
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001368}
1369
1370
Dan Gohman575fad32008-09-03 16:12:24 +00001371static bool InBlock(const Value *V, const BasicBlock *BB) {
1372 if (const Instruction *I = dyn_cast<Instruction>(V))
1373 return I->getParent() == BB;
1374 return true;
1375}
1376
Dan Gohmand01ddb52008-10-17 21:16:08 +00001377/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1378/// This function emits a branch and is used at the leaves of an OR or an
1379/// AND operator tree.
1380///
1381void
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001382SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001383 MachineBasicBlock *TBB,
1384 MachineBasicBlock *FBB,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001385 MachineBasicBlock *CurBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001386 MachineBasicBlock *SwitchBB,
1387 uint32_t TWeight,
1388 uint32_t FWeight) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001389 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohman575fad32008-09-03 16:12:24 +00001390
Dan Gohmand01ddb52008-10-17 21:16:08 +00001391 // If the leaf of the tree is a comparison, merge the condition into
1392 // the caseblock.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001393 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001394 // The operands of the cmp have to be in this block. We don't know
1395 // how to export them from some other block. If this is the first block
1396 // of the sequence, no exporting is needed.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001397 if (CurBB == SwitchBB ||
Dan Gohmand01ddb52008-10-17 21:16:08 +00001398 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1399 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohman575fad32008-09-03 16:12:24 +00001400 ISD::CondCode Condition;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001401 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman293abcc2008-10-17 18:18:45 +00001402 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001403 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman293abcc2008-10-17 18:18:45 +00001404 Condition = getFCmpCondCode(FC->getPredicate());
Nick Lewycky50f02cb2011-12-02 22:16:29 +00001405 if (TM.Options.NoNaNsFPMath)
1406 Condition = getFCmpCodeWithoutNaN(Condition);
Dan Gohman575fad32008-09-03 16:12:24 +00001407 } else {
1408 Condition = ISD::SETEQ; // silence warning.
Torok Edwinfbcc6632009-07-14 16:55:14 +00001409 llvm_unreachable("Unknown compare instruction");
Dan Gohman575fad32008-09-03 16:12:24 +00001410 }
Dan Gohmand01ddb52008-10-17 21:16:08 +00001411
1412 CaseBlock CB(Condition, BOp->getOperand(0),
Manman Ren4ece7452014-01-31 00:42:44 +00001413 BOp->getOperand(1), NULL, TBB, FBB, CurBB, TWeight, FWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001414 SwitchCases.push_back(CB);
1415 return;
1416 }
Dan Gohmand01ddb52008-10-17 21:16:08 +00001417 }
1418
1419 // Create a CaseBlock record representing this branch.
Owen Anderson23a204d2009-07-31 17:39:07 +00001420 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Manman Ren4ece7452014-01-31 00:42:44 +00001421 NULL, TBB, FBB, CurBB, TWeight, FWeight);
Dan Gohmand01ddb52008-10-17 21:16:08 +00001422 SwitchCases.push_back(CB);
1423}
1424
Manman Ren4ece7452014-01-31 00:42:44 +00001425/// Scale down both weights to fit into uint32_t.
1426static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1427 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1428 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1429 NewTrue = NewTrue / Scale;
1430 NewFalse = NewFalse / Scale;
1431}
1432
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001433/// FindMergedConditions - If Cond is an expression like
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001434void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001435 MachineBasicBlock *TBB,
1436 MachineBasicBlock *FBB,
1437 MachineBasicBlock *CurBB,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001438 MachineBasicBlock *SwitchBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001439 unsigned Opc, uint32_t TWeight,
1440 uint32_t FWeight) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001441 // If this node is not part of the or/and tree, emit it as a branch.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001442 const Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001443 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmand01ddb52008-10-17 21:16:08 +00001444 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1445 BOp->getParent() != CurBB->getBasicBlock() ||
1446 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1447 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Manman Ren4ece7452014-01-31 00:42:44 +00001448 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1449 TWeight, FWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001450 return;
1451 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001452
Dan Gohman575fad32008-09-03 16:12:24 +00001453 // Create TmpBB after CurBB.
1454 MachineFunction::iterator BBI = CurBB;
1455 MachineFunction &MF = DAG.getMachineFunction();
1456 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1457 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001458
Dan Gohman575fad32008-09-03 16:12:24 +00001459 if (Opc == Instruction::Or) {
1460 // Codegen X | Y as:
Manman Ren4ece7452014-01-31 00:42:44 +00001461 // BB1:
Dan Gohman575fad32008-09-03 16:12:24 +00001462 // jmp_if_X TBB
1463 // jmp TmpBB
1464 // TmpBB:
1465 // jmp_if_Y TBB
1466 // jmp FBB
1467 //
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001468
Manman Ren4ece7452014-01-31 00:42:44 +00001469 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1470 // The requirement is that
1471 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1472 // = TrueProb for orignal BB.
1473 // Assuming the orignal weights are A and B, one choice is to set BB1's
1474 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1475 // assumes that
1476 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1477 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1478 // TmpBB, but the math is more complicated.
Manman Ren104e0c82014-01-30 00:24:37 +00001479
Manman Ren4ece7452014-01-31 00:42:44 +00001480 uint64_t NewTrueWeight = TWeight;
1481 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1482 ScaleWeights(NewTrueWeight, NewFalseWeight);
1483 // Emit the LHS condition.
1484 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1485 NewTrueWeight, NewFalseWeight);
1486
1487 NewTrueWeight = TWeight;
1488 NewFalseWeight = 2 * (uint64_t)FWeight;
1489 ScaleWeights(NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001490 // Emit the RHS condition into TmpBB.
Manman Ren4ece7452014-01-31 00:42:44 +00001491 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1492 NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001493 } else {
1494 assert(Opc == Instruction::And && "Unknown merge op!");
1495 // Codegen X & Y as:
Manman Ren4ece7452014-01-31 00:42:44 +00001496 // BB1:
Dan Gohman575fad32008-09-03 16:12:24 +00001497 // jmp_if_X TmpBB
1498 // jmp FBB
1499 // TmpBB:
1500 // jmp_if_Y TBB
1501 // jmp FBB
1502 //
1503 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001504
Manman Ren4ece7452014-01-31 00:42:44 +00001505 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1506 // The requirement is that
1507 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1508 // = FalseProb for orignal BB.
1509 // Assuming the orignal weights are A and B, one choice is to set BB1's
1510 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1511 // assumes that
1512 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
Manman Ren104e0c82014-01-30 00:24:37 +00001513
Manman Ren4ece7452014-01-31 00:42:44 +00001514 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1515 uint64_t NewFalseWeight = FWeight;
1516 ScaleWeights(NewTrueWeight, NewFalseWeight);
1517 // Emit the LHS condition.
1518 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1519 NewTrueWeight, NewFalseWeight);
1520
1521 NewTrueWeight = 2 * (uint64_t)TWeight;
1522 NewFalseWeight = FWeight;
1523 ScaleWeights(NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001524 // Emit the RHS condition into TmpBB.
Manman Ren4ece7452014-01-31 00:42:44 +00001525 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1526 NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001527 }
1528}
1529
1530/// If the set of cases should be emitted as a series of branches, return true.
1531/// If we should emit this as a bunch of and/or'd together conditions, return
1532/// false.
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001533bool
Stephen Lin6d715e82013-07-06 21:44:25 +00001534SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
Dan Gohman575fad32008-09-03 16:12:24 +00001535 if (Cases.size() != 2) return true;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001536
Dan Gohman575fad32008-09-03 16:12:24 +00001537 // If this is two comparisons of the same values or'd or and'd together, they
1538 // will get folded into a single comparison, so don't emit two blocks.
1539 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1540 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1541 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1542 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1543 return false;
1544 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001545
Chris Lattner1eea3b02010-01-02 00:00:03 +00001546 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1547 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1548 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1549 Cases[0].CC == Cases[1].CC &&
1550 isa<Constant>(Cases[0].CmpRHS) &&
1551 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1552 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1553 return false;
1554 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1555 return false;
1556 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00001557
Dan Gohman575fad32008-09-03 16:12:24 +00001558 return true;
1559}
1560
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001561void SelectionDAGBuilder::visitBr(const BranchInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001562 MachineBasicBlock *BrMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001563
Dan Gohman575fad32008-09-03 16:12:24 +00001564 // Update machine-CFG edges.
1565 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1566
1567 // Figure out which block is immediately after the current one.
1568 MachineBasicBlock *NextBlock = 0;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001569 MachineFunction::iterator BBI = BrMBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001570 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001571 NextBlock = BBI;
1572
1573 if (I.isUnconditional()) {
1574 // Update machine-CFG edges.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001575 BrMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001576
Dan Gohman575fad32008-09-03 16:12:24 +00001577 // If this is not a fall-through branch, emit the branch.
Bill Wendling954cb182010-01-28 21:51:40 +00001578 if (Succ0MBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001579 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001580 MVT::Other, getControlRoot(),
Bill Wendling954cb182010-01-28 21:51:40 +00001581 DAG.getBasicBlock(Succ0MBB)));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001582
Dan Gohman575fad32008-09-03 16:12:24 +00001583 return;
1584 }
1585
1586 // If this condition is one of the special cases we handle, do special stuff
1587 // now.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001588 const Value *CondVal = I.getCondition();
Dan Gohman575fad32008-09-03 16:12:24 +00001589 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1590
1591 // If this is a series of conditions that are or'd or and'd together, emit
1592 // this as a sequence of branches instead of setcc's with and/or operations.
Chris Lattnerea41dfe2010-11-30 18:12:52 +00001593 // As long as jumps are not expensive, this should improve performance.
Dan Gohman575fad32008-09-03 16:12:24 +00001594 // For example, instead of something like:
1595 // cmp A, B
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001596 // C = seteq
Dan Gohman575fad32008-09-03 16:12:24 +00001597 // cmp D, E
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001598 // F = setle
Dan Gohman575fad32008-09-03 16:12:24 +00001599 // or C, F
1600 // jnz foo
1601 // Emit:
1602 // cmp A, B
1603 // je foo
1604 // cmp D, E
1605 // jle foo
1606 //
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001607 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001608 if (!TM.getTargetLowering()->isJumpExpensive() &&
Chris Lattnerea41dfe2010-11-30 18:12:52 +00001609 BOp->hasOneUse() &&
Dan Gohman575fad32008-09-03 16:12:24 +00001610 (BOp->getOpcode() == Instruction::And ||
1611 BOp->getOpcode() == Instruction::Or)) {
Dan Gohman7c0303a2010-04-19 22:41:47 +00001612 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001613 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1614 getEdgeWeight(BrMBB, Succ1MBB));
Dan Gohman575fad32008-09-03 16:12:24 +00001615 // If the compares in later blocks need to use values not currently
1616 // exported from this block, export them now. This block should always
1617 // be the first entry.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001618 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001619
Dan Gohman575fad32008-09-03 16:12:24 +00001620 // Allow some cases to be rejected.
1621 if (ShouldEmitAsBranches(SwitchCases)) {
1622 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1623 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1624 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1625 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001626
Dan Gohman575fad32008-09-03 16:12:24 +00001627 // Emit the branch for this block.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001628 visitSwitchCase(SwitchCases[0], BrMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001629 SwitchCases.erase(SwitchCases.begin());
1630 return;
1631 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001632
Dan Gohman575fad32008-09-03 16:12:24 +00001633 // Okay, we decided not to do this, remove any inserted MBB's and clear
1634 // SwitchCases.
1635 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohmane8c913e2009-08-15 02:06:22 +00001636 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001637
Dan Gohman575fad32008-09-03 16:12:24 +00001638 SwitchCases.clear();
1639 }
1640 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001641
Dan Gohman575fad32008-09-03 16:12:24 +00001642 // Create a CaseBlock record representing this branch.
Owen Anderson23a204d2009-07-31 17:39:07 +00001643 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohman7c0303a2010-04-19 22:41:47 +00001644 NULL, Succ0MBB, Succ1MBB, BrMBB);
Bill Wendling7f5eb532009-12-21 19:59:38 +00001645
Dan Gohman575fad32008-09-03 16:12:24 +00001646 // Use visitSwitchCase to actually insert the fast branch sequence for this
1647 // cond branch.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001648 visitSwitchCase(CB, BrMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001649}
1650
1651/// visitSwitchCase - Emits the necessary code to represent a single node in
1652/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001653void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1654 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001655 SDValue Cond;
1656 SDValue CondLHS = getValue(CB.CmpLHS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001657 SDLoc dl = getCurSDLoc();
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001658
1659 // Build the setcc now.
Dan Gohman575fad32008-09-03 16:12:24 +00001660 if (CB.CmpMHS == NULL) {
1661 // Fold "(X == true)" to X and "(X == false)" to !X to
1662 // handle common cases produced by branch lowering.
Owen Anderson23a204d2009-07-31 17:39:07 +00001663 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Anderson2ad52172009-07-21 02:47:59 +00001664 CB.CC == ISD::SETEQ)
Dan Gohman575fad32008-09-03 16:12:24 +00001665 Cond = CondLHS;
Owen Anderson23a204d2009-07-31 17:39:07 +00001666 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Anderson2ad52172009-07-21 02:47:59 +00001667 CB.CC == ISD::SETEQ) {
Dan Gohman575fad32008-09-03 16:12:24 +00001668 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001669 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohman575fad32008-09-03 16:12:24 +00001670 } else
Owen Anderson9f944592009-08-11 20:47:22 +00001671 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohman575fad32008-09-03 16:12:24 +00001672 } else {
Bob Wilsone4077362013-09-09 19:14:35 +00001673 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Dan Gohman575fad32008-09-03 16:12:24 +00001674
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001675 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1676 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00001677
1678 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001679 EVT VT = CmpOp.getValueType();
Stephen Lincfe7f352013-07-08 00:37:03 +00001680
Bob Wilsone4077362013-09-09 19:14:35 +00001681 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson9f944592009-08-11 20:47:22 +00001682 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Bob Wilsone4077362013-09-09 19:14:35 +00001683 ISD::SETLE);
Dan Gohman575fad32008-09-03 16:12:24 +00001684 } else {
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001685 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesened255b32009-01-30 01:34:22 +00001686 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson9f944592009-08-11 20:47:22 +00001687 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohman575fad32008-09-03 16:12:24 +00001688 DAG.getConstant(High-Low, VT), ISD::SETULE);
1689 }
1690 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001691
Dan Gohman575fad32008-09-03 16:12:24 +00001692 // Update successor info
Jakub Staszak0480a8f2011-07-29 22:25:21 +00001693 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
Jakob Stoklund Olesen7d33c572012-08-20 21:39:52 +00001694 // TrueBB and FalseBB are always different unless the incoming IR is
1695 // degenerate. This only happens when running llc on weird IR.
1696 if (CB.TrueBB != CB.FalseBB)
1697 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001698
Dan Gohman575fad32008-09-03 16:12:24 +00001699 // Set NextBlock to be the MBB immediately after the current one, if any.
1700 // This is used to avoid emitting unnecessary branches to the next block.
1701 MachineBasicBlock *NextBlock = 0;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001702 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001703 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001704 NextBlock = BBI;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001705
Dan Gohman575fad32008-09-03 16:12:24 +00001706 // If the lhs block is the next block, invert the condition so that we can
1707 // fall through to the lhs instead of the rhs block.
1708 if (CB.TrueBB == NextBlock) {
1709 std::swap(CB.TrueBB, CB.FalseBB);
1710 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001711 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohman575fad32008-09-03 16:12:24 +00001712 }
Bill Wendling7f5eb532009-12-21 19:59:38 +00001713
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001714 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson9f944592009-08-11 20:47:22 +00001715 MVT::Other, getControlRoot(), Cond,
Dale Johannesened255b32009-01-30 01:34:22 +00001716 DAG.getBasicBlock(CB.TrueBB));
Bill Wendlingc6b47342009-12-21 23:47:40 +00001717
Evan Cheng79687dd2010-09-23 06:51:55 +00001718 // Insert the false branch. Do this even if it's a fall through branch,
1719 // this makes it easier to do DAG optimizations which require inverting
1720 // the branch condition.
1721 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1722 DAG.getBasicBlock(CB.FalseBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001723
1724 DAG.setRoot(BrCond);
Dan Gohman575fad32008-09-03 16:12:24 +00001725}
1726
1727/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001728void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
Dan Gohman575fad32008-09-03 16:12:24 +00001729 // Emit the code for the jump table
1730 assert(JT.Reg != -1U && "Should lower JT Header first!");
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001731 EVT PTy = TM.getTargetLowering()->getPointerTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001732 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00001733 JT.Reg, PTy);
Dan Gohman575fad32008-09-03 16:12:24 +00001734 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001735 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
Bill Wendling7f5eb532009-12-21 19:59:38 +00001736 MVT::Other, Index.getValue(1),
1737 Table, Index);
1738 DAG.setRoot(BrJumpTable);
Dan Gohman575fad32008-09-03 16:12:24 +00001739}
1740
1741/// visitJumpTableHeader - This function emits necessary code to produce index
1742/// in the JumpTable from switch case.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001743void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001744 JumpTableHeader &JTH,
1745 MachineBasicBlock *SwitchBB) {
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001746 // Subtract the lowest switch case value from the value being switched on and
1747 // conditional branch to default mbb if the result is greater than the
Dan Gohman575fad32008-09-03 16:12:24 +00001748 // difference between smallest and largest cases.
1749 SDValue SwitchOp = getValue(JTH.SValue);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001750 EVT VT = SwitchOp.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001751 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001752 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001753
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001754 // The SDNode we just created, which holds the value being switched on minus
Dan Gohman4a618822010-02-10 16:03:48 +00001755 // the smallest case value, needs to be copied to a virtual register so it
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001756 // can be used as an index into the jump table in a subsequent basic block.
1757 // This value may be smaller or larger than the target's pointer type, and
1758 // therefore require extension or truncating.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001759 const TargetLowering *TLI = TM.getTargetLowering();
1760 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI->getPointerTy());
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001761
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001762 unsigned JumpTableReg = FuncInfo.CreateReg(TLI->getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001763 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00001764 JumpTableReg, SwitchOp);
Dan Gohman575fad32008-09-03 16:12:24 +00001765 JT.Reg = JumpTableReg;
1766
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001767 // Emit the range check for the jump table, and branch to the default block
1768 // for the switch statement if the value being switched on exceeds the largest
1769 // case in the switch.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001770 SDValue CMP = DAG.getSetCC(getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001771 TLI->getSetCCResultType(*DAG.getContext(),
1772 Sub.getValueType()),
Matt Arsenault758659232013-05-18 00:21:46 +00001773 Sub,
1774 DAG.getConstant(JTH.Last - JTH.First,VT),
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001775 ISD::SETUGT);
Dan Gohman575fad32008-09-03 16:12:24 +00001776
1777 // Set NextBlock to be the MBB immediately after the current one, if any.
1778 // This is used to avoid emitting unnecessary branches to the next block.
1779 MachineBasicBlock *NextBlock = 0;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001780 MachineFunction::iterator BBI = SwitchBB;
Bill Wendlingc6b47342009-12-21 23:47:40 +00001781
Dan Gohmane8c913e2009-08-15 02:06:22 +00001782 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001783 NextBlock = BBI;
1784
Andrew Trickef9de2a2013-05-25 02:42:55 +00001785 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001786 MVT::Other, CopyTo, CMP,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001787 DAG.getBasicBlock(JT.Default));
Dan Gohman575fad32008-09-03 16:12:24 +00001788
Bill Wendling954cb182010-01-28 21:51:40 +00001789 if (JT.MBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001790 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
Bill Wendling7f5eb532009-12-21 19:59:38 +00001791 DAG.getBasicBlock(JT.MBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001792
Bill Wendlingc6b47342009-12-21 23:47:40 +00001793 DAG.setRoot(BrCond);
Dan Gohman575fad32008-09-03 16:12:24 +00001794}
1795
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001796/// Codegen a new tail for a stack protector check ParentMBB which has had its
1797/// tail spliced into a stack protector check success bb.
1798///
1799/// For a high level explanation of how this fits into the stack protector
1800/// generation see the comment on the declaration of class
1801/// StackProtectorDescriptor.
1802void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1803 MachineBasicBlock *ParentBB) {
1804
1805 // First create the loads to the guard/stack slot for the comparison.
1806 const TargetLowering *TLI = TM.getTargetLowering();
1807 EVT PtrTy = TLI->getPointerTy();
1808
1809 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1810 int FI = MFI->getStackProtectorIndex();
1811
1812 const Value *IRGuard = SPD.getGuard();
1813 SDValue GuardPtr = getValue(IRGuard);
1814 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1815
1816 unsigned Align =
1817 TLI->getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1818 SDValue Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1819 GuardPtr, MachinePointerInfo(IRGuard, 0),
1820 true, false, false, Align);
1821
1822 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1823 StackSlotPtr,
1824 MachinePointerInfo::getFixedStack(FI),
1825 true, false, false, Align);
1826
1827 // Perform the comparison via a subtract/getsetcc.
1828 EVT VT = Guard.getValueType();
1829 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1830
1831 SDValue Cmp = DAG.getSetCC(getCurSDLoc(),
1832 TLI->getSetCCResultType(*DAG.getContext(),
1833 Sub.getValueType()),
1834 Sub, DAG.getConstant(0, VT),
1835 ISD::SETNE);
1836
1837 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1838 // branch to failure MBB.
1839 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1840 MVT::Other, StackSlot.getOperand(0),
1841 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1842 // Otherwise branch to success MBB.
1843 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1844 MVT::Other, BrCond,
1845 DAG.getBasicBlock(SPD.getSuccessMBB()));
1846
1847 DAG.setRoot(Br);
1848}
1849
1850/// Codegen the failure basic block for a stack protector check.
1851///
1852/// A failure stack protector machine basic block consists simply of a call to
1853/// __stack_chk_fail().
1854///
1855/// For a high level explanation of how this fits into the stack protector
1856/// generation see the comment on the declaration of class
1857/// StackProtectorDescriptor.
1858void
1859SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1860 const TargetLowering *TLI = TM.getTargetLowering();
1861 SDValue Chain = TLI->makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
1862 MVT::isVoid, 0, 0, false, getCurSDLoc(),
Michael Gottesman20f25eb2013-08-22 23:45:24 +00001863 false, false).second;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001864 DAG.setRoot(Chain);
1865}
1866
Dan Gohman575fad32008-09-03 16:12:24 +00001867/// visitBitTestHeader - This function emits necessary code to produce value
1868/// suitable for "bit tests"
Dan Gohman7c0303a2010-04-19 22:41:47 +00001869void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1870 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001871 // Subtract the minimum value
1872 SDValue SwitchOp = getValue(B.SValue);
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00001873 EVT VT = SwitchOp.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001874 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001875 DAG.getConstant(B.First, VT));
Dan Gohman575fad32008-09-03 16:12:24 +00001876
1877 // Check range
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001878 const TargetLowering *TLI = TM.getTargetLowering();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001879 SDValue RangeCmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001880 TLI->getSetCCResultType(*DAG.getContext(),
Matt Arsenault758659232013-05-18 00:21:46 +00001881 Sub.getValueType()),
Bill Wendlingc6b47342009-12-21 23:47:40 +00001882 Sub, DAG.getConstant(B.Range, VT),
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001883 ISD::SETUGT);
Dan Gohman575fad32008-09-03 16:12:24 +00001884
Evan Chengac730dd2011-01-06 01:02:44 +00001885 // Determine the type of the test operands.
1886 bool UsePtrType = false;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001887 if (!TLI->isTypeLegal(VT))
Evan Chengac730dd2011-01-06 01:02:44 +00001888 UsePtrType = true;
1889 else {
1890 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
Eli Friedman979009e2011-10-12 22:46:45 +00001891 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
Evan Chengac730dd2011-01-06 01:02:44 +00001892 // Switch table case range are encoded into series of masks.
1893 // Just use pointer type, it's guaranteed to fit.
1894 UsePtrType = true;
1895 break;
1896 }
1897 }
1898 if (UsePtrType) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001899 VT = TLI->getPointerTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001900 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
Evan Chengac730dd2011-01-06 01:02:44 +00001901 }
Dan Gohman575fad32008-09-03 16:12:24 +00001902
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00001903 B.RegVT = VT.getSimpleVT();
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00001904 B.Reg = FuncInfo.CreateReg(B.RegVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001905 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001906 B.Reg, Sub);
Dan Gohman575fad32008-09-03 16:12:24 +00001907
1908 // Set NextBlock to be the MBB immediately after the current one, if any.
1909 // This is used to avoid emitting unnecessary branches to the next block.
1910 MachineBasicBlock *NextBlock = 0;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001911 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001912 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001913 NextBlock = BBI;
1914
1915 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1916
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001917 addSuccessorWithWeight(SwitchBB, B.Default);
1918 addSuccessorWithWeight(SwitchBB, MBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001919
Andrew Trickef9de2a2013-05-25 02:42:55 +00001920 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001921 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001922 DAG.getBasicBlock(B.Default));
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001923
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001924 if (MBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001925 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001926 DAG.getBasicBlock(MBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001927
Bill Wendlingc6b47342009-12-21 23:47:40 +00001928 DAG.setRoot(BrRange);
Dan Gohman575fad32008-09-03 16:12:24 +00001929}
1930
1931/// visitBitTestCase - this function produces one "bit test"
Evan Chengac730dd2011-01-06 01:02:44 +00001932void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1933 MachineBasicBlock* NextMBB,
Manman Rencf104462012-08-24 18:14:27 +00001934 uint32_t BranchWeightToNext,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001935 unsigned Reg,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001936 BitTestCase &B,
1937 MachineBasicBlock *SwitchBB) {
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00001938 MVT VT = BB.RegVT;
Andrew Trickef9de2a2013-05-25 02:42:55 +00001939 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001940 Reg, VT);
Dan Gohman0695e092010-06-24 02:06:24 +00001941 SDValue Cmp;
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001942 unsigned PopCount = CountPopulation_64(B.Mask);
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001943 const TargetLowering *TLI = TM.getTargetLowering();
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001944 if (PopCount == 1) {
Dan Gohman0695e092010-06-24 02:06:24 +00001945 // Testing for a single bit; just compare the shift count with what it
1946 // would need to be to shift a 1 bit in that position.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001947 Cmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001948 TLI->getSetCCResultType(*DAG.getContext(), VT),
Dan Gohman0695e092010-06-24 02:06:24 +00001949 ShiftOp,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001950 DAG.getConstant(countTrailingZeros(B.Mask), VT),
Dan Gohman0695e092010-06-24 02:06:24 +00001951 ISD::SETEQ);
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001952 } else if (PopCount == BB.Range) {
1953 // There is only one zero bit in the range, test for it directly.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001954 Cmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001955 TLI->getSetCCResultType(*DAG.getContext(), VT),
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001956 ShiftOp,
1957 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1958 ISD::SETNE);
Dan Gohman0695e092010-06-24 02:06:24 +00001959 } else {
1960 // Make desired shift
Andrew Trickef9de2a2013-05-25 02:42:55 +00001961 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
Evan Chengac730dd2011-01-06 01:02:44 +00001962 DAG.getConstant(1, VT), ShiftOp);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001963
Dan Gohman0695e092010-06-24 02:06:24 +00001964 // Emit bit tests and jumps
Andrew Trickef9de2a2013-05-25 02:42:55 +00001965 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001966 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001967 Cmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001968 TLI->getSetCCResultType(*DAG.getContext(), VT),
Evan Chengac730dd2011-01-06 01:02:44 +00001969 AndOp, DAG.getConstant(0, VT),
Dan Gohman0695e092010-06-24 02:06:24 +00001970 ISD::SETNE);
1971 }
Dan Gohman575fad32008-09-03 16:12:24 +00001972
Manman Rencf104462012-08-24 18:14:27 +00001973 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1974 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1975 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1976 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001977
Andrew Trickef9de2a2013-05-25 02:42:55 +00001978 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001979 MVT::Other, getControlRoot(),
Dan Gohman0695e092010-06-24 02:06:24 +00001980 Cmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohman575fad32008-09-03 16:12:24 +00001981
1982 // Set NextBlock to be the MBB immediately after the current one, if any.
1983 // This is used to avoid emitting unnecessary branches to the next block.
1984 MachineBasicBlock *NextBlock = 0;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001985 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001986 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001987 NextBlock = BBI;
1988
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001989 if (NextMBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001990 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001991 DAG.getBasicBlock(NextMBB));
Bill Wendling28727f32009-12-21 21:59:52 +00001992
Bill Wendlingc6b47342009-12-21 23:47:40 +00001993 DAG.setRoot(BrAnd);
Dan Gohman575fad32008-09-03 16:12:24 +00001994}
1995
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001996void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001997 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001998
Dan Gohman575fad32008-09-03 16:12:24 +00001999 // Retrieve successors.
2000 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2001 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2002
Gabor Greif08a4c282009-01-15 11:10:44 +00002003 const Value *Callee(I.getCalledValue());
Nuno Lopesec9653b2012-06-28 22:30:12 +00002004 const Function *Fn = dyn_cast<Function>(Callee);
Gabor Greif08a4c282009-01-15 11:10:44 +00002005 if (isa<InlineAsm>(Callee))
Dan Gohman575fad32008-09-03 16:12:24 +00002006 visitInlineAsm(&I);
Nuno Lopesec9653b2012-06-28 22:30:12 +00002007 else if (Fn && Fn->isIntrinsic()) {
2008 assert(Fn->getIntrinsicID() == Intrinsic::donothing);
Nuno Lopes21514972012-07-18 00:07:17 +00002009 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
Nuno Lopesec9653b2012-06-28 22:30:12 +00002010 } else
Gabor Greif08a4c282009-01-15 11:10:44 +00002011 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohman575fad32008-09-03 16:12:24 +00002012
2013 // If the value of the invoke is used outside of its defining block, make it
2014 // available as a virtual register.
Dan Gohman9478c3f2009-04-23 23:13:24 +00002015 CopyToExportRegsIfNeeded(&I);
Dan Gohman575fad32008-09-03 16:12:24 +00002016
2017 // Update successor info
Chandler Carruthe2530dc2011-11-22 11:37:46 +00002018 addSuccessorWithWeight(InvokeMBB, Return);
2019 addSuccessorWithWeight(InvokeMBB, LandingPad);
Dan Gohman575fad32008-09-03 16:12:24 +00002020
2021 // Drop into normal successor.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002022 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002023 MVT::Other, getControlRoot(),
2024 DAG.getBasicBlock(Return)));
Dan Gohman575fad32008-09-03 16:12:24 +00002025}
2026
Bill Wendlingf891bf82011-07-31 06:30:59 +00002027void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2028 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2029}
2030
Bill Wendling247fd3b2011-08-17 21:56:44 +00002031void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2032 assert(FuncInfo.MBB->isLandingPad() &&
2033 "Call to landingpad not in landing pad!");
2034
2035 MachineBasicBlock *MBB = FuncInfo.MBB;
2036 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2037 AddLandingPadInfo(LP, MMI, MBB);
2038
Bill Wendling05d6f2f2012-02-13 23:47:16 +00002039 // If there aren't registers to copy the values into (e.g., during SjLj
2040 // exceptions), then don't bother to create these DAG nodes.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002041 const TargetLowering *TLI = TM.getTargetLowering();
2042 if (TLI->getExceptionPointerRegister() == 0 &&
2043 TLI->getExceptionSelectorRegister() == 0)
Bill Wendling05d6f2f2012-02-13 23:47:16 +00002044 return;
2045
Bill Wendling247fd3b2011-08-17 21:56:44 +00002046 SmallVector<EVT, 2> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002047 ComputeValueVTs(*TLI, LP.getType(), ValueVTs);
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002048 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
Bill Wendling247fd3b2011-08-17 21:56:44 +00002049
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002050 // Get the two live-in registers as SDValues. The physregs have already been
2051 // copied into virtual registers.
Bill Wendling247fd3b2011-08-17 21:56:44 +00002052 SDValue Ops[2];
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002053 Ops[0] = DAG.getZExtOrTrunc(
2054 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2055 FuncInfo.ExceptionPointerVirtReg, TLI->getPointerTy()),
2056 getCurSDLoc(), ValueVTs[0]);
2057 Ops[1] = DAG.getZExtOrTrunc(
2058 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2059 FuncInfo.ExceptionSelectorVirtReg, TLI->getPointerTy()),
2060 getCurSDLoc(), ValueVTs[1]);
Bill Wendling247fd3b2011-08-17 21:56:44 +00002061
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002062 // Merge into one.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002063 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling247fd3b2011-08-17 21:56:44 +00002064 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
2065 &Ops[0], 2);
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002066 setValue(&LP, Res);
Bill Wendling247fd3b2011-08-17 21:56:44 +00002067}
2068
Dan Gohman575fad32008-09-03 16:12:24 +00002069/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2070/// small case ranges).
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002071bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2072 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002073 const Value* SV,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002074 MachineBasicBlock *Default,
2075 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002076 // Size is the number of Cases represented by this range.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002077 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohman575fad32008-09-03 16:12:24 +00002078 if (Size > 3)
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002079 return false;
2080
Dan Gohman575fad32008-09-03 16:12:24 +00002081 // Get the MachineFunction which holds the current MBB. This is used when
2082 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002083 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002084
2085 // Figure out which block is immediately after the current one.
2086 MachineBasicBlock *NextBlock = 0;
2087 MachineFunction::iterator BBI = CR.CaseBB;
2088
Dan Gohmane8c913e2009-08-15 02:06:22 +00002089 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00002090 NextBlock = BBI;
2091
Manman Rencf104462012-08-24 18:14:27 +00002092 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Benjamin Kramer24656c92010-11-22 09:45:38 +00002093 // If any two of the cases has the same destination, and if one value
Dan Gohman575fad32008-09-03 16:12:24 +00002094 // is the same as the other, but has one bit unset that the other has set,
2095 // use bit manipulation to do two compares at once. For example:
2096 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Benjamin Kramer24656c92010-11-22 09:45:38 +00002097 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2098 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2099 if (Size == 2 && CR.CaseBB == SwitchBB) {
2100 Case &Small = *CR.Range.first;
2101 Case &Big = *(CR.Range.second-1);
2102
2103 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2104 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2105 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2106
2107 // Check that there is only one bit different.
2108 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2109 (SmallValue | BigValue) == BigValue) {
2110 // Isolate the common bit.
2111 APInt CommonBit = BigValue & ~SmallValue;
2112 assert((SmallValue | CommonBit) == BigValue &&
2113 CommonBit.countPopulation() == 1 && "Not a common bit?");
2114
2115 SDValue CondLHS = getValue(SV);
2116 EVT VT = CondLHS.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002117 SDLoc DL = getCurSDLoc();
Benjamin Kramer24656c92010-11-22 09:45:38 +00002118
2119 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2120 DAG.getConstant(CommonBit, VT));
2121 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2122 Or, DAG.getConstant(BigValue, VT),
2123 ISD::SETEQ);
2124
2125 // Update successor info.
Manman Rencf104462012-08-24 18:14:27 +00002126 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2127 addSuccessorWithWeight(SwitchBB, Small.BB,
2128 Small.ExtraWeight + Big.ExtraWeight);
2129 addSuccessorWithWeight(SwitchBB, Default,
2130 // The default destination is the first successor in IR.
2131 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
Benjamin Kramer24656c92010-11-22 09:45:38 +00002132
2133 // Insert the true branch.
2134 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2135 getControlRoot(), Cond,
2136 DAG.getBasicBlock(Small.BB));
2137
2138 // Insert the false branch.
2139 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2140 DAG.getBasicBlock(Default));
2141
2142 DAG.setRoot(BrCond);
2143 return true;
2144 }
2145 }
2146 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002147
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002148 // Order cases by weight so the most likely case will be checked first.
Manman Rencf104462012-08-24 18:14:27 +00002149 uint32_t UnhandledWeights = 0;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002150 if (BPI) {
2151 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
Manman Rencf104462012-08-24 18:14:27 +00002152 uint32_t IWeight = I->ExtraWeight;
2153 UnhandledWeights += IWeight;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002154 for (CaseItr J = CR.Range.first; J < I; ++J) {
Manman Rencf104462012-08-24 18:14:27 +00002155 uint32_t JWeight = J->ExtraWeight;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002156 if (IWeight > JWeight)
2157 std::swap(*I, *J);
2158 }
2159 }
2160 }
Dan Gohman575fad32008-09-03 16:12:24 +00002161 // Rearrange the case blocks so that the last one falls through if possible.
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002162 Case &BackCase = *(CR.Range.second-1);
Benjamin Kramer5aad8722012-05-26 21:19:12 +00002163 if (Size > 1 &&
2164 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Dan Gohman575fad32008-09-03 16:12:24 +00002165 // The last case block won't fall through into 'NextBlock' if we emit the
2166 // branches in this order. See if rearranging a case value would help.
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002167 // We start at the bottom as it's the case with the least weight.
Stephen Lin6d715e82013-07-06 21:44:25 +00002168 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
Dan Gohman575fad32008-09-03 16:12:24 +00002169 if (I->BB == NextBlock) {
2170 std::swap(*I, BackCase);
2171 break;
2172 }
Dan Gohman575fad32008-09-03 16:12:24 +00002173 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002174
Dan Gohman575fad32008-09-03 16:12:24 +00002175 // Create a CaseBlock record representing a conditional branch to
2176 // the Case's target mbb if the value being switched on SV is equal
2177 // to C.
2178 MachineBasicBlock *CurBlock = CR.CaseBB;
2179 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2180 MachineBasicBlock *FallThrough;
2181 if (I != E-1) {
2182 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2183 CurMF->insert(BBI, FallThrough);
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002184
2185 // Put SV in a virtual register to make it available from the new blocks.
2186 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002187 } else {
2188 // If the last case doesn't match, go to the default block.
2189 FallThrough = Default;
2190 }
2191
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002192 const Value *RHS, *LHS, *MHS;
Dan Gohman575fad32008-09-03 16:12:24 +00002193 ISD::CondCode CC;
2194 if (I->High == I->Low) {
2195 // This is just small small case range :) containing exactly 1 case
2196 CC = ISD::SETEQ;
2197 LHS = SV; RHS = I->High; MHS = NULL;
2198 } else {
Bob Wilsone4077362013-09-09 19:14:35 +00002199 CC = ISD::SETLE;
Dan Gohman575fad32008-09-03 16:12:24 +00002200 LHS = I->Low; MHS = SV; RHS = I->High;
2201 }
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002202
Manman Rencf104462012-08-24 18:14:27 +00002203 // The false weight should be sum of all un-handled cases.
2204 UnhandledWeights -= I->ExtraWeight;
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002205 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2206 /* me */ CurBlock,
Manman Rencf104462012-08-24 18:14:27 +00002207 /* trueweight */ I->ExtraWeight,
2208 /* falseweight */ UnhandledWeights);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002209
Dan Gohman575fad32008-09-03 16:12:24 +00002210 // If emitting the first comparison, just call visitSwitchCase to emit the
2211 // code into the current block. Otherwise, push the CaseBlock onto the
2212 // vector to be later processed by SDISel, and insert the node's MBB
2213 // before the next MBB.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002214 if (CurBlock == SwitchBB)
2215 visitSwitchCase(CB, SwitchBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002216 else
2217 SwitchCases.push_back(CB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002218
Dan Gohman575fad32008-09-03 16:12:24 +00002219 CurBlock = FallThrough;
2220 }
2221
2222 return true;
2223}
2224
2225static inline bool areJTsAllowed(const TargetLowering &TLI) {
Evan Cheng39e90022012-07-02 22:39:56 +00002226 return TLI.supportJumpTables() &&
Owen Anderson9f944592009-08-11 20:47:22 +00002227 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2228 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohman575fad32008-09-03 16:12:24 +00002229}
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002230
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002231static APInt ComputeRange(const APInt &First, const APInt &Last) {
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002232 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
Bob Wilsone4077362013-09-09 19:14:35 +00002233 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002234 return (LastExt - FirstExt + 1ULL);
2235}
2236
Dan Gohman575fad32008-09-03 16:12:24 +00002237/// handleJTSwitchCase - Emit jumptable for current switch case range
Chris Lattnere74e0c82011-09-09 22:06:59 +00002238bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2239 CaseRecVector &WorkList,
2240 const Value *SV,
2241 MachineBasicBlock *Default,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002242 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002243 Case& FrontCase = *CR.Range.first;
2244 Case& BackCase = *(CR.Range.second-1);
2245
Chris Lattner8e1d7222009-11-07 07:50:34 +00002246 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2247 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00002248
Chris Lattner8e1d7222009-11-07 07:50:34 +00002249 APInt TSize(First.getBitWidth(), 0);
Chris Lattnere74e0c82011-09-09 22:06:59 +00002250 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
Dan Gohman575fad32008-09-03 16:12:24 +00002251 TSize += I->size();
2252
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002253 const TargetLowering *TLI = TM.getTargetLowering();
2254 if (!areJTsAllowed(*TLI) || TSize.ult(TLI->getMinimumJumpTableEntries()))
Dan Gohman575fad32008-09-03 16:12:24 +00002255 return false;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002256
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002257 APInt Range = ComputeRange(First, Last);
Jakob Stoklund Olesene8261a22011-10-26 01:47:48 +00002258 // The density is TSize / Range. Require at least 40%.
2259 // It should not be possible for IntTSize to saturate for sane code, but make
2260 // sure we handle Range saturation correctly.
2261 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2262 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2263 if (IntTSize * 10 < IntRange * 4)
Dan Gohman575fad32008-09-03 16:12:24 +00002264 return false;
2265
David Greene5730f202010-01-05 01:24:57 +00002266 DEBUG(dbgs() << "Lowering jump table\n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002267 << "First entry: " << First << ". Last entry: " << Last << '\n'
Jakob Stoklund Olesene8261a22011-10-26 01:47:48 +00002268 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
Dan Gohman575fad32008-09-03 16:12:24 +00002269
2270 // Get the MachineFunction which holds the current MBB. This is used when
2271 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002272 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002273
2274 // Figure out which block is immediately after the current one.
Dan Gohman575fad32008-09-03 16:12:24 +00002275 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands3ee3c172009-09-06 18:03:32 +00002276 ++BBI;
Dan Gohman575fad32008-09-03 16:12:24 +00002277
2278 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2279
2280 // Create a new basic block to hold the code for loading the address
2281 // of the jump table, and jumping to it. Update successor information;
2282 // we will either branch to the default case for the switch, or the jump
2283 // table.
2284 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2285 CurMF->insert(BBI, JumpTableBB);
Jakub Staszak12a43bd2011-06-16 20:22:37 +00002286
2287 addSuccessorWithWeight(CR.CaseBB, Default);
2288 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002289
Dan Gohman575fad32008-09-03 16:12:24 +00002290 // Build a vector of destination BBs, corresponding to each target
2291 // of the jump table. If the value of the jump table slot corresponds to
2292 // a case statement, push the case's BB onto the vector, otherwise, push
2293 // the default BB.
2294 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002295 APInt TEI = First;
Dan Gohman575fad32008-09-03 16:12:24 +00002296 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Chris Lattnerb6db2c62010-01-25 23:26:13 +00002297 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2298 const APInt &High = cast<ConstantInt>(I->High)->getValue();
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002299
Bob Wilsone4077362013-09-09 19:14:35 +00002300 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002301 DestBBs.push_back(I->BB);
2302 if (TEI==High)
2303 ++I;
2304 } else {
2305 DestBBs.push_back(Default);
2306 }
2307 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002308
Manman Rencf104462012-08-24 18:14:27 +00002309 // Calculate weight for each unique destination in CR.
2310 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2311 if (FuncInfo.BPI)
2312 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2313 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2314 DestWeights.find(I->BB);
Stephen Lincfe7f352013-07-08 00:37:03 +00002315 if (Itr != DestWeights.end())
Manman Rencf104462012-08-24 18:14:27 +00002316 Itr->second += I->ExtraWeight;
2317 else
2318 DestWeights[I->BB] = I->ExtraWeight;
2319 }
2320
Dan Gohman575fad32008-09-03 16:12:24 +00002321 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002322 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2323 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohman575fad32008-09-03 16:12:24 +00002324 E = DestBBs.end(); I != E; ++I) {
2325 if (!SuccsHandled[(*I)->getNumber()]) {
2326 SuccsHandled[(*I)->getNumber()] = true;
Manman Rencf104462012-08-24 18:14:27 +00002327 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2328 DestWeights.find(*I);
2329 addSuccessorWithWeight(JumpTableBB, *I,
2330 Itr != DestWeights.end() ? Itr->second : 0);
Dan Gohman575fad32008-09-03 16:12:24 +00002331 }
2332 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002333
Bob Wilson3c7cde42010-03-18 18:42:41 +00002334 // Create a jump table index for this jump table.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002335 unsigned JTEncoding = TLI->getJumpTableEncoding();
Chris Lattnerb6db2c62010-01-25 23:26:13 +00002336 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
Bob Wilson3c7cde42010-03-18 18:42:41 +00002337 ->createJumpTableIndex(DestBBs);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002338
Dan Gohman575fad32008-09-03 16:12:24 +00002339 // Set the jump table information so that we can codegen it as a second
2340 // MachineBasicBlock
2341 JumpTable JT(-1U, JTI, JumpTableBB, Default);
Dan Gohman7c0303a2010-04-19 22:41:47 +00002342 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2343 if (CR.CaseBB == SwitchBB)
2344 visitJumpTableHeader(JT, JTH, SwitchBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002345
Dan Gohman575fad32008-09-03 16:12:24 +00002346 JTCases.push_back(JumpTableBlock(JTH, JT));
Dan Gohman575fad32008-09-03 16:12:24 +00002347 return true;
2348}
2349
2350/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2351/// 2 subtrees.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002352bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2353 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002354 const Value* SV,
Stephen Lin6d715e82013-07-06 21:44:25 +00002355 MachineBasicBlock* Default,
2356 MachineBasicBlock* SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002357 // Get the MachineFunction which holds the current MBB. This is used when
2358 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002359 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002360
2361 // Figure out which block is immediately after the current one.
Dan Gohman575fad32008-09-03 16:12:24 +00002362 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands3ee3c172009-09-06 18:03:32 +00002363 ++BBI;
Dan Gohman575fad32008-09-03 16:12:24 +00002364
2365 Case& FrontCase = *CR.Range.first;
2366 Case& BackCase = *(CR.Range.second-1);
2367 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2368
2369 // Size is the number of Cases represented by this range.
2370 unsigned Size = CR.Range.second - CR.Range.first;
2371
Chris Lattner8e1d7222009-11-07 07:50:34 +00002372 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2373 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00002374 double FMetric = 0;
2375 CaseItr Pivot = CR.Range.first + Size/2;
2376
2377 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2378 // (heuristically) allow us to emit JumpTable's later.
Chris Lattner8e1d7222009-11-07 07:50:34 +00002379 APInt TSize(First.getBitWidth(), 0);
Dan Gohman575fad32008-09-03 16:12:24 +00002380 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2381 I!=E; ++I)
2382 TSize += I->size();
2383
Chris Lattner8e1d7222009-11-07 07:50:34 +00002384 APInt LSize = FrontCase.size();
2385 APInt RSize = TSize-LSize;
David Greene5730f202010-01-05 01:24:57 +00002386 DEBUG(dbgs() << "Selecting best pivot: \n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002387 << "First: " << First << ", Last: " << Last <<'\n'
2388 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002389 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2390 J!=E; ++I, ++J) {
Chris Lattner8e1d7222009-11-07 07:50:34 +00002391 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2392 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002393 APInt Range = ComputeRange(LEnd, RBegin);
Stepan Dyatkovskiye01e9862012-05-15 06:50:18 +00002394 assert((Range - 2ULL).isNonNegative() &&
2395 "Invalid case distance");
Chris Lattnercfe5aa62011-04-09 06:57:13 +00002396 // Use volatile double here to avoid excess precision issues on some hosts,
2397 // e.g. that use 80-bit X87 registers.
2398 volatile double LDensity =
2399 (double)LSize.roundToDouble() /
Chris Lattner8e1d7222009-11-07 07:50:34 +00002400 (LEnd - First + 1ULL).roundToDouble();
Chris Lattnercfe5aa62011-04-09 06:57:13 +00002401 volatile double RDensity =
2402 (double)RSize.roundToDouble() /
Chris Lattner8e1d7222009-11-07 07:50:34 +00002403 (Last - RBegin + 1ULL).roundToDouble();
Rafael Espindolad50dbc72013-12-05 04:14:33 +00002404 volatile double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohman575fad32008-09-03 16:12:24 +00002405 // Should always split in some non-trivial place
David Greene5730f202010-01-05 01:24:57 +00002406 DEBUG(dbgs() <<"=>Step\n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002407 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2408 << "LDensity: " << LDensity
2409 << ", RDensity: " << RDensity << '\n'
2410 << "Metric: " << Metric << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002411 if (FMetric < Metric) {
2412 Pivot = J;
2413 FMetric = Metric;
David Greene5730f202010-01-05 01:24:57 +00002414 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002415 }
2416
2417 LSize += J->size();
2418 RSize -= J->size();
2419 }
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002420
2421 const TargetLowering *TLI = TM.getTargetLowering();
2422 if (areJTsAllowed(*TLI)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002423 // If our case is dense we *really* should handle it earlier!
2424 assert((FMetric > 0) && "Should handle dense range earlier!");
2425 } else {
2426 Pivot = CR.Range.first + Size/2;
2427 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002428
Dan Gohman575fad32008-09-03 16:12:24 +00002429 CaseRange LHSR(CR.Range.first, Pivot);
2430 CaseRange RHSR(Pivot, CR.Range.second);
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002431 const Constant *C = Pivot->Low;
Dan Gohman575fad32008-09-03 16:12:24 +00002432 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002433
Dan Gohman575fad32008-09-03 16:12:24 +00002434 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002435 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohman575fad32008-09-03 16:12:24 +00002436 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002437 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohman575fad32008-09-03 16:12:24 +00002438 // Pivot's Value, then we can branch directly to the LHS's Target,
2439 // rather than creating a leaf node for it.
2440 if ((LHSR.second - LHSR.first) == 1 &&
2441 LHSR.first->High == CR.GE &&
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002442 cast<ConstantInt>(C)->getValue() ==
2443 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002444 TrueBB = LHSR.first->BB;
2445 } else {
2446 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2447 CurMF->insert(BBI, TrueBB);
2448 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002449
2450 // Put SV in a virtual register to make it available from the new blocks.
2451 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002452 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002453
Dan Gohman575fad32008-09-03 16:12:24 +00002454 // Similar to the optimization above, if the Value being switched on is
2455 // known to be less than the Constant CR.LT, and the current Case Value
2456 // is CR.LT - 1, then we can branch directly to the target block for
2457 // the current Case Value, rather than emitting a RHS leaf node for it.
2458 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002459 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2460 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002461 FalseBB = RHSR.first->BB;
2462 } else {
2463 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2464 CurMF->insert(BBI, FalseBB);
2465 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002466
2467 // Put SV in a virtual register to make it available from the new blocks.
2468 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002469 }
2470
2471 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002472 // the LHS node if the value being switched on SV is less than C.
Dan Gohman575fad32008-09-03 16:12:24 +00002473 // Otherwise, branch to LHS.
Bob Wilsone4077362013-09-09 19:14:35 +00002474 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002475
Dan Gohman7c0303a2010-04-19 22:41:47 +00002476 if (CR.CaseBB == SwitchBB)
2477 visitSwitchCase(CB, SwitchBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002478 else
2479 SwitchCases.push_back(CB);
2480
2481 return true;
2482}
2483
2484/// handleBitTestsSwitchCase - if current case range has few destination and
2485/// range span less, than machine word bitwidth, encode case range into series
2486/// of masks and emit bit tests with these masks.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002487bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2488 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002489 const Value* SV,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002490 MachineBasicBlock* Default,
Stephen Lin6d715e82013-07-06 21:44:25 +00002491 MachineBasicBlock* SwitchBB) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002492 const TargetLowering *TLI = TM.getTargetLowering();
2493 EVT PTy = TLI->getPointerTy();
Owen Andersonc30530d2009-08-10 18:56:59 +00002494 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohman575fad32008-09-03 16:12:24 +00002495
2496 Case& FrontCase = *CR.Range.first;
2497 Case& BackCase = *(CR.Range.second-1);
2498
2499 // Get the MachineFunction which holds the current MBB. This is used when
2500 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002501 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002502
Anton Korobeynikovc94dbf52009-05-08 18:51:34 +00002503 // If target does not have legal shift left, do not emit bit tests at all.
Matt Arsenaultbbd24902013-10-21 19:24:15 +00002504 if (!TLI->isOperationLegal(ISD::SHL, PTy))
Anton Korobeynikovc94dbf52009-05-08 18:51:34 +00002505 return false;
2506
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002507 size_t numCmps = 0;
Dan Gohman575fad32008-09-03 16:12:24 +00002508 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2509 I!=E; ++I) {
2510 // Single case counts one, case range - two.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002511 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohman575fad32008-09-03 16:12:24 +00002512 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002513
Dan Gohman575fad32008-09-03 16:12:24 +00002514 // Count unique destinations
2515 SmallSet<MachineBasicBlock*, 4> Dests;
2516 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2517 Dests.insert(I->BB);
2518 if (Dests.size() > 3)
2519 // Don't bother the code below, if there are too much unique destinations
2520 return false;
2521 }
David Greene5730f202010-01-05 01:24:57 +00002522 DEBUG(dbgs() << "Total number of unique destinations: "
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00002523 << Dests.size() << '\n'
2524 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002525
Dan Gohman575fad32008-09-03 16:12:24 +00002526 // Compute span of values.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002527 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2528 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002529 APInt cmpRange = maxValue - minValue;
2530
David Greene5730f202010-01-05 01:24:57 +00002531 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002532 << "Low bound: " << minValue << '\n'
2533 << "High bound: " << maxValue << '\n');
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002534
Dan Gohman4ce1fb12010-04-08 23:03:40 +00002535 if (cmpRange.uge(IntPtrBits) ||
Dan Gohman575fad32008-09-03 16:12:24 +00002536 (!(Dests.size() == 1 && numCmps >= 3) &&
2537 !(Dests.size() == 2 && numCmps >= 5) &&
2538 !(Dests.size() >= 3 && numCmps >= 6)))
2539 return false;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002540
David Greene5730f202010-01-05 01:24:57 +00002541 DEBUG(dbgs() << "Emitting bit tests\n");
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002542 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2543
Dan Gohman575fad32008-09-03 16:12:24 +00002544 // Optimize the case where all the case values fit in a
2545 // word without having to subtract minValue. In this case,
2546 // we can optimize away the subtraction.
Bob Wilsone4077362013-09-09 19:14:35 +00002547 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002548 cmpRange = maxValue;
Dan Gohman575fad32008-09-03 16:12:24 +00002549 } else {
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002550 lowBound = minValue;
Dan Gohman575fad32008-09-03 16:12:24 +00002551 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002552
Dan Gohman575fad32008-09-03 16:12:24 +00002553 CaseBitsVector CasesBits;
2554 unsigned i, count = 0;
2555
2556 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2557 MachineBasicBlock* Dest = I->BB;
2558 for (i = 0; i < count; ++i)
2559 if (Dest == CasesBits[i].BB)
2560 break;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002561
Dan Gohman575fad32008-09-03 16:12:24 +00002562 if (i == count) {
2563 assert((count < 3) && "Too much destinations to test!");
Manman Rencf104462012-08-24 18:14:27 +00002564 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
Dan Gohman575fad32008-09-03 16:12:24 +00002565 count++;
2566 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002567
2568 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2569 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2570
2571 uint64_t lo = (lowValue - lowBound).getZExtValue();
2572 uint64_t hi = (highValue - lowBound).getZExtValue();
Manman Rencf104462012-08-24 18:14:27 +00002573 CasesBits[i].ExtraWeight += I->ExtraWeight;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002574
Dan Gohman575fad32008-09-03 16:12:24 +00002575 for (uint64_t j = lo; j <= hi; j++) {
2576 CasesBits[i].Mask |= 1ULL << j;
2577 CasesBits[i].Bits++;
2578 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002579
Dan Gohman575fad32008-09-03 16:12:24 +00002580 }
2581 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002582
Dan Gohman575fad32008-09-03 16:12:24 +00002583 BitTestInfo BTC;
2584
2585 // Figure out which block is immediately after the current one.
2586 MachineFunction::iterator BBI = CR.CaseBB;
2587 ++BBI;
2588
2589 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2590
David Greene5730f202010-01-05 01:24:57 +00002591 DEBUG(dbgs() << "Cases:\n");
Dan Gohman575fad32008-09-03 16:12:24 +00002592 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
David Greene5730f202010-01-05 01:24:57 +00002593 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002594 << ", Bits: " << CasesBits[i].Bits
2595 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002596
2597 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2598 CurMF->insert(BBI, CaseBB);
2599 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2600 CaseBB,
Manman Rencf104462012-08-24 18:14:27 +00002601 CasesBits[i].BB, CasesBits[i].ExtraWeight));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002602
2603 // Put SV in a virtual register to make it available from the new blocks.
2604 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002605 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002606
2607 BitTestBlock BTB(lowBound, cmpRange, SV,
Evan Chengac730dd2011-01-06 01:02:44 +00002608 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
Dan Gohman575fad32008-09-03 16:12:24 +00002609 CR.CaseBB, Default, BTC);
2610
Dan Gohman7c0303a2010-04-19 22:41:47 +00002611 if (CR.CaseBB == SwitchBB)
2612 visitBitTestHeader(BTB, SwitchBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002613
Dan Gohman575fad32008-09-03 16:12:24 +00002614 BitTestCases.push_back(BTB);
2615
2616 return true;
2617}
2618
Dan Gohman575fad32008-09-03 16:12:24 +00002619/// Clusterify - Transform simple list of Cases into list of CaseRange's
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002620size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2621 const SwitchInst& SI) {
Bob Wilsone4077362013-09-09 19:14:35 +00002622 size_t numCmps = 0;
Dan Gohman575fad32008-09-03 16:12:24 +00002623
Manman Rencf104462012-08-24 18:14:27 +00002624 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Dan Gohman575fad32008-09-03 16:12:24 +00002625 // Start with "simple" cases
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002626 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002627 i != e; ++i) {
2628 const BasicBlock *SuccBB = i.getCaseSuccessor();
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002629 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2630
Bob Wilsone4077362013-09-09 19:14:35 +00002631 uint32_t ExtraWeight =
2632 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2633
2634 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2635 SMBB, ExtraWeight));
Dan Gohman575fad32008-09-03 16:12:24 +00002636 }
Bob Wilsone4077362013-09-09 19:14:35 +00002637 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Stephen Lincfe7f352013-07-08 00:37:03 +00002638
Bob Wilsone4077362013-09-09 19:14:35 +00002639 // Merge case into clusters
2640 if (Cases.size() >= 2)
2641 // Must recompute end() each iteration because it may be
2642 // invalidated by erase if we hold on to it
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002643 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
Bob Wilsone4077362013-09-09 19:14:35 +00002644 J != Cases.end(); ) {
2645 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2646 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2647 MachineBasicBlock* nextBB = J->BB;
2648 MachineBasicBlock* currentBB = I->BB;
Stephen Lincfe7f352013-07-08 00:37:03 +00002649
Bob Wilsone4077362013-09-09 19:14:35 +00002650 // If the two neighboring cases go to the same destination, merge them
2651 // into a single case.
2652 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2653 I->High = J->High;
2654 I->ExtraWeight += J->ExtraWeight;
2655 J = Cases.erase(J);
2656 } else {
2657 I = J++;
2658 }
2659 }
Dan Gohman575fad32008-09-03 16:12:24 +00002660
Bob Wilsone4077362013-09-09 19:14:35 +00002661 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2662 if (I->Low != I->High)
2663 // A range counts double, since it requires two compares.
2664 ++numCmps;
Dan Gohman575fad32008-09-03 16:12:24 +00002665 }
2666
2667 return numCmps;
2668}
2669
Jakob Stoklund Olesen665aa6e2010-09-30 19:44:31 +00002670void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2671 MachineBasicBlock *Last) {
2672 // Update JTCases.
2673 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2674 if (JTCases[i].first.HeaderBB == First)
2675 JTCases[i].first.HeaderBB = Last;
2676
2677 // Update BitTestCases.
2678 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2679 if (BitTestCases[i].Parent == First)
2680 BitTestCases[i].Parent = Last;
2681}
2682
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002683void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00002684 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002685
Dan Gohman575fad32008-09-03 16:12:24 +00002686 // Figure out which block is immediately after the current one.
2687 MachineBasicBlock *NextBlock = 0;
Dan Gohman575fad32008-09-03 16:12:24 +00002688 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2689
2690 // If there is only the default destination, branch to it if it is not the
2691 // next basic block. Otherwise, just fall through.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002692 if (!SI.getNumCases()) {
Dan Gohman575fad32008-09-03 16:12:24 +00002693 // Update machine-CFG edges.
2694
2695 // If this is not a fall-through branch, emit the branch.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002696 SwitchMBB->addSuccessor(Default);
Bill Wendling954cb182010-01-28 21:51:40 +00002697 if (Default != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002698 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002699 MVT::Other, getControlRoot(),
2700 DAG.getBasicBlock(Default)));
Bill Wendling443d0722009-12-21 22:30:11 +00002701
Dan Gohman575fad32008-09-03 16:12:24 +00002702 return;
2703 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002704
Dan Gohman575fad32008-09-03 16:12:24 +00002705 // If there are any non-default case statements, create a vector of Cases
2706 // representing each one, and sort the vector so that we can efficiently
2707 // create a binary search tree from them.
2708 CaseVector Cases;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002709 size_t numCmps = Clusterify(Cases, SI);
David Greene5730f202010-01-05 01:24:57 +00002710 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002711 << ". Total compares: " << numCmps << '\n');
Duncan Sandsd278d352011-10-18 12:44:00 +00002712 (void)numCmps;
Dan Gohman575fad32008-09-03 16:12:24 +00002713
2714 // Get the Value to be switched on and default basic blocks, which will be
2715 // inserted into CaseBlock records, representing basic blocks in the binary
2716 // search tree.
Eli Friedman95031ed2011-09-29 20:21:17 +00002717 const Value *SV = SI.getCondition();
Dan Gohman575fad32008-09-03 16:12:24 +00002718
2719 // Push the initial CaseRec onto the worklist
2720 CaseRecVector WorkList;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002721 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2722 CaseRange(Cases.begin(),Cases.end())));
Dan Gohman575fad32008-09-03 16:12:24 +00002723
2724 while (!WorkList.empty()) {
2725 // Grab a record representing a case range to process off the worklist
2726 CaseRec CR = WorkList.back();
2727 WorkList.pop_back();
2728
Dan Gohman7c0303a2010-04-19 22:41:47 +00002729 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002730 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002731
Dan Gohman575fad32008-09-03 16:12:24 +00002732 // If the range has few cases (two or less) emit a series of specific
2733 // tests.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002734 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002735 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002736
Sebastian Popedb31fa2012-09-25 20:35:36 +00002737 // If the switch has more than N blocks, and is at least 40% dense, and the
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002738 // target supports indirect branches, then emit a jump table rather than
Dan Gohman575fad32008-09-03 16:12:24 +00002739 // lowering the switch to a binary tree of conditional branches.
Sebastian Popedb31fa2012-09-25 20:35:36 +00002740 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
Dan Gohman7c0303a2010-04-19 22:41:47 +00002741 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002742 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002743
Dan Gohman575fad32008-09-03 16:12:24 +00002744 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2745 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002746 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002747 }
2748}
2749
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002750void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00002751 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002752
Jakob Stoklund Olesen896428d2010-02-11 00:34:18 +00002753 // Update machine-CFG edges with unique successors.
Nadav Rotem33e034a2012-10-23 21:05:33 +00002754 SmallSet<BasicBlock*, 32> Done;
2755 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2756 BasicBlock *BB = I.getSuccessor(i);
2757 bool Inserted = Done.insert(BB);
2758 if (!Inserted)
2759 continue;
2760
2761 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
Jakub Staszak12a43bd2011-06-16 20:22:37 +00002762 addSuccessorWithWeight(IndirectBrMBB, Succ);
2763 }
Dan Gohmana5e078b2009-10-27 22:10:34 +00002764
Andrew Trickef9de2a2013-05-25 02:42:55 +00002765 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002766 MVT::Other, getControlRoot(),
2767 getValue(I.getAddress())));
Bill Wendling443d0722009-12-21 22:30:11 +00002768}
Dan Gohman575fad32008-09-03 16:12:24 +00002769
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002770void SelectionDAGBuilder::visitFSub(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002771 // -0.0 - X --> fneg
Chris Lattner229907c2011-07-18 04:54:35 +00002772 Type *Ty = I.getType();
Chris Lattner69229312011-02-15 00:14:00 +00002773 if (isa<Constant>(I.getOperand(0)) &&
2774 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2775 SDValue Op2 = getValue(I.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002776 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
Chris Lattner69229312011-02-15 00:14:00 +00002777 Op2.getValueType(), Op2));
2778 return;
Dan Gohman575fad32008-09-03 16:12:24 +00002779 }
Bill Wendling443d0722009-12-21 22:30:11 +00002780
Dan Gohmana5b96452009-06-04 22:49:04 +00002781 visitBinary(I, ISD::FSUB);
Dan Gohman575fad32008-09-03 16:12:24 +00002782}
2783
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002784void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
Dan Gohman575fad32008-09-03 16:12:24 +00002785 SDValue Op1 = getValue(I.getOperand(0));
2786 SDValue Op2 = getValue(I.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002787 setValue(&I, DAG.getNode(OpCode, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002788 Op1.getValueType(), Op1, Op2));
Dan Gohman575fad32008-09-03 16:12:24 +00002789}
2790
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002791void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
Dan Gohman575fad32008-09-03 16:12:24 +00002792 SDValue Op1 = getValue(I.getOperand(0));
2793 SDValue Op2 = getValue(I.getOperand(1));
Owen Andersonb2c80da2011-02-25 21:41:48 +00002794
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002795 EVT ShiftTy = TM.getTargetLowering()->getShiftAmountTy(Op2.getValueType());
Owen Andersonb2c80da2011-02-25 21:41:48 +00002796
Chris Lattner2a720d92011-02-13 09:02:52 +00002797 // Coerce the shift amount to the right type if we can.
2798 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
Chris Lattnerd5f0b112011-02-13 09:10:56 +00002799 unsigned ShiftSize = ShiftTy.getSizeInBits();
2800 unsigned Op2Size = Op2.getValueType().getSizeInBits();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002801 SDLoc DL = getCurSDLoc();
Owen Andersonb2c80da2011-02-25 21:41:48 +00002802
Dan Gohman0e8d1992009-04-09 03:51:29 +00002803 // If the operand is smaller than the shift count type, promote it.
Chris Lattner2a720d92011-02-13 09:02:52 +00002804 if (ShiftSize > Op2Size)
2805 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002806
Dan Gohman0e8d1992009-04-09 03:51:29 +00002807 // If the operand is larger than the shift count type but the shift
2808 // count type has enough bits to represent any shift value, truncate
2809 // it now. This is a common case and it exposes the truncate to
2810 // optimization early.
Chris Lattner2a720d92011-02-13 09:02:52 +00002811 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2812 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2813 // Otherwise we'll need to temporarily settle for some other convenient
Chris Lattnere95d1952011-02-13 19:09:16 +00002814 // type. Type legalization will make adjustments once the shiftee is split.
Chris Lattner2a720d92011-02-13 09:02:52 +00002815 else
Chris Lattnere95d1952011-02-13 19:09:16 +00002816 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
Dan Gohman575fad32008-09-03 16:12:24 +00002817 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002818
Andrew Trickef9de2a2013-05-25 02:42:55 +00002819 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002820 Op1.getValueType(), Op1, Op2));
Dan Gohman575fad32008-09-03 16:12:24 +00002821}
2822
Benjamin Kramer9960a252011-07-08 10:31:30 +00002823void SelectionDAGBuilder::visitSDiv(const User &I) {
Benjamin Kramer9960a252011-07-08 10:31:30 +00002824 SDValue Op1 = getValue(I.getOperand(0));
2825 SDValue Op2 = getValue(I.getOperand(1));
2826
2827 // Turn exact SDivs into multiplications.
2828 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2829 // exact bit.
Benjamin Kramer2bb8b262011-07-08 12:08:24 +00002830 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2831 !isa<ConstantSDNode>(Op1) &&
Benjamin Kramer9960a252011-07-08 10:31:30 +00002832 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002833 setValue(&I, TM.getTargetLowering()->BuildExactSDIV(Op1, Op2,
2834 getCurSDLoc(), DAG));
Benjamin Kramer9960a252011-07-08 10:31:30 +00002835 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00002836 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
Benjamin Kramer9960a252011-07-08 10:31:30 +00002837 Op1, Op2));
2838}
2839
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002840void SelectionDAGBuilder::visitICmp(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002841 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002842 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002843 predicate = IC->getPredicate();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002844 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002845 predicate = ICmpInst::Predicate(IC->getPredicate());
2846 SDValue Op1 = getValue(I.getOperand(0));
2847 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman293abcc2008-10-17 18:18:45 +00002848 ISD::CondCode Opcode = getICmpCondCode(predicate);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00002849
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002850 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002851 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohman575fad32008-09-03 16:12:24 +00002852}
2853
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002854void SelectionDAGBuilder::visitFCmp(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002855 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002856 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002857 predicate = FC->getPredicate();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002858 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002859 predicate = FCmpInst::Predicate(FC->getPredicate());
2860 SDValue Op1 = getValue(I.getOperand(0));
2861 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman293abcc2008-10-17 18:18:45 +00002862 ISD::CondCode Condition = getFCmpCondCode(predicate);
Nick Lewycky50f02cb2011-12-02 22:16:29 +00002863 if (TM.Options.NoNaNsFPMath)
2864 Condition = getFCmpCodeWithoutNaN(Condition);
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002865 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002866 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
Dan Gohman575fad32008-09-03 16:12:24 +00002867}
2868
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002869void SelectionDAGBuilder::visitSelect(const User &I) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002870 SmallVector<EVT, 4> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002871 ComputeValueVTs(*TM.getTargetLowering(), I.getType(), ValueVTs);
Dan Gohman8b44b882008-10-21 20:00:42 +00002872 unsigned NumValues = ValueVTs.size();
Bill Wendling443d0722009-12-21 22:30:11 +00002873 if (NumValues == 0) return;
Dan Gohman8b44b882008-10-21 20:00:42 +00002874
Bill Wendling443d0722009-12-21 22:30:11 +00002875 SmallVector<SDValue, 4> Values(NumValues);
2876 SDValue Cond = getValue(I.getOperand(0));
2877 SDValue TrueVal = getValue(I.getOperand(1));
2878 SDValue FalseVal = getValue(I.getOperand(2));
Duncan Sandsf2641e12011-09-06 19:07:46 +00002879 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2880 ISD::VSELECT : ISD::SELECT;
Dan Gohman8b44b882008-10-21 20:00:42 +00002881
Bill Wendling954cb182010-01-28 21:51:40 +00002882 for (unsigned i = 0; i != NumValues; ++i)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002883 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
Duncan Sandsf2641e12011-09-06 19:07:46 +00002884 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
Chris Lattner53ebf8a2010-03-12 07:15:36 +00002885 Cond,
Bill Wendling443d0722009-12-21 22:30:11 +00002886 SDValue(TrueVal.getNode(),
2887 TrueVal.getResNo() + i),
2888 SDValue(FalseVal.getNode(),
2889 FalseVal.getResNo() + i));
2890
Andrew Trickef9de2a2013-05-25 02:42:55 +00002891 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002892 DAG.getVTList(&ValueVTs[0], NumValues),
2893 &Values[0], NumValues));
Bill Wendling443d0722009-12-21 22:30:11 +00002894}
Dan Gohman575fad32008-09-03 16:12:24 +00002895
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002896void SelectionDAGBuilder::visitTrunc(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002897 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2898 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002899 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002900 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002901}
2902
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002903void SelectionDAGBuilder::visitZExt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002904 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2905 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2906 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002907 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002908 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002909}
2910
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002911void SelectionDAGBuilder::visitSExt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002912 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2913 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2914 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002915 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002916 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002917}
2918
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002919void SelectionDAGBuilder::visitFPTrunc(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002920 // FPTrunc is never a no-op cast, no need to check
2921 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002922 const TargetLowering *TLI = TM.getTargetLowering();
2923 EVT DestVT = TLI->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002924 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(),
Pete Coopere3d305a2012-01-17 01:54:07 +00002925 DestVT, N,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002926 DAG.getTargetConstant(0, TLI->getPointerTy())));
Dan Gohman575fad32008-09-03 16:12:24 +00002927}
2928
Stephen Lin6d715e82013-07-06 21:44:25 +00002929void SelectionDAGBuilder::visitFPExt(const User &I) {
Hal Finkelbab66782011-10-18 03:51:57 +00002930 // FPExt is never a no-op cast, no need to check
Dan Gohman575fad32008-09-03 16:12:24 +00002931 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002932 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002933 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002934}
2935
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002936void SelectionDAGBuilder::visitFPToUI(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002937 // FPToUI is never a no-op cast, no need to check
2938 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002939 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002940 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002941}
2942
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002943void SelectionDAGBuilder::visitFPToSI(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002944 // FPToSI is never a no-op cast, no need to check
2945 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002946 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002947 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002948}
2949
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002950void SelectionDAGBuilder::visitUIToFP(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002951 // UIToFP is never a no-op cast, no need to check
2952 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002953 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002954 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002955}
2956
Stephen Lin6d715e82013-07-06 21:44:25 +00002957void SelectionDAGBuilder::visitSIToFP(const User &I) {
Bill Wendling6c87bfc2008-10-19 20:34:04 +00002958 // SIToFP is never a no-op cast, no need to check
Dan Gohman575fad32008-09-03 16:12:24 +00002959 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002960 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002961 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002962}
2963
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002964void SelectionDAGBuilder::visitPtrToInt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002965 // What to do depends on the size of the integer and the size of the pointer.
2966 // We can either truncate, zero extend, or no-op, accordingly.
2967 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002968 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002969 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
Dan Gohman575fad32008-09-03 16:12:24 +00002970}
2971
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002972void SelectionDAGBuilder::visitIntToPtr(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002973 // What to do depends on the size of the integer and the size of the pointer.
2974 // We can either truncate, zero extend, or no-op, accordingly.
2975 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002976 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002977 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
Dan Gohman575fad32008-09-03 16:12:24 +00002978}
2979
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002980void SelectionDAGBuilder::visitBitCast(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002981 SDValue N = getValue(I.getOperand(0));
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002982 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
Dan Gohman575fad32008-09-03 16:12:24 +00002983
Bill Wendling443d0722009-12-21 22:30:11 +00002984 // BitCast assures us that source and destination are the same size so this is
Wesley Peck527da1b2010-11-23 03:31:01 +00002985 // either a BITCAST or a no-op.
Bill Wendling954cb182010-01-28 21:51:40 +00002986 if (DestVT != N.getValueType())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002987 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002988 DestVT, N)); // convert types.
Juergen Ributzka2b97f9b2014-02-13 04:19:26 +00002989 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
2990 // might fold any kind of constant expression to an integer constant and that
2991 // is not what we are looking for. Only regcognize a bitcast of a genuine
2992 // constant integer as an opaque constant.
2993 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
2994 setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
2995 /*isOpaque*/true));
Bill Wendling954cb182010-01-28 21:51:40 +00002996 else
Bill Wendling443d0722009-12-21 22:30:11 +00002997 setValue(&I, N); // noop cast.
Dan Gohman575fad32008-09-03 16:12:24 +00002998}
2999
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003000void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3001 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3002 const Value *SV = I.getOperand(0);
3003 SDValue N = getValue(SV);
3004 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
3005
3006 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3007 unsigned DestAS = I.getType()->getPointerAddressSpace();
3008
3009 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3010 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3011
3012 setValue(&I, N);
3013}
3014
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003015void SelectionDAGBuilder::visitInsertElement(const User &I) {
Tom Stellardd42c5942013-08-05 22:22:01 +00003016 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +00003017 SDValue InVec = getValue(I.getOperand(0));
3018 SDValue InVal = getValue(I.getOperand(1));
Tom Stellardd42c5942013-08-05 22:22:01 +00003019 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3020 getCurSDLoc(), TLI.getVectorIdxTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003021 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003022 TM.getTargetLowering()->getValueType(I.getType()),
Bill Wendling954cb182010-01-28 21:51:40 +00003023 InVec, InVal, InIdx));
Dan Gohman575fad32008-09-03 16:12:24 +00003024}
3025
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003026void SelectionDAGBuilder::visitExtractElement(const User &I) {
Tom Stellardd42c5942013-08-05 22:22:01 +00003027 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +00003028 SDValue InVec = getValue(I.getOperand(0));
Tom Stellardd42c5942013-08-05 22:22:01 +00003029 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3030 getCurSDLoc(), TLI.getVectorIdxTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003031 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003032 TM.getTargetLowering()->getValueType(I.getType()),
3033 InVec, InIdx));
Dan Gohman575fad32008-09-03 16:12:24 +00003034}
3035
Craig Topperf726e152012-01-04 09:23:09 +00003036// Utility for visitShuffleVector - Return true if every element in Mask,
Benjamin Kramerbde91762012-06-02 10:20:22 +00003037// beginning from position Pos and ending in Pos+Size, falls within the
Craig Topperf726e152012-01-04 09:23:09 +00003038// specified sequential range [L, L+Pos). or is undef.
3039static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
Craig Topper3ef01cd2012-04-11 03:06:35 +00003040 unsigned Pos, unsigned Size, int Low) {
3041 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
Craig Topperf726e152012-01-04 09:23:09 +00003042 if (Mask[i] >= 0 && Mask[i] != Low)
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003043 return false;
Mon P Wang25f01062008-11-10 04:46:22 +00003044 return true;
3045}
3046
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003047void SelectionDAGBuilder::visitShuffleVector(const User &I) {
Mon P Wangc3113602008-11-21 04:25:21 +00003048 SDValue Src1 = getValue(I.getOperand(0));
3049 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohman575fad32008-09-03 16:12:24 +00003050
Chris Lattnercf129702012-01-26 02:51:13 +00003051 SmallVector<int, 8> Mask;
3052 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3053 unsigned MaskNumElts = Mask.size();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003054
3055 const TargetLowering *TLI = TM.getTargetLowering();
3056 EVT VT = TLI->getValueType(I.getType());
Owen Anderson53aa7a92009-08-10 22:56:29 +00003057 EVT SrcVT = Src1.getValueType();
Nate Begeman5f829d82009-04-29 05:20:52 +00003058 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wang25f01062008-11-10 04:46:22 +00003059
Mon P Wang7a824742008-11-16 05:06:27 +00003060 if (SrcNumElts == MaskNumElts) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003061 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003062 &Mask[0]));
Mon P Wang25f01062008-11-10 04:46:22 +00003063 return;
3064 }
3065
3066 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wang7a824742008-11-16 05:06:27 +00003067 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3068 // Mask is longer than the source vectors and is a multiple of the source
3069 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wangc3113602008-11-21 04:25:21 +00003070 // lengths match.
Craig Topperf726e152012-01-04 09:23:09 +00003071 if (SrcNumElts*2 == MaskNumElts) {
3072 // First check for Src1 in low and Src2 in high
3073 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3074 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3075 // The shuffle is concatenating two vectors together.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003076 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
Craig Topperf726e152012-01-04 09:23:09 +00003077 VT, Src1, Src2));
3078 return;
3079 }
3080 // Then check for Src2 in low and Src1 in high
3081 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3082 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3083 // The shuffle is concatenating two vectors together.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003084 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
Craig Topperf726e152012-01-04 09:23:09 +00003085 VT, Src2, Src1));
3086 return;
3087 }
Mon P Wang25f01062008-11-10 04:46:22 +00003088 }
3089
Mon P Wang7a824742008-11-16 05:06:27 +00003090 // Pad both vectors with undefs to make them the same length as the mask.
3091 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003092 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3093 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesen84935752009-02-06 23:05:02 +00003094 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wang25f01062008-11-10 04:46:22 +00003095
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003096 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3097 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wangc3113602008-11-21 04:25:21 +00003098 MOps1[0] = Src1;
3099 MOps2[0] = Src2;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003100
3101 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003102 getCurSDLoc(), VT,
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003103 &MOps1[0], NumConcat);
3104 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003105 getCurSDLoc(), VT,
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003106 &MOps2[0], NumConcat);
Mon P Wangc3113602008-11-21 04:25:21 +00003107
Mon P Wang25f01062008-11-10 04:46:22 +00003108 // Readjust mask for new input vector length.
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003109 SmallVector<int, 8> MappedOps;
Nate Begeman5f829d82009-04-29 05:20:52 +00003110 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003111 int Idx = Mask[i];
Craig Topper3ef01cd2012-04-11 03:06:35 +00003112 if (Idx >= (int)SrcNumElts)
3113 Idx -= SrcNumElts - MaskNumElts;
3114 MappedOps.push_back(Idx);
Mon P Wang25f01062008-11-10 04:46:22 +00003115 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003116
Andrew Trickef9de2a2013-05-25 02:42:55 +00003117 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003118 &MappedOps[0]));
Mon P Wang25f01062008-11-10 04:46:22 +00003119 return;
3120 }
3121
Mon P Wang7a824742008-11-16 05:06:27 +00003122 if (SrcNumElts > MaskNumElts) {
Mon P Wang7a824742008-11-16 05:06:27 +00003123 // Analyze the access pattern of the vector to see if we can extract
3124 // two subvectors and do the shuffle. The analysis is done by calculating
3125 // the range of elements the mask access on both vectors.
Craig Topper6148fe62012-04-08 23:15:04 +00003126 int MinRange[2] = { static_cast<int>(SrcNumElts),
3127 static_cast<int>(SrcNumElts)};
Mon P Wang7a824742008-11-16 05:06:27 +00003128 int MaxRange[2] = {-1, -1};
3129
Nate Begeman5f829d82009-04-29 05:20:52 +00003130 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003131 int Idx = Mask[i];
Craig Topper6148fe62012-04-08 23:15:04 +00003132 unsigned Input = 0;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003133 if (Idx < 0)
3134 continue;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003135
Nate Begeman5f829d82009-04-29 05:20:52 +00003136 if (Idx >= (int)SrcNumElts) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003137 Input = 1;
3138 Idx -= SrcNumElts;
Mon P Wang25f01062008-11-10 04:46:22 +00003139 }
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003140 if (Idx > MaxRange[Input])
3141 MaxRange[Input] = Idx;
3142 if (Idx < MinRange[Input])
3143 MinRange[Input] = Idx;
Mon P Wang25f01062008-11-10 04:46:22 +00003144 }
Mon P Wang25f01062008-11-10 04:46:22 +00003145
Mon P Wang7a824742008-11-16 05:06:27 +00003146 // Check if the access is smaller than the vector size and can we find
3147 // a reasonable extract index.
Craig Topper6148fe62012-04-08 23:15:04 +00003148 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3149 // Extract.
Mon P Wang7a824742008-11-16 05:06:27 +00003150 int StartIdx[2]; // StartIdx to extract from
Craig Topper6148fe62012-04-08 23:15:04 +00003151 for (unsigned Input = 0; Input < 2; ++Input) {
3152 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
Mon P Wang7a824742008-11-16 05:06:27 +00003153 RangeUse[Input] = 0; // Unused
3154 StartIdx[Input] = 0;
Craig Topperc8e2d912012-04-08 17:53:33 +00003155 continue;
Mon P Wangc3113602008-11-21 04:25:21 +00003156 }
Craig Topperc8e2d912012-04-08 17:53:33 +00003157
3158 // Find a good start index that is a multiple of the mask length. Then
3159 // see if the rest of the elements are in range.
3160 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3161 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3162 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3163 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wang7a824742008-11-16 05:06:27 +00003164 }
3165
Bill Wendlingdff54ef2009-08-21 18:16:06 +00003166 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Bill Wendling954cb182010-01-28 21:51:40 +00003167 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wang7a824742008-11-16 05:06:27 +00003168 return;
3169 }
Craig Topper6148fe62012-04-08 23:15:04 +00003170 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
Mon P Wang7a824742008-11-16 05:06:27 +00003171 // Extract appropriate subvector and generate a vector shuffle
Craig Topper6148fe62012-04-08 23:15:04 +00003172 for (unsigned Input = 0; Input < 2; ++Input) {
Bill Wendlingc6b47342009-12-21 23:47:40 +00003173 SDValue &Src = Input == 0 ? Src1 : Src2;
Bill Wendlingfff99f02009-12-21 22:42:14 +00003174 if (RangeUse[Input] == 0)
Dale Johannesen84935752009-02-06 23:05:02 +00003175 Src = DAG.getUNDEF(VT);
Bill Wendlingfff99f02009-12-21 22:42:14 +00003176 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00003177 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT,
Tom Stellardd42c5942013-08-05 22:22:01 +00003178 Src, DAG.getConstant(StartIdx[Input],
3179 TLI->getVectorIdxTy()));
Mon P Wang25f01062008-11-10 04:46:22 +00003180 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003181
Mon P Wang7a824742008-11-16 05:06:27 +00003182 // Calculate new mask.
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003183 SmallVector<int, 8> MappedOps;
Nate Begeman5f829d82009-04-29 05:20:52 +00003184 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003185 int Idx = Mask[i];
Craig Topper3ef01cd2012-04-11 03:06:35 +00003186 if (Idx >= 0) {
3187 if (Idx < (int)SrcNumElts)
3188 Idx -= StartIdx[0];
3189 else
3190 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3191 }
3192 MappedOps.push_back(Idx);
Mon P Wang7a824742008-11-16 05:06:27 +00003193 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003194
Andrew Trickef9de2a2013-05-25 02:42:55 +00003195 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003196 &MappedOps[0]));
Mon P Wang7a824742008-11-16 05:06:27 +00003197 return;
Mon P Wang25f01062008-11-10 04:46:22 +00003198 }
3199 }
3200
Mon P Wang7a824742008-11-16 05:06:27 +00003201 // We can't use either concat vectors or extract subvectors so fall back to
3202 // replacing the shuffle with extract and build vector.
3203 // to insert and build vector.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003204 EVT EltVT = VT.getVectorElementType();
Tom Stellardd42c5942013-08-05 22:22:01 +00003205 EVT IdxVT = TLI->getVectorIdxTy();
Mon P Wang25f01062008-11-10 04:46:22 +00003206 SmallVector<SDValue,8> Ops;
Nate Begeman5f829d82009-04-29 05:20:52 +00003207 for (unsigned i = 0; i != MaskNumElts; ++i) {
Craig Topper3ef01cd2012-04-11 03:06:35 +00003208 int Idx = Mask[i];
3209 SDValue Res;
3210
3211 if (Idx < 0) {
3212 Res = DAG.getUNDEF(EltVT);
Mon P Wang25f01062008-11-10 04:46:22 +00003213 } else {
Craig Topper3ef01cd2012-04-11 03:06:35 +00003214 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3215 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
Bill Wendlingfff99f02009-12-21 22:42:14 +00003216
Andrew Trickef9de2a2013-05-25 02:42:55 +00003217 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
Tom Stellardd42c5942013-08-05 22:22:01 +00003218 EltVT, Src, DAG.getConstant(Idx, IdxVT));
Mon P Wang25f01062008-11-10 04:46:22 +00003219 }
Craig Topper3ef01cd2012-04-11 03:06:35 +00003220
3221 Ops.push_back(Res);
Mon P Wang25f01062008-11-10 04:46:22 +00003222 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003223
Andrew Trickef9de2a2013-05-25 02:42:55 +00003224 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00003225 VT, &Ops[0], Ops.size()));
Dan Gohman575fad32008-09-03 16:12:24 +00003226}
3227
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003228void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003229 const Value *Op0 = I.getOperand(0);
3230 const Value *Op1 = I.getOperand(1);
Chris Lattner229907c2011-07-18 04:54:35 +00003231 Type *AggTy = I.getType();
3232 Type *ValTy = Op1->getType();
Dan Gohman575fad32008-09-03 16:12:24 +00003233 bool IntoUndef = isa<UndefValue>(Op0);
3234 bool FromUndef = isa<UndefValue>(Op1);
3235
Jay Foad57aa6362011-07-13 10:26:04 +00003236 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohman575fad32008-09-03 16:12:24 +00003237
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003238 const TargetLowering *TLI = TM.getTargetLowering();
Owen Anderson53aa7a92009-08-10 22:56:29 +00003239 SmallVector<EVT, 4> AggValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003240 ComputeValueVTs(*TLI, AggTy, AggValueVTs);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003241 SmallVector<EVT, 4> ValValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003242 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00003243
3244 unsigned NumAggValues = AggValueVTs.size();
3245 unsigned NumValValues = ValValueVTs.size();
3246 SmallVector<SDValue, 4> Values(NumAggValues);
3247
3248 SDValue Agg = getValue(Op0);
Dan Gohman575fad32008-09-03 16:12:24 +00003249 unsigned i = 0;
3250 // Copy the beginning value(s) from the original aggregate.
3251 for (; i != LinearIndex; ++i)
Dale Johannesen84935752009-02-06 23:05:02 +00003252 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohman575fad32008-09-03 16:12:24 +00003253 SDValue(Agg.getNode(), Agg.getResNo() + i);
3254 // Copy values from the inserted value(s).
Rafael Espindolae53b7d12011-05-13 15:18:06 +00003255 if (NumValValues) {
3256 SDValue Val = getValue(Op1);
3257 for (; i != LinearIndex + NumValValues; ++i)
3258 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3259 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3260 }
Dan Gohman575fad32008-09-03 16:12:24 +00003261 // Copy remaining value(s) from the original aggregate.
3262 for (; i != NumAggValues; ++i)
Dale Johannesen84935752009-02-06 23:05:02 +00003263 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohman575fad32008-09-03 16:12:24 +00003264 SDValue(Agg.getNode(), Agg.getResNo() + i);
3265
Andrew Trickef9de2a2013-05-25 02:42:55 +00003266 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00003267 DAG.getVTList(&AggValueVTs[0], NumAggValues),
3268 &Values[0], NumAggValues));
Dan Gohman575fad32008-09-03 16:12:24 +00003269}
3270
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003271void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003272 const Value *Op0 = I.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003273 Type *AggTy = Op0->getType();
3274 Type *ValTy = I.getType();
Dan Gohman575fad32008-09-03 16:12:24 +00003275 bool OutOfUndef = isa<UndefValue>(Op0);
3276
Jay Foad57aa6362011-07-13 10:26:04 +00003277 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohman575fad32008-09-03 16:12:24 +00003278
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003279 const TargetLowering *TLI = TM.getTargetLowering();
Owen Anderson53aa7a92009-08-10 22:56:29 +00003280 SmallVector<EVT, 4> ValValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003281 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00003282
3283 unsigned NumValValues = ValValueVTs.size();
Rafael Espindolae53b7d12011-05-13 15:18:06 +00003284
3285 // Ignore a extractvalue that produces an empty object
3286 if (!NumValValues) {
3287 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3288 return;
3289 }
3290
Dan Gohman575fad32008-09-03 16:12:24 +00003291 SmallVector<SDValue, 4> Values(NumValValues);
3292
3293 SDValue Agg = getValue(Op0);
3294 // Copy out the selected value(s).
3295 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3296 Values[i - LinearIndex] =
Bill Wendling165b45d2008-11-20 07:24:30 +00003297 OutOfUndef ?
Dale Johannesen84935752009-02-06 23:05:02 +00003298 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendling165b45d2008-11-20 07:24:30 +00003299 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohman575fad32008-09-03 16:12:24 +00003300
Andrew Trickef9de2a2013-05-25 02:42:55 +00003301 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00003302 DAG.getVTList(&ValValueVTs[0], NumValValues),
3303 &Values[0], NumValValues));
Dan Gohman575fad32008-09-03 16:12:24 +00003304}
3305
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003306void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
Matt Arsenaultb7689122013-10-21 20:03:54 +00003307 Value *Op0 = I.getOperand(0);
Nadav Rotem1d666092012-02-28 14:13:19 +00003308 // Note that the pointer operand may be a vector of pointers. Take the scalar
3309 // element which holds a pointer.
Matt Arsenaultb7689122013-10-21 20:03:54 +00003310 Type *Ty = Op0->getType()->getScalarType();
3311 unsigned AS = Ty->getPointerAddressSpace();
3312 SDValue N = getValue(Op0);
Dan Gohman575fad32008-09-03 16:12:24 +00003313
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003314 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
Dan Gohman575fad32008-09-03 16:12:24 +00003315 OI != E; ++OI) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003316 const Value *Idx = *OI;
Chris Lattner229907c2011-07-18 04:54:35 +00003317 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003318 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
Dan Gohman575fad32008-09-03 16:12:24 +00003319 if (Field) {
3320 // N = N + Offset
Rafael Espindola5f57f462014-02-21 18:34:28 +00003321 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003322 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003323 DAG.getConstant(Offset, N.getValueType()));
Dan Gohman575fad32008-09-03 16:12:24 +00003324 }
Bill Wendlinge79105b2009-12-21 23:10:19 +00003325
Dan Gohman575fad32008-09-03 16:12:24 +00003326 Ty = StTy->getElementType(Field);
3327 } else {
3328 Ty = cast<SequentialType>(Ty)->getElementType();
3329
3330 // If this is a constant subscript, handle it quickly.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003331 const TargetLowering *TLI = TM.getTargetLowering();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003332 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Dan Gohmanf1d83042010-06-18 14:22:04 +00003333 if (CI->isZero()) continue;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003334 uint64_t Offs =
Rafael Espindola5f57f462014-02-21 18:34:28 +00003335 DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Chengfe174df2009-02-09 21:01:06 +00003336 SDValue OffsVal;
Tom Stellardfd155822013-08-26 15:05:36 +00003337 EVT PTy = TLI->getPointerTy(AS);
Owen Andersonc30530d2009-08-10 18:56:59 +00003338 unsigned PtrBits = PTy.getSizeInBits();
Bill Wendlinge79105b2009-12-21 23:10:19 +00003339 if (PtrBits < 64)
Tom Stellardfd155822013-08-26 15:05:36 +00003340 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
Owen Anderson9f944592009-08-11 20:47:22 +00003341 DAG.getConstant(Offs, MVT::i64));
Bill Wendlinge79105b2009-12-21 23:10:19 +00003342 else
Tom Stellardfd155822013-08-26 15:05:36 +00003343 OffsVal = DAG.getConstant(Offs, PTy);
Bill Wendlinge79105b2009-12-21 23:10:19 +00003344
Andrew Trickef9de2a2013-05-25 02:42:55 +00003345 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
Evan Cheng020588c2009-02-09 20:54:38 +00003346 OffsVal);
Dan Gohman575fad32008-09-03 16:12:24 +00003347 continue;
3348 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003349
Dan Gohman575fad32008-09-03 16:12:24 +00003350 // N = N + Idx * ElementSize;
Tom Stellardfd155822013-08-26 15:05:36 +00003351 APInt ElementSize = APInt(TLI->getPointerSizeInBits(AS),
Rafael Espindola5f57f462014-02-21 18:34:28 +00003352 DL->getTypeAllocSize(Ty));
Dan Gohman575fad32008-09-03 16:12:24 +00003353 SDValue IdxN = getValue(Idx);
3354
3355 // If the index is smaller or larger than intptr_t, truncate or extend
3356 // it.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003357 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
Dan Gohman575fad32008-09-03 16:12:24 +00003358
3359 // If this is a multiply by a power of two, turn it into a shl
3360 // immediately. This is a very common case.
3361 if (ElementSize != 1) {
Dan Gohman4ef112b2009-10-23 17:57:43 +00003362 if (ElementSize.isPowerOf2()) {
3363 unsigned Amt = ElementSize.logBase2();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003364 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003365 N.getValueType(), IdxN,
Nadav Rotem3924cb02011-12-05 06:29:09 +00003366 DAG.getConstant(Amt, IdxN.getValueType()));
Dan Gohman575fad32008-09-03 16:12:24 +00003367 } else {
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003368 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003369 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003370 N.getValueType(), IdxN, Scale);
Dan Gohman575fad32008-09-03 16:12:24 +00003371 }
3372 }
3373
Andrew Trickef9de2a2013-05-25 02:42:55 +00003374 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003375 N.getValueType(), N, IdxN);
Dan Gohman575fad32008-09-03 16:12:24 +00003376 }
3377 }
Bill Wendlinge79105b2009-12-21 23:10:19 +00003378
Dan Gohman575fad32008-09-03 16:12:24 +00003379 setValue(&I, N);
3380}
3381
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003382void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003383 // If this is a fixed sized alloca in the entry block of the function,
3384 // allocate it statically on the stack.
3385 if (FuncInfo.StaticAllocaMap.count(&I))
3386 return; // getValue will auto-populate this.
3387
Chris Lattner229907c2011-07-18 04:54:35 +00003388 Type *Ty = I.getAllocatedType();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003389 const TargetLowering *TLI = TM.getTargetLowering();
3390 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
Dan Gohman575fad32008-09-03 16:12:24 +00003391 unsigned Align =
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003392 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
Dan Gohman575fad32008-09-03 16:12:24 +00003393 I.getAlignment());
3394
3395 SDValue AllocSize = getValue(I.getArraySize());
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003396
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003397 EVT IntPtr = TLI->getPointerTy();
Dan Gohman2140a742010-05-28 01:14:11 +00003398 if (AllocSize.getValueType() != IntPtr)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003399 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
Dan Gohman2140a742010-05-28 01:14:11 +00003400
Andrew Trickef9de2a2013-05-25 02:42:55 +00003401 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
Dan Gohman2140a742010-05-28 01:14:11 +00003402 AllocSize,
3403 DAG.getConstant(TySize, IntPtr));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003404
Dan Gohman575fad32008-09-03 16:12:24 +00003405 // Handle alignment. If the requested alignment is less than or equal to
3406 // the stack alignment, ignore it. If the size is greater than or equal to
3407 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Anton Korobeynikov2f931282011-01-10 12:39:04 +00003408 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
Dan Gohman575fad32008-09-03 16:12:24 +00003409 if (Align <= StackAlign)
3410 Align = 0;
3411
3412 // Round the size of the allocation up to the stack alignment size
3413 // by add SA-1 to the size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003414 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003415 AllocSize.getValueType(), AllocSize,
Dan Gohman575fad32008-09-03 16:12:24 +00003416 DAG.getIntPtrConstant(StackAlign-1));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003417
Dan Gohman575fad32008-09-03 16:12:24 +00003418 // Mask out the low bits for alignment purposes.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003419 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003420 AllocSize.getValueType(), AllocSize,
Dan Gohman575fad32008-09-03 16:12:24 +00003421 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3422
3423 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson9f944592009-08-11 20:47:22 +00003424 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003425 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(),
Dan Gohmande912e22009-04-09 23:54:40 +00003426 VTs, Ops, 3);
Dan Gohman575fad32008-09-03 16:12:24 +00003427 setValue(&I, DSA);
3428 DAG.setRoot(DSA.getValue(1));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003429
Hans Wennborgacb842d2014-03-05 02:43:26 +00003430 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
Dan Gohman575fad32008-09-03 16:12:24 +00003431}
3432
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003433void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
Eli Friedman342e8df2011-08-24 20:50:09 +00003434 if (I.isAtomic())
3435 return visitAtomicLoad(I);
3436
Dan Gohman575fad32008-09-03 16:12:24 +00003437 const Value *SV = I.getOperand(0);
3438 SDValue Ptr = getValue(SV);
3439
Chris Lattner229907c2011-07-18 04:54:35 +00003440 Type *Ty = I.getType();
David Greene39c6d012010-02-15 17:00:31 +00003441
Dan Gohman575fad32008-09-03 16:12:24 +00003442 bool isVolatile = I.isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00003443 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Pete Cooper82cd9e82011-11-08 18:42:53 +00003444 bool isInvariant = I.getMetadata("invariant.load") != 0;
Dan Gohman575fad32008-09-03 16:12:24 +00003445 unsigned Alignment = I.getAlignment();
Dan Gohmana94cc6d2010-10-20 00:31:05 +00003446 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
Rafael Espindola80c540e2012-03-31 18:14:00 +00003447 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
Dan Gohman575fad32008-09-03 16:12:24 +00003448
Owen Anderson53aa7a92009-08-10 22:56:29 +00003449 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00003450 SmallVector<uint64_t, 4> Offsets;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003451 ComputeValueVTs(*TM.getTargetLowering(), Ty, ValueVTs, &Offsets);
Dan Gohman575fad32008-09-03 16:12:24 +00003452 unsigned NumValues = ValueVTs.size();
3453 if (NumValues == 0)
3454 return;
3455
3456 SDValue Root;
3457 bool ConstantMemory = false;
Richard Sandiford9afe6132013-12-10 10:36:34 +00003458 if (isVolatile || NumValues > MaxParallelChains)
Dan Gohman575fad32008-09-03 16:12:24 +00003459 // Serialize volatile loads with other side effects.
3460 Root = getRoot();
Dan Gohmana94cc6d2010-10-20 00:31:05 +00003461 else if (AA->pointsToConstantMemory(
3462 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
Dan Gohman575fad32008-09-03 16:12:24 +00003463 // Do not serialize (non-volatile) loads of constant memory with anything.
3464 Root = DAG.getEntryNode();
3465 ConstantMemory = true;
3466 } else {
3467 // Do not serialize non-volatile loads against each other.
3468 Root = DAG.getRoot();
3469 }
Wesley Peck527da1b2010-11-23 03:31:01 +00003470
Richard Sandiford9afe6132013-12-10 10:36:34 +00003471 const TargetLowering *TLI = TM.getTargetLowering();
3472 if (isVolatile)
3473 Root = TLI->prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
3474
Dan Gohman575fad32008-09-03 16:12:24 +00003475 SmallVector<SDValue, 4> Values(NumValues);
Andrew Trick116efac2010-11-12 17:50:46 +00003476 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3477 NumValues));
Owen Anderson53aa7a92009-08-10 22:56:29 +00003478 EVT PtrVT = Ptr.getValueType();
Andrew Trick116efac2010-11-12 17:50:46 +00003479 unsigned ChainI = 0;
3480 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3481 // Serializing loads here may result in excessive register pressure, and
3482 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3483 // could recover a bit by hoisting nodes upward in the chain by recognizing
3484 // they are side-effect free or do not alias. The optimizer should really
3485 // avoid this case by converting large object/array copies to llvm.memcpy
3486 // (MaxParallelChains should always remain as failsafe).
3487 if (ChainI == MaxParallelChains) {
3488 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
Andrew Trickef9de2a2013-05-25 02:42:55 +00003489 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Andrew Trick116efac2010-11-12 17:50:46 +00003490 MVT::Other, &Chains[0], ChainI);
3491 Root = Chain;
3492 ChainI = 0;
3493 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00003494 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003495 PtrVT, Ptr,
3496 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003497 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00003498 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
Rafael Espindola80c540e2012-03-31 18:14:00 +00003499 isNonTemporal, isInvariant, Alignment, TBAAInfo,
3500 Ranges);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003501
Dan Gohman575fad32008-09-03 16:12:24 +00003502 Values[i] = L;
Andrew Trick116efac2010-11-12 17:50:46 +00003503 Chains[ChainI] = L.getValue(1);
Dan Gohman575fad32008-09-03 16:12:24 +00003504 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003505
Dan Gohman575fad32008-09-03 16:12:24 +00003506 if (!ConstantMemory) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003507 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Andrew Trick116efac2010-11-12 17:50:46 +00003508 MVT::Other, &Chains[0], ChainI);
Dan Gohman575fad32008-09-03 16:12:24 +00003509 if (isVolatile)
3510 DAG.setRoot(Chain);
3511 else
3512 PendingLoads.push_back(Chain);
3513 }
3514
Andrew Trickef9de2a2013-05-25 02:42:55 +00003515 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00003516 DAG.getVTList(&ValueVTs[0], NumValues),
3517 &Values[0], NumValues));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003518}
Dan Gohman575fad32008-09-03 16:12:24 +00003519
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003520void SelectionDAGBuilder::visitStore(const StoreInst &I) {
Eli Friedman342e8df2011-08-24 20:50:09 +00003521 if (I.isAtomic())
3522 return visitAtomicStore(I);
3523
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003524 const Value *SrcV = I.getOperand(0);
3525 const Value *PtrV = I.getOperand(1);
Dan Gohman575fad32008-09-03 16:12:24 +00003526
Owen Anderson53aa7a92009-08-10 22:56:29 +00003527 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00003528 SmallVector<uint64_t, 4> Offsets;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003529 ComputeValueVTs(*TM.getTargetLowering(), SrcV->getType(), ValueVTs, &Offsets);
Dan Gohman575fad32008-09-03 16:12:24 +00003530 unsigned NumValues = ValueVTs.size();
3531 if (NumValues == 0)
3532 return;
3533
3534 // Get the lowered operands. Note that we do this after
3535 // checking if NumResults is zero, because with zero results
3536 // the operands won't have values in the map.
3537 SDValue Src = getValue(SrcV);
3538 SDValue Ptr = getValue(PtrV);
3539
3540 SDValue Root = getRoot();
Andrew Trick116efac2010-11-12 17:50:46 +00003541 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3542 NumValues));
Owen Anderson53aa7a92009-08-10 22:56:29 +00003543 EVT PtrVT = Ptr.getValueType();
Dan Gohman575fad32008-09-03 16:12:24 +00003544 bool isVolatile = I.isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00003545 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Dan Gohman575fad32008-09-03 16:12:24 +00003546 unsigned Alignment = I.getAlignment();
Dan Gohmana94cc6d2010-10-20 00:31:05 +00003547 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003548
Andrew Trick116efac2010-11-12 17:50:46 +00003549 unsigned ChainI = 0;
3550 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3551 // See visitLoad comments.
3552 if (ChainI == MaxParallelChains) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003553 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Andrew Trick116efac2010-11-12 17:50:46 +00003554 MVT::Other, &Chains[0], ChainI);
3555 Root = Chain;
3556 ChainI = 0;
3557 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00003558 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003559 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003560 SDValue St = DAG.getStore(Root, getCurSDLoc(),
Andrew Trick116efac2010-11-12 17:50:46 +00003561 SDValue(Src.getNode(), Src.getResNo() + i),
3562 Add, MachinePointerInfo(PtrV, Offsets[i]),
3563 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3564 Chains[ChainI] = St;
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003565 }
3566
Andrew Trickef9de2a2013-05-25 02:42:55 +00003567 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Andrew Trick116efac2010-11-12 17:50:46 +00003568 MVT::Other, &Chains[0], ChainI);
Devang Patel05561e82010-10-26 22:14:52 +00003569 DAG.setRoot(StoreNode);
Dan Gohman575fad32008-09-03 16:12:24 +00003570}
3571
Eli Friedman30a49e92011-08-03 21:06:02 +00003572static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
Eli Friedman342e8df2011-08-24 20:50:09 +00003573 SynchronizationScope Scope,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003574 bool Before, SDLoc dl,
Eli Friedman30a49e92011-08-03 21:06:02 +00003575 SelectionDAG &DAG,
3576 const TargetLowering &TLI) {
3577 // Fence, if necessary
3578 if (Before) {
Eli Friedman452aae62011-08-26 02:59:24 +00003579 if (Order == AcquireRelease || Order == SequentiallyConsistent)
Eli Friedman30a49e92011-08-03 21:06:02 +00003580 Order = Release;
3581 else if (Order == Acquire || Order == Monotonic)
3582 return Chain;
3583 } else {
3584 if (Order == AcquireRelease)
3585 Order = Acquire;
3586 else if (Order == Release || Order == Monotonic)
3587 return Chain;
3588 }
3589 SDValue Ops[3];
3590 Ops[0] = Chain;
Eli Friedman342e8df2011-08-24 20:50:09 +00003591 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
3592 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
Eli Friedman30a49e92011-08-03 21:06:02 +00003593 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
3594}
3595
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003596void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003597 SDLoc dl = getCurSDLoc();
Tim Northovere94a5182014-03-11 10:48:52 +00003598 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3599 AtomicOrdering FailureOrder = I.getFailureOrdering();
Eli Friedman342e8df2011-08-24 20:50:09 +00003600 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman30a49e92011-08-03 21:06:02 +00003601
3602 SDValue InChain = getRoot();
3603
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003604 const TargetLowering *TLI = TM.getTargetLowering();
3605 if (TLI->getInsertFencesForAtomic())
Tim Northovere94a5182014-03-11 10:48:52 +00003606 InChain = InsertFenceForAtomic(InChain, SuccessOrder, Scope, true, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003607 DAG, *TLI);
Eli Friedman30a49e92011-08-03 21:06:02 +00003608
Eli Friedmanadec5872011-07-29 03:05:32 +00003609 SDValue L =
Eli Friedman30a49e92011-08-03 21:06:02 +00003610 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
Craig Topperd9c27832013-08-15 02:44:19 +00003611 getValue(I.getCompareOperand()).getSimpleValueType(),
Eli Friedman30a49e92011-08-03 21:06:02 +00003612 InChain,
Eli Friedmanadec5872011-07-29 03:05:32 +00003613 getValue(I.getPointerOperand()),
3614 getValue(I.getCompareOperand()),
3615 getValue(I.getNewValOperand()),
3616 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
Tim Northovere94a5182014-03-11 10:48:52 +00003617 TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder,
3618 TLI->getInsertFencesForAtomic() ? Monotonic : FailureOrder,
Eli Friedman342e8df2011-08-24 20:50:09 +00003619 Scope);
Eli Friedman30a49e92011-08-03 21:06:02 +00003620
3621 SDValue OutChain = L.getValue(1);
3622
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003623 if (TLI->getInsertFencesForAtomic())
Tim Northovere94a5182014-03-11 10:48:52 +00003624 OutChain = InsertFenceForAtomic(OutChain, SuccessOrder, Scope, false, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003625 DAG, *TLI);
Eli Friedman30a49e92011-08-03 21:06:02 +00003626
Eli Friedmanadec5872011-07-29 03:05:32 +00003627 setValue(&I, L);
Eli Friedman30a49e92011-08-03 21:06:02 +00003628 DAG.setRoot(OutChain);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003629}
3630
3631void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003632 SDLoc dl = getCurSDLoc();
Eli Friedmanadec5872011-07-29 03:05:32 +00003633 ISD::NodeType NT;
3634 switch (I.getOperation()) {
David Blaikie46a9f012012-01-20 21:51:11 +00003635 default: llvm_unreachable("Unknown atomicrmw operation");
Eli Friedmanadec5872011-07-29 03:05:32 +00003636 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3637 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3638 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3639 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3640 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3641 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3642 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3643 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3644 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3645 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3646 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3647 }
Eli Friedman30a49e92011-08-03 21:06:02 +00003648 AtomicOrdering Order = I.getOrdering();
Eli Friedman342e8df2011-08-24 20:50:09 +00003649 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman30a49e92011-08-03 21:06:02 +00003650
3651 SDValue InChain = getRoot();
3652
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003653 const TargetLowering *TLI = TM.getTargetLowering();
3654 if (TLI->getInsertFencesForAtomic())
Eli Friedman342e8df2011-08-24 20:50:09 +00003655 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003656 DAG, *TLI);
Eli Friedman30a49e92011-08-03 21:06:02 +00003657
Eli Friedmanadec5872011-07-29 03:05:32 +00003658 SDValue L =
Eli Friedman30a49e92011-08-03 21:06:02 +00003659 DAG.getAtomic(NT, dl,
Craig Topperd9c27832013-08-15 02:44:19 +00003660 getValue(I.getValOperand()).getSimpleValueType(),
Eli Friedman30a49e92011-08-03 21:06:02 +00003661 InChain,
Eli Friedmanadec5872011-07-29 03:05:32 +00003662 getValue(I.getPointerOperand()),
3663 getValue(I.getValOperand()),
3664 I.getPointerOperand(), 0 /* Alignment */,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003665 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
Eli Friedman342e8df2011-08-24 20:50:09 +00003666 Scope);
Eli Friedman30a49e92011-08-03 21:06:02 +00003667
3668 SDValue OutChain = L.getValue(1);
3669
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003670 if (TLI->getInsertFencesForAtomic())
Eli Friedman342e8df2011-08-24 20:50:09 +00003671 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003672 DAG, *TLI);
Eli Friedman30a49e92011-08-03 21:06:02 +00003673
Eli Friedmanadec5872011-07-29 03:05:32 +00003674 setValue(&I, L);
Eli Friedman30a49e92011-08-03 21:06:02 +00003675 DAG.setRoot(OutChain);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003676}
3677
Eli Friedmanfee02c62011-07-25 23:16:38 +00003678void SelectionDAGBuilder::visitFence(const FenceInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003679 SDLoc dl = getCurSDLoc();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003680 const TargetLowering *TLI = TM.getTargetLowering();
Eli Friedman26a48482011-07-27 22:21:52 +00003681 SDValue Ops[3];
3682 Ops[0] = getRoot();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003683 Ops[1] = DAG.getConstant(I.getOrdering(), TLI->getPointerTy());
3684 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI->getPointerTy());
Eli Friedman26a48482011-07-27 22:21:52 +00003685 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
Eli Friedmanfee02c62011-07-25 23:16:38 +00003686}
3687
Eli Friedman342e8df2011-08-24 20:50:09 +00003688void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003689 SDLoc dl = getCurSDLoc();
Eli Friedman342e8df2011-08-24 20:50:09 +00003690 AtomicOrdering Order = I.getOrdering();
3691 SynchronizationScope Scope = I.getSynchScope();
3692
3693 SDValue InChain = getRoot();
3694
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003695 const TargetLowering *TLI = TM.getTargetLowering();
3696 EVT VT = TLI->getValueType(I.getType());
Eli Friedman342e8df2011-08-24 20:50:09 +00003697
Evan Chenga72b9702013-02-06 02:06:33 +00003698 if (I.getAlignment() < VT.getSizeInBits() / 8)
Eli Friedmanf1518212011-09-13 20:50:54 +00003699 report_fatal_error("Cannot generate unaligned atomic load");
3700
Richard Sandiford9afe6132013-12-10 10:36:34 +00003701 InChain = TLI->prepareVolatileOrAtomicLoad(InChain, dl, DAG);
Eli Friedman342e8df2011-08-24 20:50:09 +00003702 SDValue L =
3703 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3704 getValue(I.getPointerOperand()),
3705 I.getPointerOperand(), I.getAlignment(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003706 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
Eli Friedman342e8df2011-08-24 20:50:09 +00003707 Scope);
3708
3709 SDValue OutChain = L.getValue(1);
3710
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003711 if (TLI->getInsertFencesForAtomic())
Eli Friedman342e8df2011-08-24 20:50:09 +00003712 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003713 DAG, *TLI);
Eli Friedman342e8df2011-08-24 20:50:09 +00003714
3715 setValue(&I, L);
3716 DAG.setRoot(OutChain);
3717}
3718
3719void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003720 SDLoc dl = getCurSDLoc();
Eli Friedman342e8df2011-08-24 20:50:09 +00003721
3722 AtomicOrdering Order = I.getOrdering();
3723 SynchronizationScope Scope = I.getSynchScope();
3724
3725 SDValue InChain = getRoot();
3726
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003727 const TargetLowering *TLI = TM.getTargetLowering();
3728 EVT VT = TLI->getValueType(I.getValueOperand()->getType());
Eli Friedmanf1518212011-09-13 20:50:54 +00003729
Evan Chenga72b9702013-02-06 02:06:33 +00003730 if (I.getAlignment() < VT.getSizeInBits() / 8)
Eli Friedmanf1518212011-09-13 20:50:54 +00003731 report_fatal_error("Cannot generate unaligned atomic store");
3732
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003733 if (TLI->getInsertFencesForAtomic())
Eli Friedman342e8df2011-08-24 20:50:09 +00003734 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003735 DAG, *TLI);
Eli Friedman342e8df2011-08-24 20:50:09 +00003736
3737 SDValue OutChain =
Eli Friedmanf1518212011-09-13 20:50:54 +00003738 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
Eli Friedman342e8df2011-08-24 20:50:09 +00003739 InChain,
3740 getValue(I.getPointerOperand()),
3741 getValue(I.getValueOperand()),
3742 I.getPointerOperand(), I.getAlignment(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003743 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
Eli Friedman342e8df2011-08-24 20:50:09 +00003744 Scope);
3745
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003746 if (TLI->getInsertFencesForAtomic())
Eli Friedman342e8df2011-08-24 20:50:09 +00003747 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003748 DAG, *TLI);
Eli Friedman342e8df2011-08-24 20:50:09 +00003749
3750 DAG.setRoot(OutChain);
3751}
3752
Dan Gohman575fad32008-09-03 16:12:24 +00003753/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3754/// node.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003755void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00003756 unsigned Intrinsic) {
Dan Gohman575fad32008-09-03 16:12:24 +00003757 bool HasChain = !I.doesNotAccessMemory();
3758 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3759
3760 // Build the operand list.
3761 SmallVector<SDValue, 8> Ops;
3762 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3763 if (OnlyLoad) {
3764 // We don't need to serialize loads against other loads.
3765 Ops.push_back(DAG.getRoot());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003766 } else {
Dan Gohman575fad32008-09-03 16:12:24 +00003767 Ops.push_back(getRoot());
3768 }
3769 }
Mon P Wang769134b2008-11-01 20:24:53 +00003770
3771 // Info is set by getTgtMemInstrinsic
3772 TargetLowering::IntrinsicInfo Info;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003773 const TargetLowering *TLI = TM.getTargetLowering();
3774 bool IsTgtIntrinsic = TLI->getTgtMemIntrinsic(Info, I, Intrinsic);
Mon P Wang769134b2008-11-01 20:24:53 +00003775
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003776 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Bob Wilson5549d492010-09-21 17:56:22 +00003777 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3778 Info.opc == ISD::INTRINSIC_W_CHAIN)
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003779 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI->getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00003780
3781 // Add all operands of the call to the operand list.
Gabor Greifeba0be72010-06-25 09:38:13 +00003782 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3783 SDValue Op = getValue(I.getArgOperand(i));
Dan Gohman575fad32008-09-03 16:12:24 +00003784 Ops.push_back(Op);
3785 }
3786
Owen Anderson53aa7a92009-08-10 22:56:29 +00003787 SmallVector<EVT, 4> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003788 ComputeValueVTs(*TLI, I.getType(), ValueVTs);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003789
Dan Gohman575fad32008-09-03 16:12:24 +00003790 if (HasChain)
Owen Anderson9f944592009-08-11 20:47:22 +00003791 ValueVTs.push_back(MVT::Other);
Dan Gohman575fad32008-09-03 16:12:24 +00003792
Bob Wilson84aa8552009-07-31 22:41:21 +00003793 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
Dan Gohman575fad32008-09-03 16:12:24 +00003794
3795 // Create the node.
3796 SDValue Result;
Mon P Wang769134b2008-11-01 20:24:53 +00003797 if (IsTgtIntrinsic) {
3798 // This is target intrinsic that touches memory
Andrew Trickef9de2a2013-05-25 02:42:55 +00003799 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
Dan Gohmande912e22009-04-09 23:54:40 +00003800 VTs, &Ops[0], Ops.size(),
Chris Lattnerd2d58ad2010-09-21 04:57:15 +00003801 Info.memVT,
3802 MachinePointerInfo(Info.ptrVal, Info.offset),
Mon P Wang769134b2008-11-01 20:24:53 +00003803 Info.align, Info.vol,
3804 Info.readMem, Info.writeMem);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003805 } else if (!HasChain) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003806 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(),
Dan Gohmande912e22009-04-09 23:54:40 +00003807 VTs, &Ops[0], Ops.size());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003808 } else if (!I.getType()->isVoidTy()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003809 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(),
Dan Gohmande912e22009-04-09 23:54:40 +00003810 VTs, &Ops[0], Ops.size());
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003811 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003812 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(),
Dan Gohmande912e22009-04-09 23:54:40 +00003813 VTs, &Ops[0], Ops.size());
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003814 }
3815
Dan Gohman575fad32008-09-03 16:12:24 +00003816 if (HasChain) {
3817 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3818 if (OnlyLoad)
3819 PendingLoads.push_back(Chain);
3820 else
3821 DAG.setRoot(Chain);
3822 }
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003823
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003824 if (!I.getType()->isVoidTy()) {
Chris Lattner229907c2011-07-18 04:54:35 +00003825 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003826 EVT VT = TLI->getValueType(PTy);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003827 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003828 }
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003829
Dan Gohman575fad32008-09-03 16:12:24 +00003830 setValue(&I, Result);
3831 }
3832}
3833
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003834/// GetSignificand - Get the significand and build it into a floating-point
3835/// number with exponent of 1:
3836///
3837/// Op = (Op & 0x007fffff) | 0x3f800000;
3838///
Matt Beaumont-Gay0e760da2013-02-25 18:11:18 +00003839/// where Op is the hexadecimal representation of floating point value.
Bill Wendlinged3bb782008-09-09 20:39:27 +00003840static SDValue
Andrew Trickef9de2a2013-05-25 02:42:55 +00003841GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
Owen Anderson9f944592009-08-11 20:47:22 +00003842 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3843 DAG.getConstant(0x007fffff, MVT::i32));
3844 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3845 DAG.getConstant(0x3f800000, MVT::i32));
Wesley Peck527da1b2010-11-23 03:31:01 +00003846 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
Bill Wendlinged3bb782008-09-09 20:39:27 +00003847}
3848
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003849/// GetExponent - Get the exponent:
3850///
Bill Wendling23959162009-01-20 21:17:57 +00003851/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003852///
Matt Beaumont-Gay0e760da2013-02-25 18:11:18 +00003853/// where Op is the hexadecimal representation of floating point value.
Bill Wendlinged3bb782008-09-09 20:39:27 +00003854static SDValue
Dale Johannesendb7c5f62009-01-31 02:22:37 +00003855GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003856 SDLoc dl) {
Owen Anderson9f944592009-08-11 20:47:22 +00003857 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3858 DAG.getConstant(0x7f800000, MVT::i32));
3859 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands41826032009-01-31 15:50:11 +00003860 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson9f944592009-08-11 20:47:22 +00003861 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3862 DAG.getConstant(127, MVT::i32));
Bill Wendling954cb182010-01-28 21:51:40 +00003863 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendlinged3bb782008-09-09 20:39:27 +00003864}
3865
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003866/// getF32Constant - Get 32-bit floating point constant.
3867static SDValue
3868getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Tim Northover29178a32013-01-22 09:46:31 +00003869 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3870 MVT::f32);
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003871}
3872
Craig Topperd2638c12012-11-24 18:52:06 +00003873/// expandExp - Lower an exp intrinsic. Handles the special sequences for
Bill Wendling48217d82008-09-09 22:13:54 +00003874/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003875static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperd2638c12012-11-24 18:52:06 +00003876 const TargetLowering &TLI) {
3877 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48217d82008-09-09 22:13:54 +00003878 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Bill Wendling48217d82008-09-09 22:13:54 +00003879
3880 // Put the exponent in the right bit position for later addition to the
3881 // final result:
3882 //
3883 // #define LOG2OFe 1.4426950f
3884 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson9f944592009-08-11 20:47:22 +00003885 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003886 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson9f944592009-08-11 20:47:22 +00003887 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendling48217d82008-09-09 22:13:54 +00003888
3889 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson9f944592009-08-11 20:47:22 +00003890 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3891 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendling48217d82008-09-09 22:13:54 +00003892
3893 // IntegerPartOfX <<= 23;
Owen Anderson9f944592009-08-11 20:47:22 +00003894 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands41826032009-01-31 15:50:11 +00003895 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003896
Craig Topper4a981752012-11-24 08:22:37 +00003897 SDValue TwoToFracPartOfX;
Bill Wendling48217d82008-09-09 22:13:54 +00003898 if (LimitFloatPrecision <= 6) {
3899 // For floating-point precision of 6:
3900 //
3901 // TwoToFractionalPartOfX =
3902 // 0.997535578f +
3903 // (0.735607626f + 0.252464424f * x) * x;
3904 //
3905 // error 0.0144103317, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00003906 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003907 getF32Constant(DAG, 0x3e814304));
Owen Anderson9f944592009-08-11 20:47:22 +00003908 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003909 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson9f944592009-08-11 20:47:22 +00003910 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper4a981752012-11-24 08:22:37 +00003911 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3912 getF32Constant(DAG, 0x3f7f5e7e));
Craig Toppered756c52012-11-16 20:01:39 +00003913 } else if (LimitFloatPrecision <= 12) {
Bill Wendling48217d82008-09-09 22:13:54 +00003914 // For floating-point precision of 12:
3915 //
3916 // TwoToFractionalPartOfX =
3917 // 0.999892986f +
3918 // (0.696457318f +
3919 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3920 //
3921 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00003922 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003923 getF32Constant(DAG, 0x3da235e3));
Owen Anderson9f944592009-08-11 20:47:22 +00003924 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003925 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson9f944592009-08-11 20:47:22 +00003926 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3927 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003928 getF32Constant(DAG, 0x3f324b07));
Owen Anderson9f944592009-08-11 20:47:22 +00003929 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper4a981752012-11-24 08:22:37 +00003930 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3931 getF32Constant(DAG, 0x3f7ff8fd));
Craig Toppered756c52012-11-16 20:01:39 +00003932 } else { // LimitFloatPrecision <= 18
Bill Wendling48217d82008-09-09 22:13:54 +00003933 // For floating-point precision of 18:
3934 //
3935 // TwoToFractionalPartOfX =
3936 // 0.999999982f +
3937 // (0.693148872f +
3938 // (0.240227044f +
3939 // (0.554906021e-1f +
3940 // (0.961591928e-2f +
3941 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3942 //
3943 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00003944 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003945 getF32Constant(DAG, 0x3924b03e));
Owen Anderson9f944592009-08-11 20:47:22 +00003946 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003947 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson9f944592009-08-11 20:47:22 +00003948 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3949 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003950 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson9f944592009-08-11 20:47:22 +00003951 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3952 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003953 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson9f944592009-08-11 20:47:22 +00003954 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3955 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003956 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson9f944592009-08-11 20:47:22 +00003957 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3958 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003959 getF32Constant(DAG, 0x3f317234));
Owen Anderson9f944592009-08-11 20:47:22 +00003960 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topper4a981752012-11-24 08:22:37 +00003961 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3962 getF32Constant(DAG, 0x3f800000));
Bill Wendling48217d82008-09-09 22:13:54 +00003963 }
Craig Topper4a981752012-11-24 08:22:37 +00003964
3965 // Add the exponent into the result in integer domain.
3966 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
Craig Topperd2638c12012-11-24 18:52:06 +00003967 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3968 DAG.getNode(ISD::ADD, dl, MVT::i32,
3969 t13, IntegerPartOfX));
Bill Wendling48217d82008-09-09 22:13:54 +00003970 }
3971
Craig Topperd2638c12012-11-24 18:52:06 +00003972 // No special expansion.
3973 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00003974}
3975
Craig Topperbef254a2012-11-23 18:38:31 +00003976/// expandLog - Lower a log intrinsic. Handles the special sequences for
Bill Wendlinged3bb782008-09-09 20:39:27 +00003977/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003978static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00003979 const TargetLowering &TLI) {
3980 if (Op.getValueType() == MVT::f32 &&
Bill Wendlinged3bb782008-09-09 20:39:27 +00003981 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00003982 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendlinged3bb782008-09-09 20:39:27 +00003983
3984 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling78c5b7a2010-03-02 01:55:18 +00003985 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson9f944592009-08-11 20:47:22 +00003986 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003987 getF32Constant(DAG, 0x3f317218));
Bill Wendlinged3bb782008-09-09 20:39:27 +00003988
3989 // Get the significand and build it into a floating-point number with
3990 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00003991 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendlinged3bb782008-09-09 20:39:27 +00003992
Craig Topper3669de42012-11-16 19:08:44 +00003993 SDValue LogOfMantissa;
Bill Wendlinged3bb782008-09-09 20:39:27 +00003994 if (LimitFloatPrecision <= 6) {
3995 // For floating-point precision of 6:
3996 //
3997 // LogofMantissa =
3998 // -1.1609546f +
3999 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004000 //
Bill Wendlinged3bb782008-09-09 20:39:27 +00004001 // error 0.0034276066, which is better than 8 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004002 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004003 getF32Constant(DAG, 0xbe74c456));
Owen Anderson9f944592009-08-11 20:47:22 +00004004 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004005 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson9f944592009-08-11 20:47:22 +00004006 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004007 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4008 getF32Constant(DAG, 0x3f949a29));
Craig Toppered756c52012-11-16 20:01:39 +00004009 } else if (LimitFloatPrecision <= 12) {
Bill Wendlinged3bb782008-09-09 20:39:27 +00004010 // For floating-point precision of 12:
4011 //
4012 // LogOfMantissa =
4013 // -1.7417939f +
4014 // (2.8212026f +
4015 // (-1.4699568f +
4016 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4017 //
4018 // error 0.000061011436, which is 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004019 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004020 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson9f944592009-08-11 20:47:22 +00004021 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004022 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson9f944592009-08-11 20:47:22 +00004023 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4024 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004025 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson9f944592009-08-11 20:47:22 +00004026 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4027 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004028 getF32Constant(DAG, 0x40348e95));
Owen Anderson9f944592009-08-11 20:47:22 +00004029 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper3669de42012-11-16 19:08:44 +00004030 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4031 getF32Constant(DAG, 0x3fdef31a));
Craig Toppered756c52012-11-16 20:01:39 +00004032 } else { // LimitFloatPrecision <= 18
Bill Wendlinged3bb782008-09-09 20:39:27 +00004033 // For floating-point precision of 18:
4034 //
4035 // LogOfMantissa =
4036 // -2.1072184f +
4037 // (4.2372794f +
4038 // (-3.7029485f +
4039 // (2.2781945f +
4040 // (-0.87823314f +
4041 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4042 //
4043 // error 0.0000023660568, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004044 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004045 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson9f944592009-08-11 20:47:22 +00004046 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004047 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson9f944592009-08-11 20:47:22 +00004048 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4049 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004050 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson9f944592009-08-11 20:47:22 +00004051 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4052 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004053 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson9f944592009-08-11 20:47:22 +00004054 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4055 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004056 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson9f944592009-08-11 20:47:22 +00004057 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4058 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004059 getF32Constant(DAG, 0x408797cb));
Owen Anderson9f944592009-08-11 20:47:22 +00004060 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topper3669de42012-11-16 19:08:44 +00004061 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4062 getF32Constant(DAG, 0x4006dcab));
Bill Wendlinged3bb782008-09-09 20:39:27 +00004063 }
Craig Topper3669de42012-11-16 19:08:44 +00004064
Craig Topperbef254a2012-11-23 18:38:31 +00004065 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendlinged3bb782008-09-09 20:39:27 +00004066 }
4067
Craig Topperbef254a2012-11-23 18:38:31 +00004068 // No special expansion.
4069 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004070}
4071
Craig Topperbef254a2012-11-23 18:38:31 +00004072/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
Bill Wendling48416782008-09-09 00:28:24 +00004073/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004074static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00004075 const TargetLowering &TLI) {
4076 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48416782008-09-09 00:28:24 +00004077 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00004078 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling48416782008-09-09 00:28:24 +00004079
Bill Wendlinged3bb782008-09-09 20:39:27 +00004080 // Get the exponent.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004081 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00004082
Bill Wendling48416782008-09-09 00:28:24 +00004083 // Get the significand and build it into a floating-point number with
Bill Wendlinged3bb782008-09-09 20:39:27 +00004084 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004085 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004086
Bill Wendling48416782008-09-09 00:28:24 +00004087 // Different possible minimax approximations of significand in
4088 // floating-point for various degrees of accuracy over [1,2].
Craig Topper3669de42012-11-16 19:08:44 +00004089 SDValue Log2ofMantissa;
Bill Wendling48416782008-09-09 00:28:24 +00004090 if (LimitFloatPrecision <= 6) {
4091 // For floating-point precision of 6:
4092 //
4093 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4094 //
4095 // error 0.0049451742, which is more than 7 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004096 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004097 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson9f944592009-08-11 20:47:22 +00004098 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004099 getF32Constant(DAG, 0x40019463));
Owen Anderson9f944592009-08-11 20:47:22 +00004100 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004101 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4102 getF32Constant(DAG, 0x3fd6633d));
Craig Toppered756c52012-11-16 20:01:39 +00004103 } else if (LimitFloatPrecision <= 12) {
Bill Wendling48416782008-09-09 00:28:24 +00004104 // For floating-point precision of 12:
4105 //
4106 // Log2ofMantissa =
4107 // -2.51285454f +
4108 // (4.07009056f +
4109 // (-2.12067489f +
4110 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004111 //
Bill Wendling48416782008-09-09 00:28:24 +00004112 // error 0.0000876136000, which is better than 13 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004113 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004114 getF32Constant(DAG, 0xbda7262e));
Owen Anderson9f944592009-08-11 20:47:22 +00004115 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004116 getF32Constant(DAG, 0x3f25280b));
Owen Anderson9f944592009-08-11 20:47:22 +00004117 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4118 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004119 getF32Constant(DAG, 0x4007b923));
Owen Anderson9f944592009-08-11 20:47:22 +00004120 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4121 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004122 getF32Constant(DAG, 0x40823e2f));
Owen Anderson9f944592009-08-11 20:47:22 +00004123 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper3669de42012-11-16 19:08:44 +00004124 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4125 getF32Constant(DAG, 0x4020d29c));
Craig Toppered756c52012-11-16 20:01:39 +00004126 } else { // LimitFloatPrecision <= 18
Bill Wendling48416782008-09-09 00:28:24 +00004127 // For floating-point precision of 18:
4128 //
4129 // Log2ofMantissa =
4130 // -3.0400495f +
4131 // (6.1129976f +
4132 // (-5.3420409f +
4133 // (3.2865683f +
4134 // (-1.2669343f +
4135 // (0.27515199f -
4136 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4137 //
4138 // error 0.0000018516, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004139 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004140 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson9f944592009-08-11 20:47:22 +00004141 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004142 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson9f944592009-08-11 20:47:22 +00004143 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4144 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004145 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson9f944592009-08-11 20:47:22 +00004146 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4147 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004148 getF32Constant(DAG, 0x40525723));
Owen Anderson9f944592009-08-11 20:47:22 +00004149 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4150 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004151 getF32Constant(DAG, 0x40aaf200));
Owen Anderson9f944592009-08-11 20:47:22 +00004152 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4153 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004154 getF32Constant(DAG, 0x40c39dad));
Owen Anderson9f944592009-08-11 20:47:22 +00004155 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topper3669de42012-11-16 19:08:44 +00004156 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4157 getF32Constant(DAG, 0x4042902c));
Bill Wendling48416782008-09-09 00:28:24 +00004158 }
Craig Topper3669de42012-11-16 19:08:44 +00004159
Craig Topperbef254a2012-11-23 18:38:31 +00004160 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
Dale Johannesen36d532a2008-09-05 23:49:37 +00004161 }
Bill Wendling48416782008-09-09 00:28:24 +00004162
Craig Topperbef254a2012-11-23 18:38:31 +00004163 // No special expansion.
4164 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004165}
4166
Craig Topperbef254a2012-11-23 18:38:31 +00004167/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
Bill Wendling48416782008-09-09 00:28:24 +00004168/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004169static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00004170 const TargetLowering &TLI) {
4171 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48416782008-09-09 00:28:24 +00004172 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00004173 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling48416782008-09-09 00:28:24 +00004174
Bill Wendlinged3bb782008-09-09 20:39:27 +00004175 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004176 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson9f944592009-08-11 20:47:22 +00004177 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004178 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling48416782008-09-09 00:28:24 +00004179
4180 // Get the significand and build it into a floating-point number with
Bill Wendlinged3bb782008-09-09 20:39:27 +00004181 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004182 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling48416782008-09-09 00:28:24 +00004183
Craig Topper3669de42012-11-16 19:08:44 +00004184 SDValue Log10ofMantissa;
Bill Wendling48416782008-09-09 00:28:24 +00004185 if (LimitFloatPrecision <= 6) {
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004186 // For floating-point precision of 6:
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004187 //
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004188 // Log10ofMantissa =
4189 // -0.50419619f +
4190 // (0.60948995f - 0.10380950f * x) * x;
4191 //
4192 // error 0.0014886165, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004193 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004194 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson9f944592009-08-11 20:47:22 +00004195 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004196 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson9f944592009-08-11 20:47:22 +00004197 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004198 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4199 getF32Constant(DAG, 0x3f011300));
Craig Toppered756c52012-11-16 20:01:39 +00004200 } else if (LimitFloatPrecision <= 12) {
Bill Wendling48416782008-09-09 00:28:24 +00004201 // For floating-point precision of 12:
4202 //
4203 // Log10ofMantissa =
4204 // -0.64831180f +
4205 // (0.91751397f +
4206 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4207 //
4208 // error 0.00019228036, which is better than 12 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004209 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004210 getF32Constant(DAG, 0x3d431f31));
Owen Anderson9f944592009-08-11 20:47:22 +00004211 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004212 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson9f944592009-08-11 20:47:22 +00004213 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4214 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004215 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson9f944592009-08-11 20:47:22 +00004216 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper3669de42012-11-16 19:08:44 +00004217 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4218 getF32Constant(DAG, 0x3f25f7c3));
Craig Toppered756c52012-11-16 20:01:39 +00004219 } else { // LimitFloatPrecision <= 18
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004220 // For floating-point precision of 18:
4221 //
4222 // Log10ofMantissa =
4223 // -0.84299375f +
4224 // (1.5327582f +
4225 // (-1.0688956f +
4226 // (0.49102474f +
4227 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4228 //
4229 // error 0.0000037995730, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004230 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004231 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson9f944592009-08-11 20:47:22 +00004232 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004233 getF32Constant(DAG, 0x3e00685a));
Owen Anderson9f944592009-08-11 20:47:22 +00004234 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4235 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004236 getF32Constant(DAG, 0x3efb6798));
Owen Anderson9f944592009-08-11 20:47:22 +00004237 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4238 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004239 getF32Constant(DAG, 0x3f88d192));
Owen Anderson9f944592009-08-11 20:47:22 +00004240 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4241 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004242 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson9f944592009-08-11 20:47:22 +00004243 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
Craig Topper3669de42012-11-16 19:08:44 +00004244 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4245 getF32Constant(DAG, 0x3f57ce70));
Bill Wendling48416782008-09-09 00:28:24 +00004246 }
Craig Topper3669de42012-11-16 19:08:44 +00004247
Craig Topperbef254a2012-11-23 18:38:31 +00004248 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
Dale Johannesend4dac0e2008-09-05 21:27:19 +00004249 }
Bill Wendling48416782008-09-09 00:28:24 +00004250
Craig Topperbef254a2012-11-23 18:38:31 +00004251 // No special expansion.
4252 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004253}
4254
Craig Topperd2638c12012-11-24 18:52:06 +00004255/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
Bill Wendlingab6676a2008-09-09 22:39:21 +00004256/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004257static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperd2638c12012-11-24 18:52:06 +00004258 const TargetLowering &TLI) {
4259 if (Op.getValueType() == MVT::f32 &&
Bill Wendlingab6676a2008-09-09 22:39:21 +00004260 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Owen Anderson9f944592009-08-11 20:47:22 +00004261 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlingab6676a2008-09-09 22:39:21 +00004262
4263 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson9f944592009-08-11 20:47:22 +00004264 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4265 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlingab6676a2008-09-09 22:39:21 +00004266
4267 // IntegerPartOfX <<= 23;
Owen Anderson9f944592009-08-11 20:47:22 +00004268 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands41826032009-01-31 15:50:11 +00004269 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingab6676a2008-09-09 22:39:21 +00004270
Craig Topper4a981752012-11-24 08:22:37 +00004271 SDValue TwoToFractionalPartOfX;
Bill Wendlingab6676a2008-09-09 22:39:21 +00004272 if (LimitFloatPrecision <= 6) {
4273 // For floating-point precision of 6:
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004274 //
Bill Wendlingab6676a2008-09-09 22:39:21 +00004275 // TwoToFractionalPartOfX =
4276 // 0.997535578f +
4277 // (0.735607626f + 0.252464424f * x) * x;
4278 //
4279 // error 0.0144103317, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004280 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004281 getF32Constant(DAG, 0x3e814304));
Owen Anderson9f944592009-08-11 20:47:22 +00004282 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004283 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson9f944592009-08-11 20:47:22 +00004284 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper4a981752012-11-24 08:22:37 +00004285 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4286 getF32Constant(DAG, 0x3f7f5e7e));
Craig Toppered756c52012-11-16 20:01:39 +00004287 } else if (LimitFloatPrecision <= 12) {
Bill Wendlingab6676a2008-09-09 22:39:21 +00004288 // For floating-point precision of 12:
4289 //
4290 // TwoToFractionalPartOfX =
4291 // 0.999892986f +
4292 // (0.696457318f +
4293 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4294 //
4295 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004296 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004297 getF32Constant(DAG, 0x3da235e3));
Owen Anderson9f944592009-08-11 20:47:22 +00004298 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004299 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson9f944592009-08-11 20:47:22 +00004300 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4301 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004302 getF32Constant(DAG, 0x3f324b07));
Owen Anderson9f944592009-08-11 20:47:22 +00004303 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper4a981752012-11-24 08:22:37 +00004304 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4305 getF32Constant(DAG, 0x3f7ff8fd));
Craig Toppered756c52012-11-16 20:01:39 +00004306 } else { // LimitFloatPrecision <= 18
Bill Wendlingab6676a2008-09-09 22:39:21 +00004307 // For floating-point precision of 18:
4308 //
4309 // TwoToFractionalPartOfX =
4310 // 0.999999982f +
4311 // (0.693148872f +
4312 // (0.240227044f +
4313 // (0.554906021e-1f +
4314 // (0.961591928e-2f +
4315 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4316 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004317 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004318 getF32Constant(DAG, 0x3924b03e));
Owen Anderson9f944592009-08-11 20:47:22 +00004319 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004320 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson9f944592009-08-11 20:47:22 +00004321 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4322 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004323 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson9f944592009-08-11 20:47:22 +00004324 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4325 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004326 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson9f944592009-08-11 20:47:22 +00004327 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4328 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004329 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson9f944592009-08-11 20:47:22 +00004330 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4331 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004332 getF32Constant(DAG, 0x3f317234));
Owen Anderson9f944592009-08-11 20:47:22 +00004333 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topper4a981752012-11-24 08:22:37 +00004334 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4335 getF32Constant(DAG, 0x3f800000));
Bill Wendlingab6676a2008-09-09 22:39:21 +00004336 }
Craig Topper4a981752012-11-24 08:22:37 +00004337
4338 // Add the exponent into the result in integer domain.
4339 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4340 TwoToFractionalPartOfX);
Craig Topperd2638c12012-11-24 18:52:06 +00004341 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4342 DAG.getNode(ISD::ADD, dl, MVT::i32,
4343 t13, IntegerPartOfX));
Dale Johannesenf2a52bb2008-09-05 01:48:15 +00004344 }
Bill Wendlingab6676a2008-09-09 22:39:21 +00004345
Craig Topperd2638c12012-11-24 18:52:06 +00004346 // No special expansion.
4347 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
Dale Johannesenf2a52bb2008-09-05 01:48:15 +00004348}
4349
Bill Wendling648930b2008-09-10 00:20:20 +00004350/// visitPow - Lower a pow intrinsic. Handles the special sequences for
4351/// limited-precision mode with x == 10.0f.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004352static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
Craig Topper79bd2052012-11-25 08:08:58 +00004353 SelectionDAG &DAG, const TargetLowering &TLI) {
Bill Wendling648930b2008-09-10 00:20:20 +00004354 bool IsExp10 = false;
Benjamin Kramer671a5962013-12-11 16:36:09 +00004355 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
Bill Wendling648930b2008-09-10 00:20:20 +00004356 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Craig Topper79bd2052012-11-25 08:08:58 +00004357 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4358 APFloat Ten(10.0f);
4359 IsExp10 = LHSC->isExactlyValue(Ten);
Bill Wendling648930b2008-09-10 00:20:20 +00004360 }
4361 }
4362
Craig Topper268b6222012-11-25 00:48:58 +00004363 if (IsExp10) {
Bill Wendling648930b2008-09-10 00:20:20 +00004364 // Put the exponent in the right bit position for later addition to the
4365 // final result:
4366 //
4367 // #define LOG2OF10 3.3219281f
4368 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Craig Topper79bd2052012-11-25 08:08:58 +00004369 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004370 getF32Constant(DAG, 0x40549a78));
Owen Anderson9f944592009-08-11 20:47:22 +00004371 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendling648930b2008-09-10 00:20:20 +00004372
4373 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson9f944592009-08-11 20:47:22 +00004374 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4375 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendling648930b2008-09-10 00:20:20 +00004376
4377 // IntegerPartOfX <<= 23;
Owen Anderson9f944592009-08-11 20:47:22 +00004378 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands41826032009-01-31 15:50:11 +00004379 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendling648930b2008-09-10 00:20:20 +00004380
Craig Topper85719442012-11-25 00:15:07 +00004381 SDValue TwoToFractionalPartOfX;
Bill Wendling648930b2008-09-10 00:20:20 +00004382 if (LimitFloatPrecision <= 6) {
4383 // For floating-point precision of 6:
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004384 //
Bill Wendling648930b2008-09-10 00:20:20 +00004385 // twoToFractionalPartOfX =
4386 // 0.997535578f +
4387 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004388 //
Bill Wendling648930b2008-09-10 00:20:20 +00004389 // error 0.0144103317, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004390 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004391 getF32Constant(DAG, 0x3e814304));
Owen Anderson9f944592009-08-11 20:47:22 +00004392 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004393 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson9f944592009-08-11 20:47:22 +00004394 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper85719442012-11-25 00:15:07 +00004395 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4396 getF32Constant(DAG, 0x3f7f5e7e));
Craig Toppered756c52012-11-16 20:01:39 +00004397 } else if (LimitFloatPrecision <= 12) {
Bill Wendling648930b2008-09-10 00:20:20 +00004398 // For floating-point precision of 12:
4399 //
4400 // TwoToFractionalPartOfX =
4401 // 0.999892986f +
4402 // (0.696457318f +
4403 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4404 //
4405 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004406 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004407 getF32Constant(DAG, 0x3da235e3));
Owen Anderson9f944592009-08-11 20:47:22 +00004408 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004409 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson9f944592009-08-11 20:47:22 +00004410 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4411 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004412 getF32Constant(DAG, 0x3f324b07));
Owen Anderson9f944592009-08-11 20:47:22 +00004413 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper85719442012-11-25 00:15:07 +00004414 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4415 getF32Constant(DAG, 0x3f7ff8fd));
Craig Toppered756c52012-11-16 20:01:39 +00004416 } else { // LimitFloatPrecision <= 18
Bill Wendling648930b2008-09-10 00:20:20 +00004417 // For floating-point precision of 18:
4418 //
4419 // TwoToFractionalPartOfX =
4420 // 0.999999982f +
4421 // (0.693148872f +
4422 // (0.240227044f +
4423 // (0.554906021e-1f +
4424 // (0.961591928e-2f +
4425 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4426 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004427 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004428 getF32Constant(DAG, 0x3924b03e));
Owen Anderson9f944592009-08-11 20:47:22 +00004429 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004430 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson9f944592009-08-11 20:47:22 +00004431 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4432 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004433 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson9f944592009-08-11 20:47:22 +00004434 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4435 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004436 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson9f944592009-08-11 20:47:22 +00004437 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4438 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004439 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson9f944592009-08-11 20:47:22 +00004440 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4441 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004442 getF32Constant(DAG, 0x3f317234));
Owen Anderson9f944592009-08-11 20:47:22 +00004443 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topper85719442012-11-25 00:15:07 +00004444 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4445 getF32Constant(DAG, 0x3f800000));
Bill Wendling648930b2008-09-10 00:20:20 +00004446 }
Craig Topper85719442012-11-25 00:15:07 +00004447
4448 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
Craig Topper79bd2052012-11-25 08:08:58 +00004449 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4450 DAG.getNode(ISD::ADD, dl, MVT::i32,
4451 t13, IntegerPartOfX));
Bill Wendling648930b2008-09-10 00:20:20 +00004452 }
4453
Craig Topper79bd2052012-11-25 08:08:58 +00004454 // No special expansion.
4455 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
Bill Wendling648930b2008-09-10 00:20:20 +00004456}
4457
Chris Lattner39f18e52010-01-01 03:32:16 +00004458
4459/// ExpandPowI - Expand a llvm.powi intrinsic.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004460static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
Chris Lattner39f18e52010-01-01 03:32:16 +00004461 SelectionDAG &DAG) {
4462 // If RHS is a constant, we can expand this out to a multiplication tree,
4463 // otherwise we end up lowering to a call to __powidf2 (for example). When
4464 // optimizing for size, we only want to do this if the expansion would produce
4465 // a small number of multiplies, otherwise we do the full expansion.
4466 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4467 // Get the exponent as a positive value.
4468 unsigned Val = RHSC->getSExtValue();
4469 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004470
Chris Lattner39f18e52010-01-01 03:32:16 +00004471 // powi(x, 0) -> 1.0
4472 if (Val == 0)
4473 return DAG.getConstantFP(1.0, LHS.getValueType());
4474
Dan Gohman913c9982010-04-15 04:33:49 +00004475 const Function *F = DAG.getMachineFunction().getFunction();
Bill Wendling698e84f2012-12-30 10:32:01 +00004476 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
4477 Attribute::OptimizeForSize) ||
Chris Lattner39f18e52010-01-01 03:32:16 +00004478 // If optimizing for size, don't insert too many multiplies. This
4479 // inserts up to 5 multiplies.
4480 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4481 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004482 // sequence. There are more optimal ways to do this (for example,
Chris Lattner39f18e52010-01-01 03:32:16 +00004483 // powi(x,15) generates one more multiply than it should), but this has
4484 // the benefit of being both really simple and much better than a libcall.
4485 SDValue Res; // Logically starts equal to 1.0
4486 SDValue CurSquare = LHS;
4487 while (Val) {
Mikhail Glushenkov5c35d2f2010-01-01 04:41:36 +00004488 if (Val & 1) {
Chris Lattner39f18e52010-01-01 03:32:16 +00004489 if (Res.getNode())
4490 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4491 else
4492 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkov5c35d2f2010-01-01 04:41:36 +00004493 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004494
Chris Lattner39f18e52010-01-01 03:32:16 +00004495 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4496 CurSquare, CurSquare);
4497 Val >>= 1;
4498 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004499
Chris Lattner39f18e52010-01-01 03:32:16 +00004500 // If the original was negative, invert the result, producing 1/(x*x*x).
4501 if (RHSC->getSExtValue() < 0)
4502 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4503 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4504 return Res;
4505 }
4506 }
4507
4508 // Otherwise, expand to a libcall.
4509 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4510}
4511
Devang Patel8e60ff12011-05-16 21:24:05 +00004512// getTruncatedArgReg - Find underlying register used for an truncated
4513// argument.
4514static unsigned getTruncatedArgReg(const SDValue &N) {
4515 if (N.getOpcode() != ISD::TRUNCATE)
4516 return 0;
4517
4518 const SDValue &Ext = N.getOperand(0);
Stephen Lin6d715e82013-07-06 21:44:25 +00004519 if (Ext.getOpcode() == ISD::AssertZext ||
4520 Ext.getOpcode() == ISD::AssertSext) {
Devang Patel8e60ff12011-05-16 21:24:05 +00004521 const SDValue &CFR = Ext.getOperand(0);
4522 if (CFR.getOpcode() == ISD::CopyFromReg)
4523 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
Craig Topper692d5842012-04-11 04:55:51 +00004524 if (CFR.getOpcode() == ISD::TRUNCATE)
4525 return getTruncatedArgReg(CFR);
Devang Patel8e60ff12011-05-16 21:24:05 +00004526 }
4527 return 0;
4528}
4529
Evan Cheng6e822452010-04-28 23:08:54 +00004530/// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4531/// argument, create the corresponding DBG_VALUE machine instruction for it now.
4532/// At the end of instruction selection, they will be inserted to the entry BB.
Evan Cheng5fb45a22010-04-29 01:40:30 +00004533bool
Devang Patel3f53d6e2010-08-25 20:39:26 +00004534SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00004535 int64_t Offset,
Dan Gohman63f31112010-05-01 00:33:16 +00004536 const SDValue &N) {
Devang Patel86ec8b32010-08-31 22:22:42 +00004537 const Argument *Arg = dyn_cast<Argument>(V);
4538 if (!Arg)
Evan Cheng5fb45a22010-04-29 01:40:30 +00004539 return false;
Evan Cheng6e822452010-04-28 23:08:54 +00004540
Devang Patel03955532010-04-29 20:40:36 +00004541 MachineFunction &MF = DAG.getMachineFunction();
Devang Patel94f2a252010-11-02 17:01:30 +00004542 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
Devang Patel94f2a252010-11-02 17:01:30 +00004543
Devang Patela46953d2010-04-29 18:50:36 +00004544 // Ignore inlined function arguments here.
4545 DIVariable DV(Variable);
Devang Patel03955532010-04-29 20:40:36 +00004546 if (DV.isInlinedFnArgument(MF.getFunction()))
Devang Patela46953d2010-04-29 18:50:36 +00004547 return false;
4548
David Blaikie0252265b2013-06-16 20:34:15 +00004549 Optional<MachineOperand> Op;
Devang Patel9d904e12011-09-08 22:59:09 +00004550 // Some arguments' frame index is recorded during argument lowering.
David Blaikie0252265b2013-06-16 20:34:15 +00004551 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4552 Op = MachineOperand::CreateFI(FI);
Devang Patel86ec8b32010-08-31 22:22:42 +00004553
David Blaikie0252265b2013-06-16 20:34:15 +00004554 if (!Op && N.getNode()) {
4555 unsigned Reg;
Devang Patel8e60ff12011-05-16 21:24:05 +00004556 if (N.getOpcode() == ISD::CopyFromReg)
4557 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4558 else
4559 Reg = getTruncatedArgReg(N);
4560 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
Evan Cheng6e822452010-04-28 23:08:54 +00004561 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4562 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4563 if (PR)
4564 Reg = PR;
4565 }
David Blaikie0252265b2013-06-16 20:34:15 +00004566 if (Reg)
4567 Op = MachineOperand::CreateReg(Reg, false);
Evan Cheng6e822452010-04-28 23:08:54 +00004568 }
4569
David Blaikie0252265b2013-06-16 20:34:15 +00004570 if (!Op) {
Devang Patel94f2a252010-11-02 17:01:30 +00004571 // Check if ValueMap has reg number.
Evan Cheng923679f2010-04-29 06:33:38 +00004572 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
Devang Patelbc741402010-11-02 17:19:03 +00004573 if (VMI != FuncInfo.ValueMap.end())
David Blaikie0252265b2013-06-16 20:34:15 +00004574 Op = MachineOperand::CreateReg(VMI->second, false);
Evan Cheng923679f2010-04-29 06:33:38 +00004575 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004576
David Blaikie0252265b2013-06-16 20:34:15 +00004577 if (!Op && N.getNode())
Devang Patel94f2a252010-11-02 17:01:30 +00004578 // Check if frame index is available.
4579 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
Wesley Peck527da1b2010-11-23 03:31:01 +00004580 if (FrameIndexSDNode *FINode =
David Blaikie0252265b2013-06-16 20:34:15 +00004581 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4582 Op = MachineOperand::CreateFI(FINode->getIndex());
Devang Patelbc741402010-11-02 17:19:03 +00004583
David Blaikie0252265b2013-06-16 20:34:15 +00004584 if (!Op)
Devang Patelbc741402010-11-02 17:19:03 +00004585 return false;
Devang Patel94f2a252010-11-02 17:01:30 +00004586
Adrian Prantlfacc9f42013-07-10 01:53:30 +00004587 // FIXME: This does not handle register-indirect values at offset 0.
4588 bool IsIndirect = Offset != 0;
David Blaikie0252265b2013-06-16 20:34:15 +00004589 if (Op->isReg())
Adrian Prantl418d1d12013-07-09 20:28:37 +00004590 FuncInfo.ArgDbgValues.push_back(BuildMI(MF, getCurDebugLoc(),
4591 TII->get(TargetOpcode::DBG_VALUE),
Adrian Prantlfacc9f42013-07-10 01:53:30 +00004592 IsIndirect,
Adrian Prantl418d1d12013-07-09 20:28:37 +00004593 Op->getReg(), Offset, Variable));
4594 else
4595 FuncInfo.ArgDbgValues.push_back(
David Blaikie0252265b2013-06-16 20:34:15 +00004596 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4597 .addOperand(*Op).addImm(Offset).addMetadata(Variable));
Adrian Prantl418d1d12013-07-09 20:28:37 +00004598
Evan Cheng5fb45a22010-04-29 01:40:30 +00004599 return true;
Evan Cheng6e822452010-04-28 23:08:54 +00004600}
Chris Lattner39f18e52010-01-01 03:32:16 +00004601
Douglas Gregor6739a892010-05-11 06:17:44 +00004602// VisualStudio defines setjmp as _setjmp
Michael J. Spencerded5f662010-09-24 19:48:47 +00004603#if defined(_MSC_VER) && defined(setjmp) && \
4604 !defined(setjmp_undefined_for_msvc)
4605# pragma push_macro("setjmp")
4606# undef setjmp
4607# define setjmp_undefined_for_msvc
Douglas Gregor6739a892010-05-11 06:17:44 +00004608#endif
4609
Dan Gohman575fad32008-09-03 16:12:24 +00004610/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4611/// we want to emit this as a call to a named external function, return the name
4612/// otherwise lower it and return null.
4613const char *
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004614SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004615 const TargetLowering *TLI = TM.getTargetLowering();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004616 SDLoc sdl = getCurSDLoc();
Dale Johannesendb7c5f62009-01-31 02:22:37 +00004617 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb99b2692009-12-22 00:40:51 +00004618 SDValue Res;
4619
Dan Gohman575fad32008-09-03 16:12:24 +00004620 switch (Intrinsic) {
4621 default:
4622 // By default, turn this into a target intrinsic node.
4623 visitTargetIntrinsic(I, Intrinsic);
4624 return 0;
4625 case Intrinsic::vastart: visitVAStart(I); return 0;
4626 case Intrinsic::vaend: visitVAEnd(I); return 0;
4627 case Intrinsic::vacopy: visitVACopy(I); return 0;
4628 case Intrinsic::returnaddress:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004629 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI->getPointerTy(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004630 getValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00004631 return 0;
Bill Wendlingc966a732008-09-26 22:10:44 +00004632 case Intrinsic::frameaddress:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004633 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI->getPointerTy(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004634 getValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00004635 return 0;
4636 case Intrinsic::setjmp:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004637 return &"_setjmp"[!TLI->usesUnderscoreSetJmp()];
Dan Gohman575fad32008-09-03 16:12:24 +00004638 case Intrinsic::longjmp:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004639 return &"_longjmp"[!TLI->usesUnderscoreLongJmp()];
Chris Lattnerdd708342008-11-21 16:42:48 +00004640 case Intrinsic::memcpy: {
Mon P Wangc576ee92010-04-04 03:10:48 +00004641 // Assert for address < 256 since we support only user defined address
4642 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004643 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004644 < 256 &&
Gabor Greifeba0be72010-06-25 09:38:13 +00004645 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004646 < 256 &&
4647 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004648 SDValue Op1 = getValue(I.getArgOperand(0));
4649 SDValue Op2 = getValue(I.getArgOperand(1));
4650 SDValue Op3 = getValue(I.getArgOperand(2));
4651 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004652 if (!Align)
4653 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004654 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004655 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
Chris Lattner2510de22010-09-21 05:40:29 +00004656 MachinePointerInfo(I.getArgOperand(0)),
4657 MachinePointerInfo(I.getArgOperand(1))));
Dan Gohman575fad32008-09-03 16:12:24 +00004658 return 0;
4659 }
Chris Lattnerdd708342008-11-21 16:42:48 +00004660 case Intrinsic::memset: {
Mon P Wangc576ee92010-04-04 03:10:48 +00004661 // Assert for address < 256 since we support only user defined address
4662 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004663 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004664 < 256 &&
4665 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004666 SDValue Op1 = getValue(I.getArgOperand(0));
4667 SDValue Op2 = getValue(I.getArgOperand(1));
4668 SDValue Op3 = getValue(I.getArgOperand(2));
4669 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004670 if (!Align)
4671 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004672 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004673 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
Chris Lattner2510de22010-09-21 05:40:29 +00004674 MachinePointerInfo(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00004675 return 0;
4676 }
Chris Lattnerdd708342008-11-21 16:42:48 +00004677 case Intrinsic::memmove: {
Mon P Wangc576ee92010-04-04 03:10:48 +00004678 // Assert for address < 256 since we support only user defined address
4679 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004680 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004681 < 256 &&
Gabor Greifeba0be72010-06-25 09:38:13 +00004682 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004683 < 256 &&
4684 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004685 SDValue Op1 = getValue(I.getArgOperand(0));
4686 SDValue Op2 = getValue(I.getArgOperand(1));
4687 SDValue Op3 = getValue(I.getArgOperand(2));
4688 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004689 if (!Align)
4690 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004691 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004692 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
Chris Lattner2510de22010-09-21 05:40:29 +00004693 MachinePointerInfo(I.getArgOperand(0)),
4694 MachinePointerInfo(I.getArgOperand(1))));
Dan Gohman575fad32008-09-03 16:12:24 +00004695 return 0;
4696 }
Bill Wendling65c0fd42009-02-13 02:16:35 +00004697 case Intrinsic::dbg_declare: {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004698 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Devang Pateldf45c7f2009-10-09 22:42:28 +00004699 MDNode *Variable = DI.getVariable();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004700 const Value *Address = DI.getAddress();
Manman Ren983a16c2013-06-28 05:43:10 +00004701 DIVariable DIVar(Variable);
4702 assert((!DIVar || DIVar.isVariable()) &&
4703 "Variable in DbgDeclareInst should be either null or a DIVariable.");
4704 if (!Address || !DIVar) {
Eric Christopherbe7a1012012-03-15 21:33:41 +00004705 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesen120cfe22010-02-08 21:53:27 +00004706 return 0;
Eric Christopherbe7a1012012-03-15 21:33:41 +00004707 }
Dale Johannesene0983522010-04-26 20:06:49 +00004708
Devang Patel3bffd522010-09-02 21:29:42 +00004709 // Check if address has undef value.
4710 if (isa<UndefValue>(Address) ||
4711 (Address->use_empty() && !isa<Argument>(Address))) {
Eric Christopher5c452052012-02-23 03:39:39 +00004712 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patel3bffd522010-09-02 21:29:42 +00004713 return 0;
4714 }
4715
Dale Johannesene0983522010-04-26 20:06:49 +00004716 SDValue &N = NodeMap[Address];
Devang Patel86ec8b32010-08-31 22:22:42 +00004717 if (!N.getNode() && isa<Argument>(Address))
4718 // Check unused arguments map.
4719 N = UnusedArgNodeMap[Address];
Dale Johannesene0983522010-04-26 20:06:49 +00004720 SDDbgValue *SDV;
4721 if (N.getNode()) {
Devang Patel98d3edf2010-09-02 21:02:27 +00004722 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4723 Address = BCI->getOperand(0);
Eric Christopherda970542012-02-24 01:59:08 +00004724 // Parameters are handled specially.
4725 bool isParameter =
4726 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4727 isa<Argument>(Address));
4728
Devang Patel98d3edf2010-09-02 21:02:27 +00004729 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4730
Dale Johannesene0983522010-04-26 20:06:49 +00004731 if (isParameter && !AI) {
4732 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4733 if (FINode)
4734 // Byval parameter. We have a frame index at this point.
4735 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4736 0, dl, SDNodeOrder);
Devang Patelc24048a2010-12-06 22:39:26 +00004737 else {
Devang Patel8e60ff12011-05-16 21:24:05 +00004738 // Address is an argument, so try to emit its dbg value using
4739 // virtual register info from the FuncInfo.ValueMap.
4740 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
Dale Johannesene0983522010-04-26 20:06:49 +00004741 return 0;
Devang Patelc24048a2010-12-06 22:39:26 +00004742 }
Dale Johannesene0983522010-04-26 20:06:49 +00004743 } else if (AI)
4744 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4745 0, dl, SDNodeOrder);
Devang Patelc24048a2010-12-06 22:39:26 +00004746 else {
Dale Johannesene0983522010-04-26 20:06:49 +00004747 // Can't do anything with other non-AI cases yet.
Eric Christopher5c452052012-02-23 03:39:39 +00004748 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Eric Christopherda970542012-02-24 01:59:08 +00004749 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4750 DEBUG(Address->dump());
Dale Johannesene0983522010-04-26 20:06:49 +00004751 return 0;
Devang Patelc24048a2010-12-06 22:39:26 +00004752 }
Dale Johannesene0983522010-04-26 20:06:49 +00004753 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4754 } else {
Gabor Greif47a3b8c2010-10-01 10:32:19 +00004755 // If Address is an argument then try to emit its dbg value using
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00004756 // virtual register info from the FuncInfo.ValueMap.
Devang Patelea134f52010-08-26 22:53:27 +00004757 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
Devang Patelda25de82010-09-15 14:48:53 +00004758 // If variable is pinned by a alloca in dominating bb then
4759 // use StaticAllocaMap.
4760 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
Devang Patel46b96c42010-09-15 18:13:55 +00004761 if (AI->getParent() != DI.getParent()) {
4762 DenseMap<const AllocaInst*, int>::iterator SI =
4763 FuncInfo.StaticAllocaMap.find(AI);
4764 if (SI != FuncInfo.StaticAllocaMap.end()) {
4765 SDV = DAG.getDbgValue(Variable, SI->second,
4766 0, dl, SDNodeOrder);
4767 DAG.AddDbgValue(SDV, 0, false);
4768 return 0;
4769 }
Devang Patelda25de82010-09-15 14:48:53 +00004770 }
4771 }
Eric Christopher18c6be72012-02-23 03:39:43 +00004772 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patelea134f52010-08-26 22:53:27 +00004773 }
Dale Johannesene0983522010-04-26 20:06:49 +00004774 }
Dan Gohman575fad32008-09-03 16:12:24 +00004775 return 0;
Bill Wendling65c0fd42009-02-13 02:16:35 +00004776 }
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004777 case Intrinsic::dbg_value: {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004778 const DbgValueInst &DI = cast<DbgValueInst>(I);
Manman Ren983a16c2013-06-28 05:43:10 +00004779 DIVariable DIVar(DI.getVariable());
4780 assert((!DIVar || DIVar.isVariable()) &&
4781 "Variable in DbgValueInst should be either null or a DIVariable.");
4782 if (!DIVar)
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004783 return 0;
4784
4785 MDNode *Variable = DI.getVariable();
Devang Patelf2bce7c2010-03-15 19:15:44 +00004786 uint64_t Offset = DI.getOffset();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004787 const Value *V = DI.getValue();
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004788 if (!V)
4789 return 0;
Devang Patelf2bce7c2010-03-15 19:15:44 +00004790
Dale Johannesene0983522010-04-26 20:06:49 +00004791 SDDbgValue *SDV;
Devang Patelaab841c2011-08-03 23:13:55 +00004792 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
Dale Johannesene0983522010-04-26 20:06:49 +00004793 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4794 DAG.AddDbgValue(SDV, 0, false);
Devang Patelf2bce7c2010-03-15 19:15:44 +00004795 } else {
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00004796 // Do not use getValue() in here; we don't want to generate code at
4797 // this point if it hasn't been done yet.
Devang Patelb0c76392010-06-01 19:59:01 +00004798 SDValue N = NodeMap[V];
4799 if (!N.getNode() && isa<Argument>(V))
4800 // Check unused arguments map.
4801 N = UnusedArgNodeMap[V];
Dale Johannesene0983522010-04-26 20:06:49 +00004802 if (N.getNode()) {
Devang Patel3f53d6e2010-08-25 20:39:26 +00004803 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
Evan Cheng5fb45a22010-04-29 01:40:30 +00004804 SDV = DAG.getDbgValue(Variable, N.getNode(),
4805 N.getResNo(), Offset, dl, SDNodeOrder);
4806 DAG.AddDbgValue(SDV, N.getNode(), false);
4807 }
Devang Patelb7ae3cc2011-02-18 22:43:42 +00004808 } else if (!V->use_empty() ) {
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00004809 // Do not call getValue(V) yet, as we don't want to generate code.
4810 // Remember it for later.
4811 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4812 DanglingDebugInfoMap[V] = DDI;
Devang Patelf2855b12010-08-27 22:25:51 +00004813 } else {
Devang Patelf2bce7c2010-03-15 19:15:44 +00004814 // We may expand this to cover more cases. One case where we have no
Devang Patelc24048a2010-12-06 22:39:26 +00004815 // data available is an unreferenced parameter.
Eric Christopher18c6be72012-02-23 03:39:43 +00004816 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesene0983522010-04-26 20:06:49 +00004817 }
Devang Patelf2bce7c2010-03-15 19:15:44 +00004818 }
4819
4820 // Build a debug info table entry.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004821 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004822 V = BCI->getOperand(0);
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004823 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004824 // Don't handle byval struct arguments or VLAs, for example.
Eric Christopherc1e2dcd2012-03-26 06:10:32 +00004825 if (!AI) {
Eric Christopher24a62982012-03-28 07:34:36 +00004826 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4827 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004828 return 0;
Eric Christopherc1e2dcd2012-03-26 06:10:32 +00004829 }
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004830 DenseMap<const AllocaInst*, int>::iterator SI =
4831 FuncInfo.StaticAllocaMap.find(AI);
4832 if (SI == FuncInfo.StaticAllocaMap.end())
4833 return 0; // VLAs.
4834 int FI = SI->second;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00004835
Chris Lattnerfb964e52010-04-05 06:19:28 +00004836 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4837 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4838 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004839 return 0;
4840 }
Dan Gohman575fad32008-09-03 16:12:24 +00004841
Duncan Sands8e6ccb62009-10-14 16:11:37 +00004842 case Intrinsic::eh_typeid_for: {
Chris Lattnerfb964e52010-04-05 06:19:28 +00004843 // Find the type id for the given typeinfo.
Gabor Greifeba0be72010-06-25 09:38:13 +00004844 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
Chris Lattnerfb964e52010-04-05 06:19:28 +00004845 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4846 Res = DAG.getConstant(TypeID, MVT::i32);
Bill Wendlingb99b2692009-12-22 00:40:51 +00004847 setValue(&I, Res);
Dan Gohman575fad32008-09-03 16:12:24 +00004848 return 0;
4849 }
4850
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004851 case Intrinsic::eh_return_i32:
4852 case Intrinsic::eh_return_i64:
Chris Lattnerfb964e52010-04-05 06:19:28 +00004853 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004854 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
Chris Lattnerfb964e52010-04-05 06:19:28 +00004855 MVT::Other,
4856 getControlRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004857 getValue(I.getArgOperand(0)),
4858 getValue(I.getArgOperand(1))));
Dan Gohman575fad32008-09-03 16:12:24 +00004859 return 0;
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004860 case Intrinsic::eh_unwind_init:
Chris Lattnerfb964e52010-04-05 06:19:28 +00004861 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004862 return 0;
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004863 case Intrinsic::eh_dwarf_cfa: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004864 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004865 TLI->getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004866 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
Tom Stellard838e2342013-08-26 15:06:10 +00004867 CfaArg.getValueType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004868 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
Tom Stellard838e2342013-08-26 15:06:10 +00004869 CfaArg.getValueType()),
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004870 CfaArg);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004871 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004872 TLI->getPointerTy(),
4873 DAG.getConstant(0, TLI->getPointerTy()));
Tom Stellard838e2342013-08-26 15:06:10 +00004874 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
Bill Wendling954cb182010-01-28 21:51:40 +00004875 FA, Offset));
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004876 return 0;
Dan Gohman575fad32008-09-03 16:12:24 +00004877 }
Jim Grosbach54c05302010-01-28 01:45:32 +00004878 case Intrinsic::eh_sjlj_callsite: {
Chris Lattnerfb964e52010-04-05 06:19:28 +00004879 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Gabor Greifeba0be72010-06-25 09:38:13 +00004880 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
Jim Grosbach54c05302010-01-28 01:45:32 +00004881 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
Chris Lattnerfb964e52010-04-05 06:19:28 +00004882 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
Jim Grosbach54c05302010-01-28 01:45:32 +00004883
Chris Lattnerfb964e52010-04-05 06:19:28 +00004884 MMI.setCurrentCallSite(CI->getZExtValue());
Jim Grosbach54c05302010-01-28 01:45:32 +00004885 return 0;
4886 }
Bill Wendling66b110f2011-09-28 03:36:43 +00004887 case Intrinsic::eh_sjlj_functioncontext: {
4888 // Get and store the index of the function context.
4889 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
Bill Wendlingbaf39412011-09-28 03:52:41 +00004890 AllocaInst *FnCtx =
4891 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
Bill Wendling66b110f2011-09-28 03:36:43 +00004892 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4893 MFI->setFunctionContextIndex(FI);
4894 return 0;
4895 }
Jim Grosbachc98892f2010-05-26 20:22:18 +00004896 case Intrinsic::eh_sjlj_setjmp: {
Bill Wendling7ecfbd92011-10-07 21:25:38 +00004897 SDValue Ops[2];
4898 Ops[0] = getRoot();
4899 Ops[1] = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004900 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
Bill Wendling7ecfbd92011-10-07 21:25:38 +00004901 DAG.getVTList(MVT::i32, MVT::Other),
4902 Ops, 2);
4903 setValue(&I, Op.getValue(0));
4904 DAG.setRoot(Op.getValue(1));
Jim Grosbachc98892f2010-05-26 20:22:18 +00004905 return 0;
4906 }
Jim Grosbachbd9485d2010-05-22 01:06:18 +00004907 case Intrinsic::eh_sjlj_longjmp: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004908 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
Jim Grosbachbbdc5d22010-10-19 23:27:08 +00004909 getRoot(), getValue(I.getArgOperand(0))));
4910 return 0;
4911 }
Jim Grosbach54c05302010-01-28 01:45:32 +00004912
Dale Johannesendd224d22010-09-30 23:57:10 +00004913 case Intrinsic::x86_mmx_pslli_w:
4914 case Intrinsic::x86_mmx_pslli_d:
4915 case Intrinsic::x86_mmx_pslli_q:
4916 case Intrinsic::x86_mmx_psrli_w:
4917 case Intrinsic::x86_mmx_psrli_d:
4918 case Intrinsic::x86_mmx_psrli_q:
4919 case Intrinsic::x86_mmx_psrai_w:
4920 case Intrinsic::x86_mmx_psrai_d: {
4921 SDValue ShAmt = getValue(I.getArgOperand(1));
4922 if (isa<ConstantSDNode>(ShAmt)) {
4923 visitTargetIntrinsic(I, Intrinsic);
4924 return 0;
4925 }
4926 unsigned NewIntrinsic = 0;
4927 EVT ShAmtVT = MVT::v2i32;
4928 switch (Intrinsic) {
4929 case Intrinsic::x86_mmx_pslli_w:
4930 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4931 break;
4932 case Intrinsic::x86_mmx_pslli_d:
4933 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4934 break;
4935 case Intrinsic::x86_mmx_pslli_q:
4936 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4937 break;
4938 case Intrinsic::x86_mmx_psrli_w:
4939 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4940 break;
4941 case Intrinsic::x86_mmx_psrli_d:
4942 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4943 break;
4944 case Intrinsic::x86_mmx_psrli_q:
4945 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4946 break;
4947 case Intrinsic::x86_mmx_psrai_w:
4948 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4949 break;
4950 case Intrinsic::x86_mmx_psrai_d:
4951 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4952 break;
4953 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4954 }
4955
4956 // The vector shift intrinsics with scalars uses 32b shift amounts but
4957 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4958 // to be zero.
4959 // We must do this early because v2i32 is not a legal type.
Dale Johannesendd224d22010-09-30 23:57:10 +00004960 SDValue ShOps[2];
4961 ShOps[0] = ShAmt;
4962 ShOps[1] = DAG.getConstant(0, MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004963 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, &ShOps[0], 2);
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004964 EVT DestVT = TLI->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004965 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4966 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
Dale Johannesendd224d22010-09-30 23:57:10 +00004967 DAG.getConstant(NewIntrinsic, MVT::i32),
4968 getValue(I.getArgOperand(0)), ShAmt);
4969 setValue(&I, Res);
4970 return 0;
4971 }
Pete Cooper682c76b2012-02-24 03:51:49 +00004972 case Intrinsic::x86_avx_vinsertf128_pd_256:
4973 case Intrinsic::x86_avx_vinsertf128_ps_256:
Craig Topperd024cef2012-04-07 22:32:29 +00004974 case Intrinsic::x86_avx_vinsertf128_si_256:
4975 case Intrinsic::x86_avx2_vinserti128: {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004976 EVT DestVT = TLI->getValueType(I.getType());
4977 EVT ElVT = TLI->getValueType(I.getArgOperand(1)->getType());
Pete Cooper682c76b2012-02-24 03:51:49 +00004978 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
4979 ElVT.getVectorNumElements();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004980 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
Pete Cooper682c76b2012-02-24 03:51:49 +00004981 getValue(I.getArgOperand(0)),
4982 getValue(I.getArgOperand(1)),
Tom Stellardd42c5942013-08-05 22:22:01 +00004983 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
Craig Topper2db23532012-09-05 05:48:09 +00004984 setValue(&I, Res);
4985 return 0;
4986 }
4987 case Intrinsic::x86_avx_vextractf128_pd_256:
4988 case Intrinsic::x86_avx_vextractf128_ps_256:
4989 case Intrinsic::x86_avx_vextractf128_si_256:
4990 case Intrinsic::x86_avx2_vextracti128: {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004991 EVT DestVT = TLI->getValueType(I.getType());
Craig Topper2db23532012-09-05 05:48:09 +00004992 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
4993 DestVT.getVectorNumElements();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004994 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
Craig Topper2db23532012-09-05 05:48:09 +00004995 getValue(I.getArgOperand(0)),
Tom Stellardd42c5942013-08-05 22:22:01 +00004996 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
Pete Cooper682c76b2012-02-24 03:51:49 +00004997 setValue(&I, Res);
4998 return 0;
4999 }
Mon P Wang58fb9132008-11-10 20:54:11 +00005000 case Intrinsic::convertff:
5001 case Intrinsic::convertfsi:
5002 case Intrinsic::convertfui:
5003 case Intrinsic::convertsif:
5004 case Intrinsic::convertuif:
5005 case Intrinsic::convertss:
5006 case Intrinsic::convertsu:
5007 case Intrinsic::convertus:
5008 case Intrinsic::convertuu: {
5009 ISD::CvtCode Code = ISD::CVT_INVALID;
5010 switch (Intrinsic) {
Craig Topperbc680062012-04-11 04:34:11 +00005011 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
Mon P Wang58fb9132008-11-10 20:54:11 +00005012 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
5013 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
5014 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
5015 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
5016 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
5017 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
5018 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
5019 case Intrinsic::convertus: Code = ISD::CVT_US; break;
5020 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
5021 }
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005022 EVT DestVT = TLI->getValueType(I.getType());
Gabor Greifeba0be72010-06-25 09:38:13 +00005023 const Value *Op1 = I.getArgOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005024 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
Bill Wendlingb99b2692009-12-22 00:40:51 +00005025 DAG.getValueType(DestVT),
5026 DAG.getValueType(getValue(Op1).getValueType()),
Gabor Greifeba0be72010-06-25 09:38:13 +00005027 getValue(I.getArgOperand(1)),
5028 getValue(I.getArgOperand(2)),
Bill Wendlingb99b2692009-12-22 00:40:51 +00005029 Code);
5030 setValue(&I, Res);
Mon P Wang58fb9132008-11-10 20:54:11 +00005031 return 0;
5032 }
Dan Gohman575fad32008-09-03 16:12:24 +00005033 case Intrinsic::powi:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005034 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
Gabor Greifeba0be72010-06-25 09:38:13 +00005035 getValue(I.getArgOperand(1)), DAG));
Dan Gohman575fad32008-09-03 16:12:24 +00005036 return 0;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005037 case Intrinsic::log:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005038 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Dale Johannesenda2d8062008-09-04 00:47:13 +00005039 return 0;
5040 case Intrinsic::log2:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005041 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Dale Johannesenda2d8062008-09-04 00:47:13 +00005042 return 0;
5043 case Intrinsic::log10:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005044 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Dale Johannesenda2d8062008-09-04 00:47:13 +00005045 return 0;
5046 case Intrinsic::exp:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005047 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Dale Johannesenda2d8062008-09-04 00:47:13 +00005048 return 0;
5049 case Intrinsic::exp2:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005050 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Dale Johannesenda2d8062008-09-04 00:47:13 +00005051 return 0;
Dan Gohman575fad32008-09-03 16:12:24 +00005052 case Intrinsic::pow:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005053 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005054 getValue(I.getArgOperand(1)), DAG, *TLI));
Dan Gohman575fad32008-09-03 16:12:24 +00005055 return 0;
Craig Topperae894262012-11-16 07:48:23 +00005056 case Intrinsic::sqrt:
Peter Collingbourne913869b2012-05-28 21:48:37 +00005057 case Intrinsic::fabs:
Craig Topperae894262012-11-16 07:48:23 +00005058 case Intrinsic::sin:
5059 case Intrinsic::cos:
Dan Gohman0b3d7822012-07-26 17:43:27 +00005060 case Intrinsic::floor:
Craig Topper61d04572012-11-15 06:51:10 +00005061 case Intrinsic::ceil:
Craig Topper61d04572012-11-15 06:51:10 +00005062 case Intrinsic::trunc:
Craig Topper61d04572012-11-15 06:51:10 +00005063 case Intrinsic::rint:
Hal Finkel171817e2013-08-07 22:49:12 +00005064 case Intrinsic::nearbyint:
5065 case Intrinsic::round: {
Craig Topperae894262012-11-16 07:48:23 +00005066 unsigned Opcode;
5067 switch (Intrinsic) {
5068 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5069 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5070 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5071 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5072 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5073 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5074 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5075 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5076 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5077 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
Hal Finkel171817e2013-08-07 22:49:12 +00005078 case Intrinsic::round: Opcode = ISD::FROUND; break;
Craig Topperae894262012-11-16 07:48:23 +00005079 }
5080
Andrew Trickef9de2a2013-05-25 02:42:55 +00005081 setValue(&I, DAG.getNode(Opcode, sdl,
Craig Topper61d04572012-11-15 06:51:10 +00005082 getValue(I.getArgOperand(0)).getValueType(),
5083 getValue(I.getArgOperand(0))));
5084 return 0;
Craig Topperae894262012-11-16 07:48:23 +00005085 }
Hal Finkel0c5c01aa2013-08-19 23:35:46 +00005086 case Intrinsic::copysign:
5087 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5088 getValue(I.getArgOperand(0)).getValueType(),
5089 getValue(I.getArgOperand(0)),
5090 getValue(I.getArgOperand(1))));
5091 return 0;
Cameron Zwarichf03fa182011-07-08 21:39:21 +00005092 case Intrinsic::fma:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005093 setValue(&I, DAG.getNode(ISD::FMA, sdl,
Cameron Zwarichf03fa182011-07-08 21:39:21 +00005094 getValue(I.getArgOperand(0)).getValueType(),
5095 getValue(I.getArgOperand(0)),
5096 getValue(I.getArgOperand(1)),
5097 getValue(I.getArgOperand(2))));
5098 return 0;
Lang Hamesa59100c2012-06-05 19:07:46 +00005099 case Intrinsic::fmuladd: {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005100 EVT VT = TLI->getValueType(I.getType());
Lang Hamesb8650f12012-06-22 01:09:09 +00005101 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00005102 TLI->isFMAFasterThanFMulAndFAdd(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005103 setValue(&I, DAG.getNode(ISD::FMA, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005104 getValue(I.getArgOperand(0)).getValueType(),
5105 getValue(I.getArgOperand(0)),
5106 getValue(I.getArgOperand(1)),
5107 getValue(I.getArgOperand(2))));
5108 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005109 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005110 getValue(I.getArgOperand(0)).getValueType(),
5111 getValue(I.getArgOperand(0)),
5112 getValue(I.getArgOperand(1)));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005113 SDValue Add = DAG.getNode(ISD::FADD, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005114 getValue(I.getArgOperand(0)).getValueType(),
5115 Mul,
5116 getValue(I.getArgOperand(2)));
5117 setValue(&I, Add);
5118 }
5119 return 0;
5120 }
Anton Korobeynikov39ed49d2010-03-14 18:42:15 +00005121 case Intrinsic::convert_to_fp16:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005122 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, sdl,
Gabor Greifeba0be72010-06-25 09:38:13 +00005123 MVT::i16, getValue(I.getArgOperand(0))));
Anton Korobeynikov39ed49d2010-03-14 18:42:15 +00005124 return 0;
5125 case Intrinsic::convert_from_fp16:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005126 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, sdl,
Gabor Greifeba0be72010-06-25 09:38:13 +00005127 MVT::f32, getValue(I.getArgOperand(0))));
Anton Korobeynikov39ed49d2010-03-14 18:42:15 +00005128 return 0;
Dan Gohman575fad32008-09-03 16:12:24 +00005129 case Intrinsic::pcmarker: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005130 SDValue Tmp = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005131 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
Dan Gohman575fad32008-09-03 16:12:24 +00005132 return 0;
5133 }
5134 case Intrinsic::readcyclecounter: {
5135 SDValue Op = getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005136 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
Bill Wendlingb99b2692009-12-22 00:40:51 +00005137 DAG.getVTList(MVT::i64, MVT::Other),
5138 &Op, 1);
5139 setValue(&I, Res);
5140 DAG.setRoot(Res.getValue(1));
Dan Gohman575fad32008-09-03 16:12:24 +00005141 return 0;
5142 }
Dan Gohman575fad32008-09-03 16:12:24 +00005143 case Intrinsic::bswap:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005144 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
Gabor Greifeba0be72010-06-25 09:38:13 +00005145 getValue(I.getArgOperand(0)).getValueType(),
5146 getValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00005147 return 0;
5148 case Intrinsic::cttz: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005149 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005150 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005151 EVT Ty = Arg.getValueType();
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005152 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005153 sdl, Ty, Arg));
Dan Gohman575fad32008-09-03 16:12:24 +00005154 return 0;
5155 }
5156 case Intrinsic::ctlz: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005157 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005158 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005159 EVT Ty = Arg.getValueType();
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005160 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005161 sdl, Ty, Arg));
Dan Gohman575fad32008-09-03 16:12:24 +00005162 return 0;
5163 }
5164 case Intrinsic::ctpop: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005165 SDValue Arg = getValue(I.getArgOperand(0));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005166 EVT Ty = Arg.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005167 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
Dan Gohman575fad32008-09-03 16:12:24 +00005168 return 0;
5169 }
5170 case Intrinsic::stacksave: {
5171 SDValue Op = getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005172 Res = DAG.getNode(ISD::STACKSAVE, sdl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005173 DAG.getVTList(TLI->getPointerTy(), MVT::Other), &Op, 1);
Bill Wendlingb99b2692009-12-22 00:40:51 +00005174 setValue(&I, Res);
5175 DAG.setRoot(Res.getValue(1));
Dan Gohman575fad32008-09-03 16:12:24 +00005176 return 0;
5177 }
5178 case Intrinsic::stackrestore: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005179 Res = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005180 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
Dan Gohman575fad32008-09-03 16:12:24 +00005181 return 0;
5182 }
Bill Wendling13020d22008-11-18 11:01:33 +00005183 case Intrinsic::stackprotector: {
Bill Wendlingd970ea32008-11-06 02:29:10 +00005184 // Emit code into the DAG to store the stack guard onto the stack.
5185 MachineFunction &MF = DAG.getMachineFunction();
5186 MachineFrameInfo *MFI = MF.getFrameInfo();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005187 EVT PtrTy = TLI->getPointerTy();
Bill Wendlingd970ea32008-11-06 02:29:10 +00005188
Gabor Greifeba0be72010-06-25 09:38:13 +00005189 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
5190 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
Bill Wendlingd970ea32008-11-06 02:29:10 +00005191
Bill Wendlingeb4268d2008-11-07 01:23:58 +00005192 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingd970ea32008-11-06 02:29:10 +00005193 MFI->setStackProtectorIndex(FI);
5194
5195 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5196
5197 // Store the stack protector onto the stack.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005198 Res = DAG.getStore(getRoot(), sdl, Src, FIN,
Chris Lattnera4f19972010-09-21 18:58:22 +00005199 MachinePointerInfo::getFixedStack(FI),
5200 true, false, 0);
Bill Wendlingb99b2692009-12-22 00:40:51 +00005201 setValue(&I, Res);
5202 DAG.setRoot(Res);
Bill Wendlingd970ea32008-11-06 02:29:10 +00005203 return 0;
5204 }
Eric Christopher7a50b282009-10-27 00:52:25 +00005205 case Intrinsic::objectsize: {
5206 // If we don't know by now, we're never going to know.
Gabor Greifeba0be72010-06-25 09:38:13 +00005207 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
Eric Christopher7a50b282009-10-27 00:52:25 +00005208
5209 assert(CI && "Non-constant type in __builtin_object_size?");
5210
Gabor Greifeba0be72010-06-25 09:38:13 +00005211 SDValue Arg = getValue(I.getCalledValue());
Eric Christopher1fd4c572009-10-28 21:32:16 +00005212 EVT Ty = Arg.getValueType();
5213
Dan Gohmanf1d83042010-06-18 14:22:04 +00005214 if (CI->isZero())
Bill Wendlingb99b2692009-12-22 00:40:51 +00005215 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7a50b282009-10-27 00:52:25 +00005216 else
Bill Wendlingb99b2692009-12-22 00:40:51 +00005217 Res = DAG.getConstant(0, Ty);
5218
5219 setValue(&I, Res);
Eric Christopher7a50b282009-10-27 00:52:25 +00005220 return 0;
5221 }
Justin Holewinskifff1f5f2013-05-21 14:37:16 +00005222 case Intrinsic::annotation:
5223 case Intrinsic::ptr_annotation:
5224 // Drop the intrinsic, but forward the value
5225 setValue(&I, getValue(I.getOperand(0)));
5226 return 0;
Dan Gohman575fad32008-09-03 16:12:24 +00005227 case Intrinsic::var_annotation:
5228 // Discard annotate attributes
5229 return 0;
5230
5231 case Intrinsic::init_trampoline: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005232 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
Dan Gohman575fad32008-09-03 16:12:24 +00005233
5234 SDValue Ops[6];
5235 Ops[0] = getRoot();
Gabor Greifeba0be72010-06-25 09:38:13 +00005236 Ops[1] = getValue(I.getArgOperand(0));
5237 Ops[2] = getValue(I.getArgOperand(1));
5238 Ops[3] = getValue(I.getArgOperand(2));
5239 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
Dan Gohman575fad32008-09-03 16:12:24 +00005240 Ops[5] = DAG.getSrcValue(F);
5241
Andrew Trickef9de2a2013-05-25 02:42:55 +00005242 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops, 6);
Dan Gohman575fad32008-09-03 16:12:24 +00005243
Duncan Sandsa0984362011-09-06 13:37:06 +00005244 DAG.setRoot(Res);
5245 return 0;
5246 }
5247 case Intrinsic::adjust_trampoline: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005248 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005249 TLI->getPointerTy(),
Duncan Sandsa0984362011-09-06 13:37:06 +00005250 getValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00005251 return 0;
5252 }
Dan Gohman575fad32008-09-03 16:12:24 +00005253 case Intrinsic::gcroot:
5254 if (GFI) {
Bill Wendlingb6b50c62012-05-01 22:50:45 +00005255 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
Gabor Greifeba0be72010-06-25 09:38:13 +00005256 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00005257
Dan Gohman575fad32008-09-03 16:12:24 +00005258 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5259 GFI->addStackRoot(FI->getIndex(), TypeMap);
5260 }
5261 return 0;
Dan Gohman575fad32008-09-03 16:12:24 +00005262 case Intrinsic::gcread:
5263 case Intrinsic::gcwrite:
Torok Edwinfbcc6632009-07-14 16:55:14 +00005264 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Bill Wendlingb99b2692009-12-22 00:40:51 +00005265 case Intrinsic::flt_rounds:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005266 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
Dan Gohman575fad32008-09-03 16:12:24 +00005267 return 0;
Jakub Staszak3f158fd2011-07-06 18:22:43 +00005268
5269 case Intrinsic::expect: {
5270 // Just replace __builtin_expect(exp, c) with EXP.
5271 setValue(&I, getValue(I.getArgOperand(0)));
5272 return 0;
5273 }
5274
Shuxin Yangcdde0592012-10-19 20:11:16 +00005275 case Intrinsic::debugtrap:
Evan Cheng74d92c12011-04-08 21:37:21 +00005276 case Intrinsic::trap: {
Nick Lewycky50f02cb2011-12-02 22:16:29 +00005277 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
Evan Cheng74d92c12011-04-08 21:37:21 +00005278 if (TrapFuncName.empty()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00005279 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
Shuxin Yangcdde0592012-10-19 20:11:16 +00005280 ISD::TRAP : ISD::DEBUGTRAP;
Andrew Trickef9de2a2013-05-25 02:42:55 +00005281 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
Evan Cheng74d92c12011-04-08 21:37:21 +00005282 return 0;
5283 }
5284 TargetLowering::ArgListTy Args;
Justin Holewinskiaa583972012-05-25 16:35:28 +00005285 TargetLowering::
5286 CallLoweringInfo CLI(getRoot(), I.getType(),
Evan Cheng74d92c12011-04-08 21:37:21 +00005287 false, false, false, false, 0, CallingConv::C,
Evan Cheng65f9d192012-02-28 18:51:51 +00005288 /*isTailCall=*/false,
5289 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005290 DAG.getExternalSymbol(TrapFuncName.data(),
5291 TLI->getPointerTy()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005292 Args, DAG, sdl);
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005293 std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
Evan Cheng74d92c12011-04-08 21:37:21 +00005294 DAG.setRoot(Result.second);
Dan Gohman575fad32008-09-03 16:12:24 +00005295 return 0;
Evan Cheng74d92c12011-04-08 21:37:21 +00005296 }
Shuxin Yangcdde0592012-10-19 20:11:16 +00005297
Bill Wendling5eee7442008-11-21 02:38:44 +00005298 case Intrinsic::uadd_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005299 case Intrinsic::sadd_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005300 case Intrinsic::usub_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005301 case Intrinsic::ssub_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005302 case Intrinsic::umul_with_overflow:
Craig Topperbc680062012-04-11 04:34:11 +00005303 case Intrinsic::smul_with_overflow: {
5304 ISD::NodeType Op;
5305 switch (Intrinsic) {
5306 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5307 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5308 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5309 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5310 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5311 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5312 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5313 }
5314 SDValue Op1 = getValue(I.getArgOperand(0));
5315 SDValue Op2 = getValue(I.getArgOperand(1));
Bill Wendling74296c62008-11-21 02:03:52 +00005316
Craig Topperbc680062012-04-11 04:34:11 +00005317 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005318 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
Craig Topperbc680062012-04-11 04:34:11 +00005319 return 0;
5320 }
Dan Gohman575fad32008-09-03 16:12:24 +00005321 case Intrinsic::prefetch: {
Bruno Cardoso Lopesdc9ff3a2011-06-14 04:58:37 +00005322 SDValue Ops[5];
Dale Johannesene660f4d2010-10-26 23:11:10 +00005323 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
Dan Gohman575fad32008-09-03 16:12:24 +00005324 Ops[0] = getRoot();
Gabor Greifeba0be72010-06-25 09:38:13 +00005325 Ops[1] = getValue(I.getArgOperand(0));
5326 Ops[2] = getValue(I.getArgOperand(1));
5327 Ops[3] = getValue(I.getArgOperand(2));
Bruno Cardoso Lopesdc9ff3a2011-06-14 04:58:37 +00005328 Ops[4] = getValue(I.getArgOperand(3));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005329 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
Dale Johannesene660f4d2010-10-26 23:11:10 +00005330 DAG.getVTList(MVT::Other),
Bruno Cardoso Lopesdc9ff3a2011-06-14 04:58:37 +00005331 &Ops[0], 5,
Dale Johannesene660f4d2010-10-26 23:11:10 +00005332 EVT::getIntegerVT(*Context, 8),
5333 MachinePointerInfo(I.getArgOperand(0)),
5334 0, /* align */
5335 false, /* volatile */
5336 rw==0, /* read */
5337 rw==1)); /* write */
Dan Gohman575fad32008-09-03 16:12:24 +00005338 return 0;
5339 }
Duncan Sandsdca0c282009-11-10 09:08:09 +00005340 case Intrinsic::lifetime_start:
Nadav Rotem7c277da2012-09-06 09:17:37 +00005341 case Intrinsic::lifetime_end: {
Nadav Rotem7c277da2012-09-06 09:17:37 +00005342 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
Nadav Rotemd753a952012-09-10 08:43:23 +00005343 // Stack coloring is not enabled in O0, discard region information.
5344 if (TM.getOptLevel() == CodeGenOpt::None)
5345 return 0;
Nadav Rotem7c277da2012-09-06 09:17:37 +00005346
Nadav Rotemd753a952012-09-10 08:43:23 +00005347 SmallVector<Value *, 4> Allocas;
Rafael Espindola5f57f462014-02-21 18:34:28 +00005348 GetUnderlyingObjects(I.getArgOperand(1), Allocas, DL);
Nadav Rotemd753a952012-09-10 08:43:23 +00005349
Craig Toppere1c1d362013-07-03 05:11:49 +00005350 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5351 E = Allocas.end(); Object != E; ++Object) {
Nadav Rotemd753a952012-09-10 08:43:23 +00005352 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5353
5354 // Could not find an Alloca.
5355 if (!LifetimeObject)
5356 continue;
5357
5358 int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
5359
5360 SDValue Ops[2];
5361 Ops[0] = getRoot();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005362 Ops[1] = DAG.getFrameIndex(FI, TLI->getPointerTy(), true);
Nadav Rotemd753a952012-09-10 08:43:23 +00005363 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5364
Andrew Trickef9de2a2013-05-25 02:42:55 +00005365 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops, 2);
Nadav Rotemd753a952012-09-10 08:43:23 +00005366 DAG.setRoot(Res);
5367 }
Nadav Rotemf04cbeb2013-02-01 19:25:23 +00005368 return 0;
Nadav Rotem7c277da2012-09-06 09:17:37 +00005369 }
5370 case Intrinsic::invariant_start:
Duncan Sandsdca0c282009-11-10 09:08:09 +00005371 // Discard region information.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005372 setValue(&I, DAG.getUNDEF(TLI->getPointerTy()));
Duncan Sandsdca0c282009-11-10 09:08:09 +00005373 return 0;
5374 case Intrinsic::invariant_end:
Duncan Sandsdca0c282009-11-10 09:08:09 +00005375 // Discard region information.
5376 return 0;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00005377 case Intrinsic::stackprotectorcheck: {
5378 // Do not actually emit anything for this basic block. Instead we initialize
5379 // the stack protector descriptor and export the guard variable so we can
5380 // access it in FinishBasicBlock.
5381 const BasicBlock *BB = I.getParent();
5382 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5383 ExportFromCurrentBlock(SPDescriptor.getGuard());
5384
5385 // Flush our exports since we are going to process a terminator.
5386 (void)getControlRoot();
5387 return 0;
5388 }
Renato Golinc0a3c1d2014-03-26 12:52:28 +00005389 case Intrinsic::clear_cache:
5390 return TLI->getClearCacheBuiltinName();
Nuno Lopesec9653b2012-06-28 22:30:12 +00005391 case Intrinsic::donothing:
5392 // ignore
5393 return 0;
Andrew Trick74f4c742013-10-31 17:18:24 +00005394 case Intrinsic::experimental_stackmap: {
5395 visitStackmap(I);
5396 return 0;
5397 }
5398 case Intrinsic::experimental_patchpoint_void:
5399 case Intrinsic::experimental_patchpoint_i64: {
5400 visitPatchpoint(I);
5401 return 0;
5402 }
Dan Gohman575fad32008-09-03 16:12:24 +00005403 }
5404}
5405
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005406void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00005407 bool isTailCall,
5408 MachineBasicBlock *LandingPad) {
Chris Lattner229907c2011-07-18 04:54:35 +00005409 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5410 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5411 Type *RetTy = FTy->getReturnType();
Chris Lattnerfb964e52010-04-05 06:19:28 +00005412 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Chris Lattner34adc8d2010-03-14 01:41:15 +00005413 MCSymbol *BeginLabel = 0;
Dan Gohman575fad32008-09-03 16:12:24 +00005414
5415 TargetLowering::ArgListTy Args;
5416 TargetLowering::ArgListEntry Entry;
5417 Args.reserve(CS.arg_size());
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005418
5419 // Check whether the function can return without sret-demotion.
Dan Gohmand7b5ce32010-07-10 09:00:22 +00005420 SmallVector<ISD::OutputArg, 4> Outs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005421 const TargetLowering *TLI = TM.getTargetLowering();
5422 GetReturnInfo(RetTy, CS.getAttributes(), Outs, *TLI);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005423
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005424 bool CanLowerReturn = TLI->CanLowerReturn(CS.getCallingConv(),
5425 DAG.getMachineFunction(),
5426 FTy->isVarArg(), Outs,
5427 FTy->getContext());
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005428
5429 SDValue DemoteStackSlot;
Chris Lattner1ffcf522010-09-21 16:36:31 +00005430 int DemoteStackIdx = -100;
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005431
5432 if (!CanLowerReturn) {
Reid Klecknerf5b76512014-01-31 23:50:57 +00005433 assert(!CS.hasInAllocaArgument() &&
5434 "sret demotion is incompatible with inalloca");
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005435 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005436 FTy->getReturnType());
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005437 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005438 FTy->getReturnType());
5439 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattner1ffcf522010-09-21 16:36:31 +00005440 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Chris Lattner229907c2011-07-18 04:54:35 +00005441 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005442
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005443 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI->getPointerTy());
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005444 Entry.Node = DemoteStackSlot;
5445 Entry.Ty = StackSlotPtrType;
5446 Entry.isSExt = false;
5447 Entry.isZExt = false;
5448 Entry.isInReg = false;
5449 Entry.isSRet = true;
5450 Entry.isNest = false;
5451 Entry.isByVal = false;
Stephen Linb8bd2322013-04-20 05:14:40 +00005452 Entry.isReturned = false;
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005453 Entry.Alignment = Align;
5454 Args.push_back(Entry);
5455 RetTy = Type::getVoidTy(FTy->getContext());
5456 }
5457
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005458 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005459 i != e; ++i) {
Rafael Espindolae53b7d12011-05-13 15:18:06 +00005460 const Value *V = *i;
5461
5462 // Skip empty types
5463 if (V->getType()->isEmptyTy())
5464 continue;
5465
5466 SDValue ArgNode = getValue(V);
5467 Entry.Node = ArgNode; Entry.Ty = V->getType();
Dan Gohman575fad32008-09-03 16:12:24 +00005468
Andrew Trick74f4c742013-10-31 17:18:24 +00005469 // Skip the first return-type Attribute to get to params.
5470 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
Dan Gohman575fad32008-09-03 16:12:24 +00005471 Args.push_back(Entry);
5472 }
5473
Chris Lattnerfb964e52010-04-05 06:19:28 +00005474 if (LandingPad) {
Dan Gohman575fad32008-09-03 16:12:24 +00005475 // Insert a label before the invoke call to mark the try range. This can be
5476 // used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005477 BeginLabel = MMI.getContext().CreateTempSymbol();
Jim Grosbach693e36a2009-08-11 00:09:57 +00005478
Jim Grosbach54c05302010-01-28 01:45:32 +00005479 // For SjLj, keep track of which landing pads go with which invokes
5480 // so as to maintain the ordering of pads in the LSDA.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005481 unsigned CallSiteIndex = MMI.getCurrentCallSite();
Jim Grosbach54c05302010-01-28 01:45:32 +00005482 if (CallSiteIndex) {
Chris Lattnerfb964e52010-04-05 06:19:28 +00005483 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
Bill Wendling267f3232011-10-05 22:24:35 +00005484 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
Bill Wendling3d11aa72011-10-04 22:00:35 +00005485
Jim Grosbach54c05302010-01-28 01:45:32 +00005486 // Now that the call site is handled, stop tracking it.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005487 MMI.setCurrentCallSite(0);
Jim Grosbach54c05302010-01-28 01:45:32 +00005488 }
5489
Dan Gohman575fad32008-09-03 16:12:24 +00005490 // Both PendingLoads and PendingExports must be flushed here;
5491 // this call might not return.
5492 (void)getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005493 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
Dan Gohman575fad32008-09-03 16:12:24 +00005494 }
5495
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005496 // Check if target-independent constraints permit a tail call here.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005497 // Target-dependent constraints are checked within TLI->LowerCallTo.
5498 if (isTailCall && !isInTailCallPosition(CS, *TLI))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005499 isTailCall = false;
5500
Justin Holewinskiaa583972012-05-25 16:35:28 +00005501 TargetLowering::
5502 CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005503 getCurSDLoc(), CS);
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005504 std::pair<SDValue,SDValue> Result = TLI->LowerCallTo(CLI);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005505 assert((isTailCall || Result.second.getNode()) &&
5506 "Non-null chain expected with non-tail call!");
5507 assert((Result.second.getNode() || !Result.first.getNode()) &&
5508 "Null value expected with tail call!");
Bill Wendlinga4d7df72009-12-22 00:50:32 +00005509 if (Result.first.getNode()) {
Dan Gohman575fad32008-09-03 16:12:24 +00005510 setValue(CS.getInstruction(), Result.first);
Bill Wendlinga4d7df72009-12-22 00:50:32 +00005511 } else if (!CanLowerReturn && Result.second.getNode()) {
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005512 // The instruction result is the result of loading from the
5513 // hidden sret parameter.
5514 SmallVector<EVT, 1> PVTs;
Chris Lattner229907c2011-07-18 04:54:35 +00005515 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005516
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005517 ComputeValueVTs(*TLI, PtrRetTy, PVTs);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005518 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5519 EVT PtrVT = PVTs[0];
Eli Friedman315a0c72012-05-25 00:09:29 +00005520
5521 SmallVector<EVT, 4> RetTys;
5522 SmallVector<uint64_t, 4> Offsets;
5523 RetTy = FTy->getReturnType();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005524 ComputeValueVTs(*TLI, RetTy, RetTys, &Offsets);
Eli Friedman315a0c72012-05-25 00:09:29 +00005525
5526 unsigned NumValues = RetTys.size();
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005527 SmallVector<SDValue, 4> Values(NumValues);
5528 SmallVector<SDValue, 4> Chains(NumValues);
5529
5530 for (unsigned i = 0; i < NumValues; ++i) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005531 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT,
Bill Wendlinga4d7df72009-12-22 00:50:32 +00005532 DemoteStackSlot,
5533 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005534 SDValue L = DAG.getLoad(RetTys[i], getCurSDLoc(), Result.second, Add,
Chris Lattner1ffcf522010-09-21 16:36:31 +00005535 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005536 false, false, false, 1);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005537 Values[i] = L;
5538 Chains[i] = L.getValue(1);
5539 }
Bill Wendlinga4d7df72009-12-22 00:50:32 +00005540
Andrew Trickef9de2a2013-05-25 02:42:55 +00005541 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005542 MVT::Other, &Chains[0], NumValues);
5543 PendingLoads.push_back(Chain);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00005544
Bill Wendling954cb182010-01-28 21:51:40 +00005545 setValue(CS.getInstruction(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005546 DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00005547 DAG.getVTList(&RetTys[0], RetTys.size()),
Eli Friedman315a0c72012-05-25 00:09:29 +00005548 &Values[0], Values.size()));
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005549 }
Bill Wendlinga4d7df72009-12-22 00:50:32 +00005550
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005551 if (!Result.second.getNode()) {
Andrew Trick74f4c742013-10-31 17:18:24 +00005552 // As a special case, a null chain means that a tail call has been emitted
5553 // and the DAG root is already updated.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005554 HasTailCall = true;
Tim Northoverdab4db52013-07-06 12:58:45 +00005555
5556 // Since there's no actual continuation from this block, nothing can be
5557 // relying on us setting vregs for them.
5558 PendingExports.clear();
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005559 } else {
5560 DAG.setRoot(Result.second);
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005561 }
Dan Gohman575fad32008-09-03 16:12:24 +00005562
Chris Lattnerfb964e52010-04-05 06:19:28 +00005563 if (LandingPad) {
Dan Gohman575fad32008-09-03 16:12:24 +00005564 // Insert a label at the end of the invoke call to mark the try range. This
5565 // can be used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005566 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005567 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
Dan Gohman575fad32008-09-03 16:12:24 +00005568
5569 // Inform MachineModuleInfo of range.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005570 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
Dan Gohman575fad32008-09-03 16:12:24 +00005571 }
5572}
5573
Chris Lattner1a32ede2009-12-24 00:37:38 +00005574/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5575/// value is equal or not-equal to zero.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005576static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00005577 for (const User *U : V->users()) {
5578 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005579 if (IC->isEquality())
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005580 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005581 if (C->isNullValue())
5582 continue;
5583 // Unknown instruction.
5584 return false;
5585 }
5586 return true;
5587}
5588
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005589static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
Chris Lattner229907c2011-07-18 04:54:35 +00005590 Type *LoadTy,
Chris Lattner1a32ede2009-12-24 00:37:38 +00005591 SelectionDAGBuilder &Builder) {
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005592
Chris Lattner1a32ede2009-12-24 00:37:38 +00005593 // Check to see if this load can be trivially constant folded, e.g. if the
5594 // input is from a string literal.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005595 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
Chris Lattner1a32ede2009-12-24 00:37:38 +00005596 // Cast pointer to the type we really want to load.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005597 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
Chris Lattner1a32ede2009-12-24 00:37:38 +00005598 PointerType::getUnqual(LoadTy));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005599
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005600 if (const Constant *LoadCst =
5601 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
Rafael Espindola5f57f462014-02-21 18:34:28 +00005602 Builder.DL))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005603 return Builder.getValue(LoadCst);
5604 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005605
Chris Lattner1a32ede2009-12-24 00:37:38 +00005606 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5607 // still constant memory, the input chain can be the entry node.
5608 SDValue Root;
5609 bool ConstantMemory = false;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005610
Chris Lattner1a32ede2009-12-24 00:37:38 +00005611 // Do not serialize (non-volatile) loads of constant memory with anything.
5612 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5613 Root = Builder.DAG.getEntryNode();
5614 ConstantMemory = true;
5615 } else {
5616 // Do not serialize non-volatile loads against each other.
5617 Root = Builder.DAG.getRoot();
5618 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005619
Chris Lattner1a32ede2009-12-24 00:37:38 +00005620 SDValue Ptr = Builder.getValue(PtrVal);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005621 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
Chris Lattner1ffcf522010-09-21 16:36:31 +00005622 Ptr, MachinePointerInfo(PtrVal),
David Greene39c6d012010-02-15 17:00:31 +00005623 false /*volatile*/,
Stephen Lincfe7f352013-07-08 00:37:03 +00005624 false /*nontemporal*/,
Pete Cooper82cd9e82011-11-08 18:42:53 +00005625 false /*isinvariant*/, 1 /* align=1 */);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005626
Chris Lattner1a32ede2009-12-24 00:37:38 +00005627 if (!ConstantMemory)
5628 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5629 return LoadVal;
5630}
5631
Richard Sandiforde3827752013-08-16 10:55:47 +00005632/// processIntegerCallValue - Record the value for an instruction that
5633/// produces an integer result, converting the type where necessary.
5634void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5635 SDValue Value,
5636 bool IsSigned) {
5637 EVT VT = TM.getTargetLowering()->getValueType(I.getType(), true);
5638 if (IsSigned)
5639 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5640 else
5641 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5642 setValue(&I, Value);
5643}
Chris Lattner1a32ede2009-12-24 00:37:38 +00005644
5645/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5646/// If so, return true and lower it, otherwise return false and it will be
5647/// lowered like a normal call.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005648bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
Chris Lattner1a32ede2009-12-24 00:37:38 +00005649 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
Gabor Greiff69acfe2010-06-30 12:55:46 +00005650 if (I.getNumArgOperands() != 3)
Chris Lattner1a32ede2009-12-24 00:37:38 +00005651 return false;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005652
Gabor Greifeba0be72010-06-25 09:38:13 +00005653 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
Duncan Sands19d0b472010-02-16 11:11:14 +00005654 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
Gabor Greifeba0be72010-06-25 09:38:13 +00005655 !I.getArgOperand(2)->getType()->isIntegerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00005656 !I.getType()->isIntegerTy())
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005657 return false;
5658
Richard Sandiforde3827752013-08-16 10:55:47 +00005659 const Value *Size = I.getArgOperand(2);
5660 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5661 if (CSize && CSize->getZExtValue() == 0) {
Richard Sandiford564681c2013-08-12 10:28:10 +00005662 EVT CallVT = TM.getTargetLowering()->getValueType(I.getType(), true);
5663 setValue(&I, DAG.getConstant(0, CallVT));
5664 return true;
5665 }
5666
Richard Sandiford564681c2013-08-12 10:28:10 +00005667 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5668 std::pair<SDValue, SDValue> Res =
5669 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
Richard Sandiforde3827752013-08-16 10:55:47 +00005670 getValue(LHS), getValue(RHS), getValue(Size),
5671 MachinePointerInfo(LHS),
5672 MachinePointerInfo(RHS));
Richard Sandiford564681c2013-08-12 10:28:10 +00005673 if (Res.first.getNode()) {
Richard Sandiforde3827752013-08-16 10:55:47 +00005674 processIntegerCallValue(I, Res.first, true);
5675 PendingLoads.push_back(Res.second);
Richard Sandiford564681c2013-08-12 10:28:10 +00005676 return true;
5677 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005678
Chris Lattner1a32ede2009-12-24 00:37:38 +00005679 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5680 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Richard Sandiforde3827752013-08-16 10:55:47 +00005681 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005682 bool ActuallyDoIt = true;
5683 MVT LoadVT;
Chris Lattner229907c2011-07-18 04:54:35 +00005684 Type *LoadTy;
Richard Sandiforde3827752013-08-16 10:55:47 +00005685 switch (CSize->getZExtValue()) {
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005686 default:
5687 LoadVT = MVT::Other;
5688 LoadTy = 0;
5689 ActuallyDoIt = false;
5690 break;
5691 case 2:
5692 LoadVT = MVT::i16;
Richard Sandiforde3827752013-08-16 10:55:47 +00005693 LoadTy = Type::getInt16Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005694 break;
5695 case 4:
5696 LoadVT = MVT::i32;
Richard Sandiforde3827752013-08-16 10:55:47 +00005697 LoadTy = Type::getInt32Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005698 break;
5699 case 8:
5700 LoadVT = MVT::i64;
Richard Sandiforde3827752013-08-16 10:55:47 +00005701 LoadTy = Type::getInt64Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005702 break;
5703 /*
5704 case 16:
5705 LoadVT = MVT::v4i32;
Richard Sandiforde3827752013-08-16 10:55:47 +00005706 LoadTy = Type::getInt32Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005707 LoadTy = VectorType::get(LoadTy, 4);
5708 break;
5709 */
5710 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005711
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005712 // This turns into unaligned loads. We only do this if the target natively
5713 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5714 // we'll only produce a small number of byte loads.
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005715
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005716 // Require that we can find a legal MVT, and only do this if the target
5717 // supports unaligned loads of that type. Expanding into byte loads would
5718 // bloat the code.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005719 const TargetLowering *TLI = TM.getTargetLowering();
Richard Sandiforde3827752013-08-16 10:55:47 +00005720 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
Matt Arsenault1b55dd92014-02-05 23:16:05 +00005721 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5722 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005723 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5724 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
Matt Arsenault1b55dd92014-02-05 23:16:05 +00005725 if (!TLI->isTypeLegal(LoadVT) ||
5726 !TLI->allowsUnalignedMemoryAccesses(LoadVT, SrcAS) ||
5727 !TLI->allowsUnalignedMemoryAccesses(LoadVT, DstAS))
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005728 ActuallyDoIt = false;
5729 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005730
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005731 if (ActuallyDoIt) {
5732 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5733 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005734
Andrew Trickef9de2a2013-05-25 02:42:55 +00005735 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005736 ISD::SETNE);
Richard Sandiforde3827752013-08-16 10:55:47 +00005737 processIntegerCallValue(I, Res, false);
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005738 return true;
5739 }
Chris Lattner1a32ede2009-12-24 00:37:38 +00005740 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005741
5742
Chris Lattner1a32ede2009-12-24 00:37:38 +00005743 return false;
5744}
5745
Richard Sandiford6f6d5512013-08-20 09:38:48 +00005746/// visitMemChrCall -- See if we can lower a memchr call into an optimized
5747/// form. If so, return true and lower it, otherwise return false and it
5748/// will be lowered like a normal call.
5749bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5750 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5751 if (I.getNumArgOperands() != 3)
5752 return false;
5753
5754 const Value *Src = I.getArgOperand(0);
5755 const Value *Char = I.getArgOperand(1);
5756 const Value *Length = I.getArgOperand(2);
5757 if (!Src->getType()->isPointerTy() ||
5758 !Char->getType()->isIntegerTy() ||
5759 !Length->getType()->isIntegerTy() ||
5760 !I.getType()->isPointerTy())
5761 return false;
5762
5763 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5764 std::pair<SDValue, SDValue> Res =
5765 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5766 getValue(Src), getValue(Char), getValue(Length),
5767 MachinePointerInfo(Src));
5768 if (Res.first.getNode()) {
5769 setValue(&I, Res.first);
5770 PendingLoads.push_back(Res.second);
5771 return true;
5772 }
5773
5774 return false;
5775}
5776
Richard Sandifordbb83a502013-08-16 11:29:37 +00005777/// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5778/// optimized form. If so, return true and lower it, otherwise return false
5779/// and it will be lowered like a normal call.
5780bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5781 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5782 if (I.getNumArgOperands() != 2)
5783 return false;
5784
5785 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5786 if (!Arg0->getType()->isPointerTy() ||
5787 !Arg1->getType()->isPointerTy() ||
5788 !I.getType()->isPointerTy())
5789 return false;
5790
5791 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5792 std::pair<SDValue, SDValue> Res =
5793 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5794 getValue(Arg0), getValue(Arg1),
5795 MachinePointerInfo(Arg0),
5796 MachinePointerInfo(Arg1), isStpcpy);
5797 if (Res.first.getNode()) {
5798 setValue(&I, Res.first);
5799 DAG.setRoot(Res.second);
5800 return true;
5801 }
5802
5803 return false;
5804}
5805
Richard Sandifordca232712013-08-16 11:21:54 +00005806/// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5807/// If so, return true and lower it, otherwise return false and it will be
5808/// lowered like a normal call.
5809bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5810 // Verify that the prototype makes sense. int strcmp(void*,void*)
5811 if (I.getNumArgOperands() != 2)
5812 return false;
5813
5814 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5815 if (!Arg0->getType()->isPointerTy() ||
5816 !Arg1->getType()->isPointerTy() ||
5817 !I.getType()->isIntegerTy())
5818 return false;
5819
5820 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5821 std::pair<SDValue, SDValue> Res =
5822 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5823 getValue(Arg0), getValue(Arg1),
5824 MachinePointerInfo(Arg0),
5825 MachinePointerInfo(Arg1));
5826 if (Res.first.getNode()) {
5827 processIntegerCallValue(I, Res.first, true);
5828 PendingLoads.push_back(Res.second);
5829 return true;
5830 }
5831
5832 return false;
5833}
5834
Richard Sandiford0dec06a2013-08-16 11:41:43 +00005835/// visitStrLenCall -- See if we can lower a strlen call into an optimized
5836/// form. If so, return true and lower it, otherwise return false and it
5837/// will be lowered like a normal call.
5838bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5839 // Verify that the prototype makes sense. size_t strlen(char *)
5840 if (I.getNumArgOperands() != 1)
5841 return false;
5842
5843 const Value *Arg0 = I.getArgOperand(0);
5844 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5845 return false;
5846
5847 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5848 std::pair<SDValue, SDValue> Res =
5849 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5850 getValue(Arg0), MachinePointerInfo(Arg0));
5851 if (Res.first.getNode()) {
5852 processIntegerCallValue(I, Res.first, false);
5853 PendingLoads.push_back(Res.second);
5854 return true;
5855 }
5856
5857 return false;
5858}
5859
5860/// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5861/// form. If so, return true and lower it, otherwise return false and it
5862/// will be lowered like a normal call.
5863bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5864 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5865 if (I.getNumArgOperands() != 2)
5866 return false;
5867
5868 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5869 if (!Arg0->getType()->isPointerTy() ||
5870 !Arg1->getType()->isIntegerTy() ||
5871 !I.getType()->isIntegerTy())
5872 return false;
5873
5874 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5875 std::pair<SDValue, SDValue> Res =
5876 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5877 getValue(Arg0), getValue(Arg1),
5878 MachinePointerInfo(Arg0));
5879 if (Res.first.getNode()) {
5880 processIntegerCallValue(I, Res.first, false);
5881 PendingLoads.push_back(Res.second);
5882 return true;
5883 }
5884
5885 return false;
5886}
5887
Bob Wilson874886c2012-08-03 23:29:17 +00005888/// visitUnaryFloatCall - If a call instruction is a unary floating-point
5889/// operation (as expected), translate it to an SDNode with the specified opcode
5890/// and return true.
5891bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5892 unsigned Opcode) {
5893 // Sanity check that it really is a unary floating-point call.
5894 if (I.getNumArgOperands() != 1 ||
5895 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5896 I.getType() != I.getArgOperand(0)->getType() ||
5897 !I.onlyReadsMemory())
5898 return false;
5899
5900 SDValue Tmp = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005901 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
Bob Wilson874886c2012-08-03 23:29:17 +00005902 return true;
5903}
Chris Lattner1a32ede2009-12-24 00:37:38 +00005904
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005905void SelectionDAGBuilder::visitCall(const CallInst &I) {
Chris Lattner2c0315a2010-07-05 05:36:21 +00005906 // Handle inline assembly differently.
5907 if (isa<InlineAsm>(I.getCalledValue())) {
5908 visitInlineAsm(&I);
5909 return;
5910 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00005911
Michael J. Spencer0e36e032010-10-21 20:49:23 +00005912 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Michael J. Spencer8b98bf22012-02-22 19:06:13 +00005913 ComputeUsesVAFloatArgument(I, &MMI);
Michael J. Spencer0e36e032010-10-21 20:49:23 +00005914
Dan Gohman575fad32008-09-03 16:12:24 +00005915 const char *RenameFn = 0;
5916 if (Function *F = I.getCalledFunction()) {
5917 if (F->isDeclaration()) {
Chris Lattner2c0315a2010-07-05 05:36:21 +00005918 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
Dale Johannesenb842d522009-02-05 01:49:45 +00005919 if (unsigned IID = II->getIntrinsicID(F)) {
5920 RenameFn = visitIntrinsicCall(I, IID);
5921 if (!RenameFn)
5922 return;
5923 }
5924 }
Dan Gohman575fad32008-09-03 16:12:24 +00005925 if (unsigned IID = F->getIntrinsicID()) {
5926 RenameFn = visitIntrinsicCall(I, IID);
5927 if (!RenameFn)
5928 return;
5929 }
5930 }
5931
5932 // Check for well-known libc/libm calls. If the function is internal, it
5933 // can't be a library call.
Bob Wilson871701c2012-08-03 21:26:24 +00005934 LibFunc::Func Func;
5935 if (!F->hasLocalLinkage() && F->hasName() &&
5936 LibInfo->getLibFunc(F->getName(), Func) &&
5937 LibInfo->hasOptimizedCodeGen(Func)) {
5938 switch (Func) {
5939 default: break;
5940 case LibFunc::copysign:
5941 case LibFunc::copysignf:
5942 case LibFunc::copysignl:
Gabor Greiff69acfe2010-06-30 12:55:46 +00005943 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
Gabor Greifeba0be72010-06-25 09:38:13 +00005944 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5945 I.getType() == I.getArgOperand(0)->getType() &&
Bob Wilson874886c2012-08-03 23:29:17 +00005946 I.getType() == I.getArgOperand(1)->getType() &&
5947 I.onlyReadsMemory()) {
Gabor Greifeba0be72010-06-25 09:38:13 +00005948 SDValue LHS = getValue(I.getArgOperand(0));
5949 SDValue RHS = getValue(I.getArgOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005950 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
Bill Wendling0602f392009-12-23 01:28:19 +00005951 LHS.getValueType(), LHS, RHS));
Dan Gohman575fad32008-09-03 16:12:24 +00005952 return;
5953 }
Bob Wilson871701c2012-08-03 21:26:24 +00005954 break;
5955 case LibFunc::fabs:
5956 case LibFunc::fabsf:
5957 case LibFunc::fabsl:
Bob Wilson874886c2012-08-03 23:29:17 +00005958 if (visitUnaryFloatCall(I, ISD::FABS))
Dan Gohman575fad32008-09-03 16:12:24 +00005959 return;
Bob Wilson871701c2012-08-03 21:26:24 +00005960 break;
5961 case LibFunc::sin:
5962 case LibFunc::sinf:
5963 case LibFunc::sinl:
Bob Wilson874886c2012-08-03 23:29:17 +00005964 if (visitUnaryFloatCall(I, ISD::FSIN))
Dan Gohman575fad32008-09-03 16:12:24 +00005965 return;
Bob Wilson871701c2012-08-03 21:26:24 +00005966 break;
5967 case LibFunc::cos:
5968 case LibFunc::cosf:
5969 case LibFunc::cosl:
Bob Wilson874886c2012-08-03 23:29:17 +00005970 if (visitUnaryFloatCall(I, ISD::FCOS))
Dan Gohman575fad32008-09-03 16:12:24 +00005971 return;
Bob Wilson871701c2012-08-03 21:26:24 +00005972 break;
5973 case LibFunc::sqrt:
5974 case LibFunc::sqrtf:
5975 case LibFunc::sqrtl:
Preston Gurd048f99d2013-05-27 15:44:35 +00005976 case LibFunc::sqrt_finite:
5977 case LibFunc::sqrtf_finite:
5978 case LibFunc::sqrtl_finite:
Bob Wilson874886c2012-08-03 23:29:17 +00005979 if (visitUnaryFloatCall(I, ISD::FSQRT))
Dale Johannesenc7213422009-09-25 17:23:22 +00005980 return;
Bob Wilson871701c2012-08-03 21:26:24 +00005981 break;
5982 case LibFunc::floor:
5983 case LibFunc::floorf:
5984 case LibFunc::floorl:
Bob Wilson874886c2012-08-03 23:29:17 +00005985 if (visitUnaryFloatCall(I, ISD::FFLOOR))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00005986 return;
Bob Wilson871701c2012-08-03 21:26:24 +00005987 break;
5988 case LibFunc::nearbyint:
5989 case LibFunc::nearbyintf:
5990 case LibFunc::nearbyintl:
Bob Wilson874886c2012-08-03 23:29:17 +00005991 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00005992 return;
Bob Wilson871701c2012-08-03 21:26:24 +00005993 break;
5994 case LibFunc::ceil:
5995 case LibFunc::ceilf:
5996 case LibFunc::ceill:
Bob Wilson874886c2012-08-03 23:29:17 +00005997 if (visitUnaryFloatCall(I, ISD::FCEIL))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00005998 return;
Bob Wilson871701c2012-08-03 21:26:24 +00005999 break;
6000 case LibFunc::rint:
6001 case LibFunc::rintf:
6002 case LibFunc::rintl:
Bob Wilson874886c2012-08-03 23:29:17 +00006003 if (visitUnaryFloatCall(I, ISD::FRINT))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006004 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006005 break;
Hal Finkel171817e2013-08-07 22:49:12 +00006006 case LibFunc::round:
6007 case LibFunc::roundf:
6008 case LibFunc::roundl:
6009 if (visitUnaryFloatCall(I, ISD::FROUND))
6010 return;
6011 break;
Bob Wilson871701c2012-08-03 21:26:24 +00006012 case LibFunc::trunc:
6013 case LibFunc::truncf:
6014 case LibFunc::truncl:
Bob Wilson874886c2012-08-03 23:29:17 +00006015 if (visitUnaryFloatCall(I, ISD::FTRUNC))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006016 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006017 break;
6018 case LibFunc::log2:
6019 case LibFunc::log2f:
6020 case LibFunc::log2l:
Bob Wilson874886c2012-08-03 23:29:17 +00006021 if (visitUnaryFloatCall(I, ISD::FLOG2))
Owen Andersone7f329f2011-12-15 00:54:12 +00006022 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006023 break;
6024 case LibFunc::exp2:
6025 case LibFunc::exp2f:
6026 case LibFunc::exp2l:
Bob Wilson874886c2012-08-03 23:29:17 +00006027 if (visitUnaryFloatCall(I, ISD::FEXP2))
Owen Andersone7f329f2011-12-15 00:54:12 +00006028 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006029 break;
6030 case LibFunc::memcmp:
Chris Lattner1a32ede2009-12-24 00:37:38 +00006031 if (visitMemCmpCall(I))
6032 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006033 break;
Richard Sandiford6f6d5512013-08-20 09:38:48 +00006034 case LibFunc::memchr:
6035 if (visitMemChrCall(I))
6036 return;
6037 break;
Richard Sandifordbb83a502013-08-16 11:29:37 +00006038 case LibFunc::strcpy:
6039 if (visitStrCpyCall(I, false))
6040 return;
6041 break;
6042 case LibFunc::stpcpy:
6043 if (visitStrCpyCall(I, true))
6044 return;
6045 break;
Richard Sandifordca232712013-08-16 11:21:54 +00006046 case LibFunc::strcmp:
6047 if (visitStrCmpCall(I))
6048 return;
6049 break;
Richard Sandiford0dec06a2013-08-16 11:41:43 +00006050 case LibFunc::strlen:
6051 if (visitStrLenCall(I))
6052 return;
6053 break;
6054 case LibFunc::strnlen:
6055 if (visitStrNLenCall(I))
6056 return;
6057 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006058 }
6059 }
Dan Gohman575fad32008-09-03 16:12:24 +00006060 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006061
Dan Gohman575fad32008-09-03 16:12:24 +00006062 SDValue Callee;
6063 if (!RenameFn)
Gabor Greifeba0be72010-06-25 09:38:13 +00006064 Callee = getValue(I.getCalledValue());
Dan Gohman575fad32008-09-03 16:12:24 +00006065 else
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006066 Callee = DAG.getExternalSymbol(RenameFn,
6067 TM.getTargetLowering()->getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00006068
Bill Wendling0602f392009-12-23 01:28:19 +00006069 // Check if we can potentially perform a tail call. More detailed checking is
6070 // be done within LowerCallTo, after more information about the call is known.
Evan Chengc35b5a12010-01-26 23:13:04 +00006071 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohman575fad32008-09-03 16:12:24 +00006072}
6073
Benjamin Kramer355ce072011-03-26 16:35:10 +00006074namespace {
Dan Gohman4db93c92010-05-29 17:53:24 +00006075
Dan Gohman575fad32008-09-03 16:12:24 +00006076/// AsmOperandInfo - This contains information for each constraint that we are
6077/// lowering.
Benjamin Kramer355ce072011-03-26 16:35:10 +00006078class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
Cedric Venetd1e179d2009-02-14 16:06:42 +00006079public:
Dan Gohman575fad32008-09-03 16:12:24 +00006080 /// CallOperand - If this is the result output operand or a clobber
6081 /// this is null, otherwise it is the incoming operand to the CallInst.
6082 /// This gets modified as the asm is processed.
6083 SDValue CallOperand;
6084
6085 /// AssignedRegs - If this is a register or register class operand, this
6086 /// contains the set of register corresponding to the operand.
6087 RegsForValue AssignedRegs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006088
John Thompson1094c802010-09-13 18:15:37 +00006089 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
Dan Gohman575fad32008-09-03 16:12:24 +00006090 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
6091 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006092
Owen Anderson53aa7a92009-08-10 22:56:29 +00006093 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner3b1833c2008-10-17 17:05:25 +00006094 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson9f944592009-08-11 20:47:22 +00006095 /// MVT::Other.
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00006096 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson55f1c092009-08-13 21:58:54 +00006097 const TargetLowering &TLI,
Rafael Espindola5f57f462014-02-21 18:34:28 +00006098 const DataLayout *DL) const {
Owen Anderson9f944592009-08-11 20:47:22 +00006099 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006100
Chris Lattner3b1833c2008-10-17 17:05:25 +00006101 if (isa<BasicBlock>(CallOperandVal))
6102 return TLI.getPointerTy();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006103
Chris Lattner229907c2011-07-18 04:54:35 +00006104 llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006105
Eric Christopher44804282011-05-09 20:04:43 +00006106 // FIXME: code duplicated from TargetLowering::ParseConstraints().
Chris Lattner3b1833c2008-10-17 17:05:25 +00006107 // If this is an indirect operand, the operand is a pointer to the
6108 // accessed type.
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006109 if (isIndirect) {
Chris Lattner229907c2011-07-18 04:54:35 +00006110 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006111 if (!PtrTy)
Chris Lattner2104b8d2010-04-07 22:58:41 +00006112 report_fatal_error("Indirect operand for inline asm not a pointer!");
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006113 OpTy = PtrTy->getElementType();
6114 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006115
Eric Christopher44804282011-05-09 20:04:43 +00006116 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattner229907c2011-07-18 04:54:35 +00006117 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christopher44804282011-05-09 20:04:43 +00006118 if (STy->getNumElements() == 1)
6119 OpTy = STy->getElementType(0);
6120
Chris Lattner3b1833c2008-10-17 17:05:25 +00006121 // If OpTy is not a single value, it may be a struct/union that we
6122 // can tile with integers.
6123 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Rafael Espindola5f57f462014-02-21 18:34:28 +00006124 unsigned BitSize = DL->getTypeSizeInBits(OpTy);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006125 switch (BitSize) {
6126 default: break;
6127 case 1:
6128 case 8:
6129 case 16:
6130 case 32:
6131 case 64:
Chris Lattneraadf7412008-10-17 19:59:51 +00006132 case 128:
Owen Anderson55f1c092009-08-13 21:58:54 +00006133 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006134 break;
6135 }
6136 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006137
Chris Lattner3b1833c2008-10-17 17:05:25 +00006138 return TLI.getValueType(OpTy, true);
6139 }
Dan Gohman575fad32008-09-03 16:12:24 +00006140};
Dan Gohman4db93c92010-05-29 17:53:24 +00006141
John Thompsone8360b72010-10-29 17:29:13 +00006142typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6143
Benjamin Kramer355ce072011-03-26 16:35:10 +00006144} // end anonymous namespace
Dan Gohman575fad32008-09-03 16:12:24 +00006145
Dan Gohman575fad32008-09-03 16:12:24 +00006146/// GetRegistersForValue - Assign registers (virtual or physical) for the
6147/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson1c00b692009-12-17 05:07:36 +00006148/// register allocator to handle the assignment process. However, if the asm
6149/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohman575fad32008-09-03 16:12:24 +00006150/// allocation. This produces generally horrible, but correct, code.
6151///
6152/// OpInfo describes the operand.
Dan Gohman575fad32008-09-03 16:12:24 +00006153///
Benjamin Kramer355ce072011-03-26 16:35:10 +00006154static void GetRegistersForValue(SelectionDAG &DAG,
6155 const TargetLowering &TLI,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006156 SDLoc DL,
Benjamin Kramer6fe3e3d2012-02-24 14:01:17 +00006157 SDISelAsmOperandInfo &OpInfo) {
Benjamin Kramer355ce072011-03-26 16:35:10 +00006158 LLVMContext &Context = *DAG.getContext();
Owen Anderson117c9e82009-08-12 00:36:31 +00006159
Dan Gohman575fad32008-09-03 16:12:24 +00006160 MachineFunction &MF = DAG.getMachineFunction();
6161 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006162
Dan Gohman575fad32008-09-03 16:12:24 +00006163 // If this is a constraint for a single physreg, or a constraint for a
6164 // register class, find it.
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006165 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohman575fad32008-09-03 16:12:24 +00006166 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6167 OpInfo.ConstraintVT);
6168
6169 unsigned NumRegs = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00006170 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner4396e0d2008-10-21 00:45:36 +00006171 // If this is a FP input in an integer register (or visa versa) insert a bit
6172 // cast of the input value. More generally, handle any case where the input
6173 // value disagrees with the register class we plan to stick this in.
6174 if (OpInfo.Type == InlineAsm::isInput &&
6175 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006176 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner4396e0d2008-10-21 00:45:36 +00006177 // types are identical size, use a bitcast to convert (e.g. two differing
6178 // vector types).
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006179 MVT RegVT = *PhysReg.second->vt_begin();
Kevin Qin275ce912014-03-21 02:14:50 +00006180 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
Benjamin Kramer355ce072011-03-26 16:35:10 +00006181 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesened255b32009-01-30 01:34:22 +00006182 RegVT, OpInfo.CallOperand);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006183 OpInfo.ConstraintVT = RegVT;
6184 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6185 // If the input is a FP value and we want it in FP registers, do a
6186 // bitcast to the corresponding integer type. This turns an f64 value
6187 // into i64, which can be passed with two i32 values on a 32-bit
6188 // machine.
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006189 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Benjamin Kramer355ce072011-03-26 16:35:10 +00006190 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesened255b32009-01-30 01:34:22 +00006191 RegVT, OpInfo.CallOperand);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006192 OpInfo.ConstraintVT = RegVT;
6193 }
6194 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006195
Owen Anderson117c9e82009-08-12 00:36:31 +00006196 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006197 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006198
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006199 MVT RegVT;
Owen Anderson53aa7a92009-08-10 22:56:29 +00006200 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohman575fad32008-09-03 16:12:24 +00006201
6202 // If this is a constraint for a specific physical register, like {r17},
6203 // assign it now.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006204 if (unsigned AssignedReg = PhysReg.first) {
6205 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson9f944592009-08-11 20:47:22 +00006206 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnerc35847e2009-03-24 15:27:37 +00006207 ValueVT = *RC->vt_begin();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006208
Dan Gohman575fad32008-09-03 16:12:24 +00006209 // Get the actual register value type. This is important, because the user
6210 // may have asked for (e.g.) the AX register in i32 type. We need to
6211 // remember that AX is actually i16 to get the right extension.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006212 RegVT = *RC->vt_begin();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006213
Dan Gohman575fad32008-09-03 16:12:24 +00006214 // This is a explicit reference to a physical register.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006215 Regs.push_back(AssignedReg);
Dan Gohman575fad32008-09-03 16:12:24 +00006216
6217 // If this is an expanded reference, add the rest of the regs to Regs.
6218 if (NumRegs != 1) {
Chris Lattnerc35847e2009-03-24 15:27:37 +00006219 TargetRegisterClass::iterator I = RC->begin();
6220 for (; *I != AssignedReg; ++I)
6221 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006222
Dan Gohman575fad32008-09-03 16:12:24 +00006223 // Already added the first reg.
6224 --NumRegs; ++I;
6225 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnerc35847e2009-03-24 15:27:37 +00006226 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohman575fad32008-09-03 16:12:24 +00006227 Regs.push_back(*I);
6228 }
6229 }
Bill Wendlingac087582009-12-22 01:25:10 +00006230
Dan Gohmand16aa542010-05-29 17:03:36 +00006231 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Dan Gohman575fad32008-09-03 16:12:24 +00006232 return;
6233 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006234
Dan Gohman575fad32008-09-03 16:12:24 +00006235 // Otherwise, if this was a reference to an LLVM register class, create vregs
6236 // for this reference.
Chris Lattner42eceb32009-03-24 15:25:07 +00006237 if (const TargetRegisterClass *RC = PhysReg.second) {
6238 RegVT = *RC->vt_begin();
Owen Anderson9f944592009-08-11 20:47:22 +00006239 if (OpInfo.ConstraintVT == MVT::Other)
Evan Cheng968c3b02009-03-23 08:01:15 +00006240 ValueVT = RegVT;
Dan Gohman575fad32008-09-03 16:12:24 +00006241
Evan Cheng968c3b02009-03-23 08:01:15 +00006242 // Create the appropriate number of virtual registers.
6243 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6244 for (; NumRegs; --NumRegs)
Chris Lattner42eceb32009-03-24 15:25:07 +00006245 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006246
Dan Gohmand16aa542010-05-29 17:03:36 +00006247 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Evan Cheng968c3b02009-03-23 08:01:15 +00006248 return;
Dan Gohman575fad32008-09-03 16:12:24 +00006249 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00006250
Dan Gohman575fad32008-09-03 16:12:24 +00006251 // Otherwise, we couldn't allocate enough registers for this.
6252}
6253
Dan Gohman575fad32008-09-03 16:12:24 +00006254/// visitInlineAsm - Handle a call to an InlineAsm object.
6255///
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006256void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6257 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Dan Gohman575fad32008-09-03 16:12:24 +00006258
6259 /// ConstraintOperands - Information about all of the constraints.
John Thompsone8360b72010-10-29 17:29:13 +00006260 SDISelAsmOperandInfoVector ConstraintOperands;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006261
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006262 const TargetLowering *TLI = TM.getTargetLowering();
Evan Chengd26fc5e2011-05-06 20:52:23 +00006263 TargetLowering::AsmOperandInfoVector
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006264 TargetConstraints = TLI->ParseConstraints(CS);
Evan Chengd26fc5e2011-05-06 20:52:23 +00006265
John Thompson1094c802010-09-13 18:15:37 +00006266 bool hasMemory = false;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006267
Dan Gohman575fad32008-09-03 16:12:24 +00006268 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6269 unsigned ResNo = 0; // ResNo - The result number of the next output.
John Thompson1094c802010-09-13 18:15:37 +00006270 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6271 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
Dan Gohman575fad32008-09-03 16:12:24 +00006272 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006273
Patrik Hagglundf9934612012-12-19 15:19:11 +00006274 MVT OpVT = MVT::Other;
Dan Gohman575fad32008-09-03 16:12:24 +00006275
6276 // Compute the value type for each operand.
6277 switch (OpInfo.Type) {
6278 case InlineAsm::isOutput:
6279 // Indirect outputs just consume an argument.
6280 if (OpInfo.isIndirect) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006281 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohman575fad32008-09-03 16:12:24 +00006282 break;
6283 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006284
Dan Gohman575fad32008-09-03 16:12:24 +00006285 // The return value of the call is this value. As such, there is no
6286 // corresponding argument.
Nick Lewyckyf40df1d2011-09-30 22:19:53 +00006287 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Chris Lattner229907c2011-07-18 04:54:35 +00006288 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006289 OpVT = TLI->getSimpleValueType(STy->getElementType(ResNo));
Dan Gohman575fad32008-09-03 16:12:24 +00006290 } else {
6291 assert(ResNo == 0 && "Asm only has one result!");
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006292 OpVT = TLI->getSimpleValueType(CS.getType());
Dan Gohman575fad32008-09-03 16:12:24 +00006293 }
6294 ++ResNo;
6295 break;
6296 case InlineAsm::isInput:
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006297 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohman575fad32008-09-03 16:12:24 +00006298 break;
6299 case InlineAsm::isClobber:
6300 // Nothing to do.
6301 break;
6302 }
6303
6304 // If this is an input or an indirect output, process the call argument.
6305 // BasicBlocks are labels, currently appearing only in asm's.
6306 if (OpInfo.CallOperandVal) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006307 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohman575fad32008-09-03 16:12:24 +00006308 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006309 } else {
Dan Gohman575fad32008-09-03 16:12:24 +00006310 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohman575fad32008-09-03 16:12:24 +00006311 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006312
Rafael Espindola5f57f462014-02-21 18:34:28 +00006313 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), *TLI, DL).
Patrik Hagglundf9934612012-12-19 15:19:11 +00006314 getSimpleVT();
Dan Gohman575fad32008-09-03 16:12:24 +00006315 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006316
Dan Gohman575fad32008-09-03 16:12:24 +00006317 OpInfo.ConstraintVT = OpVT;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006318
John Thompson1094c802010-09-13 18:15:37 +00006319 // Indirect operand accesses access memory.
6320 if (OpInfo.isIndirect)
6321 hasMemory = true;
6322 else {
6323 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
Evan Chengd26fc5e2011-05-06 20:52:23 +00006324 TargetLowering::ConstraintType
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006325 CType = TLI->getConstraintType(OpInfo.Codes[j]);
John Thompson1094c802010-09-13 18:15:37 +00006326 if (CType == TargetLowering::C_Memory) {
6327 hasMemory = true;
6328 break;
6329 }
6330 }
6331 }
Chris Lattner160e8ab2008-10-18 18:49:30 +00006332 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006333
John Thompson1094c802010-09-13 18:15:37 +00006334 SDValue Chain, Flag;
6335
6336 // We won't need to flush pending loads if this asm doesn't touch
6337 // memory and is nonvolatile.
6338 if (hasMemory || IA->hasSideEffects())
6339 Chain = getRoot();
6340 else
6341 Chain = DAG.getRoot();
6342
Chris Lattner160e8ab2008-10-18 18:49:30 +00006343 // Second pass over the constraints: compute which constraint option to use
6344 // and assign registers to constraints that want a specific physreg.
John Thompson1094c802010-09-13 18:15:37 +00006345 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Chris Lattner160e8ab2008-10-18 18:49:30 +00006346 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006347
John Thompson8118ef82010-09-24 22:24:05 +00006348 // If this is an output operand with a matching input operand, look up the
6349 // matching input. If their types mismatch, e.g. one is an integer, the
6350 // other is floating point, or their sizes are different, flag it as an
6351 // error.
6352 if (OpInfo.hasMatchingInput()) {
6353 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006354
John Thompson8118ef82010-09-24 22:24:05 +00006355 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Bill Wendlingd1634052012-07-19 00:04:14 +00006356 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006357 TLI->getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6358 OpInfo.ConstraintVT);
Bill Wendlingd1634052012-07-19 00:04:14 +00006359 std::pair<unsigned, const TargetRegisterClass*> InputRC =
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006360 TLI->getRegForInlineAsmConstraint(Input.ConstraintCode,
6361 Input.ConstraintVT);
John Thompson8118ef82010-09-24 22:24:05 +00006362 if ((OpInfo.ConstraintVT.isInteger() !=
6363 Input.ConstraintVT.isInteger()) ||
Eric Christopher92464be2011-07-14 20:13:52 +00006364 (MatchRC.second != InputRC.second)) {
John Thompson8118ef82010-09-24 22:24:05 +00006365 report_fatal_error("Unsupported asm: input constraint"
6366 " with a matching output constraint of"
6367 " incompatible type!");
6368 }
6369 Input.ConstraintVT = OpInfo.ConstraintVT;
6370 }
6371 }
6372
Dan Gohman575fad32008-09-03 16:12:24 +00006373 // Compute the constraint code and ConstraintType to use.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006374 TLI->ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Dan Gohman575fad32008-09-03 16:12:24 +00006375
Eric Christopher0cb6fd92013-01-11 18:12:39 +00006376 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6377 OpInfo.Type == InlineAsm::isClobber)
6378 continue;
6379
Dan Gohman575fad32008-09-03 16:12:24 +00006380 // If this is a memory input, and if the operand is not indirect, do what we
6381 // need to to provide an address for the memory input.
6382 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6383 !OpInfo.isIndirect) {
Evan Chengd26fc5e2011-05-06 20:52:23 +00006384 assert((OpInfo.isMultipleAlternative ||
6385 (OpInfo.Type == InlineAsm::isInput)) &&
Dan Gohman575fad32008-09-03 16:12:24 +00006386 "Can only indirectify direct input operands!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006387
Dan Gohman575fad32008-09-03 16:12:24 +00006388 // Memory operands really want the address of the value. If we don't have
6389 // an indirect input, put it in the constpool if we can, otherwise spill
6390 // it to a stack slot.
Eric Christopherfbff0e42011-06-03 17:21:23 +00006391 // TODO: This isn't quite right. We need to handle these according to
6392 // the addressing mode that the constraint wants. Also, this may take
6393 // an additional register for the computation and we don't want that
6394 // either.
Eric Christopher0713a9d2011-06-08 23:55:35 +00006395
Dan Gohman575fad32008-09-03 16:12:24 +00006396 // If the operand is a float, integer, or vector constant, spill to a
6397 // constant pool entry to get its address.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006398 const Value *OpVal = OpInfo.CallOperandVal;
Dan Gohman575fad32008-09-03 16:12:24 +00006399 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
Chris Lattner0256be92012-01-27 03:08:05 +00006400 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
Dan Gohman575fad32008-09-03 16:12:24 +00006401 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006402 TLI->getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00006403 } else {
6404 // Otherwise, create a stack slot and emit a store to it before the
6405 // asm.
Chris Lattner229907c2011-07-18 04:54:35 +00006406 Type *Ty = OpVal->getType();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006407 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
6408 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(Ty);
Dan Gohman575fad32008-09-03 16:12:24 +00006409 MachineFunction &MF = DAG.getMachineFunction();
David Greene1fbe0542009-11-12 20:49:22 +00006410 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006411 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI->getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006412 Chain = DAG.getStore(Chain, getCurSDLoc(),
Chris Lattner1ffcf522010-09-21 16:36:31 +00006413 OpInfo.CallOperand, StackSlot,
6414 MachinePointerInfo::getFixedStack(SSFI),
David Greene39c6d012010-02-15 17:00:31 +00006415 false, false, 0);
Dan Gohman575fad32008-09-03 16:12:24 +00006416 OpInfo.CallOperand = StackSlot;
6417 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006418
Dan Gohman575fad32008-09-03 16:12:24 +00006419 // There is no longer a Value* corresponding to this operand.
6420 OpInfo.CallOperandVal = 0;
Bill Wendlingac087582009-12-22 01:25:10 +00006421
Dan Gohman575fad32008-09-03 16:12:24 +00006422 // It is now an indirect operand.
6423 OpInfo.isIndirect = true;
6424 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006425
Dan Gohman575fad32008-09-03 16:12:24 +00006426 // If this constraint is for a specific register, allocate it before
6427 // anything else.
6428 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006429 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
Dan Gohman575fad32008-09-03 16:12:24 +00006430 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006431
Dan Gohman575fad32008-09-03 16:12:24 +00006432 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattneref890172008-10-17 16:21:11 +00006433 // to register class operands.
Dan Gohman575fad32008-09-03 16:12:24 +00006434 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6435 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006436
Dan Gohman575fad32008-09-03 16:12:24 +00006437 // C_Register operands have already been allocated, Other/Memory don't need
6438 // to be.
6439 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006440 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006441 }
6442
Dan Gohman575fad32008-09-03 16:12:24 +00006443 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6444 std::vector<SDValue> AsmNodeOperands;
6445 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6446 AsmNodeOperands.push_back(
Dan Gohmanfeeced42010-01-04 21:00:54 +00006447 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006448 TLI->getPointerTy()));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006449
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006450 // If we have a !srcloc metadata node associated with it, we want to attach
6451 // this to the ultimately generated inline asm machineinstr. To do this, we
6452 // pass in the third operand as this (potentially null) inline asm MDNode.
6453 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6454 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006455
Chad Rosier9e1274f2012-10-30 19:11:54 +00006456 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6457 // bits as operand 3.
Evan Cheng6eb516d2011-01-07 23:50:32 +00006458 unsigned ExtraInfo = 0;
6459 if (IA->hasSideEffects())
6460 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6461 if (IA->isAlignStack())
6462 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
Chad Rosiercbd2a192012-09-05 22:17:43 +00006463 // Set the asm dialect.
Chad Rosiere53314f2012-09-05 22:40:13 +00006464 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
Chad Rosier9e1274f2012-10-30 19:11:54 +00006465
6466 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6467 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6468 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6469
6470 // Compute the constraint code and ConstraintType to use.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006471 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chad Rosier9e1274f2012-10-30 19:11:54 +00006472
Chad Rosier86f60502012-10-30 20:01:12 +00006473 // Ideally, we would only check against memory constraints. However, the
6474 // meaning of an other constraint can be target-specific and we can't easily
6475 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6476 // for other constriants as well.
Chad Rosier9e1274f2012-10-30 19:11:54 +00006477 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6478 OpInfo.ConstraintType == TargetLowering::C_Other) {
6479 if (OpInfo.Type == InlineAsm::isInput)
6480 ExtraInfo |= InlineAsm::Extra_MayLoad;
6481 else if (OpInfo.Type == InlineAsm::isOutput)
6482 ExtraInfo |= InlineAsm::Extra_MayStore;
Eric Christopher0cb6fd92013-01-11 18:12:39 +00006483 else if (OpInfo.Type == InlineAsm::isClobber)
6484 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
Chad Rosier9e1274f2012-10-30 19:11:54 +00006485 }
6486 }
6487
Evan Cheng6eb516d2011-01-07 23:50:32 +00006488 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006489 TLI->getPointerTy()));
Dale Johannesen4d887f7c2010-07-02 20:16:09 +00006490
Dan Gohman575fad32008-09-03 16:12:24 +00006491 // Loop over all of the inputs, copying the operand values into the
6492 // appropriate registers and processing the output regs.
6493 RegsForValue RetValRegs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006494
Dan Gohman575fad32008-09-03 16:12:24 +00006495 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6496 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006497
Dan Gohman575fad32008-09-03 16:12:24 +00006498 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6499 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6500
6501 switch (OpInfo.Type) {
6502 case InlineAsm::isOutput: {
6503 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6504 OpInfo.ConstraintType != TargetLowering::C_Register) {
6505 // Memory output, or 'other' output (e.g. 'X' constraint).
6506 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6507
6508 // Add information to the INLINEASM node to know about this output.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006509 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6510 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006511 TLI->getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006512 AsmNodeOperands.push_back(OpInfo.CallOperand);
6513 break;
6514 }
6515
6516 // Otherwise, this is a register or register class output.
6517
6518 // Copy the output from the appropriate register. Find a register that
6519 // we can use.
Chris Lattner6b77a072012-01-03 23:51:01 +00006520 if (OpInfo.AssignedRegs.Regs.empty()) {
6521 LLVMContext &Ctx = *DAG.getContext();
Stephen Lincfe7f352013-07-08 00:37:03 +00006522 Ctx.emitError(CS.getInstruction(),
Chris Lattner6b77a072012-01-03 23:51:01 +00006523 "couldn't allocate output register for constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006524 Twine(OpInfo.ConstraintCode) + "'");
6525 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006526 }
Dan Gohman575fad32008-09-03 16:12:24 +00006527
6528 // If this is an indirect operand, store through the pointer after the
6529 // asm.
6530 if (OpInfo.isIndirect) {
6531 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6532 OpInfo.CallOperandVal));
6533 } else {
6534 // This is the result value of the call.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00006535 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohman575fad32008-09-03 16:12:24 +00006536 // Concatenate this output onto the outputs list.
6537 RetValRegs.append(OpInfo.AssignedRegs);
6538 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006539
Dan Gohman575fad32008-09-03 16:12:24 +00006540 // Add information to the INLINEASM node to know that this register is
6541 // set.
Eric Christopher029af152013-07-30 22:50:44 +00006542 OpInfo.AssignedRegs
6543 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6544 ? InlineAsm::Kind_RegDefEarlyClobber
6545 : InlineAsm::Kind_RegDef,
6546 false, 0, DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006547 break;
6548 }
6549 case InlineAsm::isInput: {
6550 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006551
Chris Lattner860df6e2008-10-17 16:47:46 +00006552 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohman575fad32008-09-03 16:12:24 +00006553 // If this is required to match an output register we have already set,
6554 // just use its register.
Chris Lattneref890172008-10-17 16:21:11 +00006555 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006556
Dan Gohman575fad32008-09-03 16:12:24 +00006557 // Scan until we find the definition we already emitted of this operand.
6558 // When we find it, create a RegsForValue operand.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006559 unsigned CurOp = InlineAsm::Op_FirstOperand;
Dan Gohman575fad32008-09-03 16:12:24 +00006560 for (; OperandNo; --OperandNo) {
6561 // Advance to the next operand.
Evan Cheng2e559232009-03-20 18:03:34 +00006562 unsigned OpFlag =
Dan Gohmaneffb8942008-09-12 16:56:44 +00006563 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006564 assert((InlineAsm::isRegDefKind(OpFlag) ||
6565 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6566 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
Evan Cheng2e559232009-03-20 18:03:34 +00006567 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohman575fad32008-09-03 16:12:24 +00006568 }
6569
Evan Cheng2e559232009-03-20 18:03:34 +00006570 unsigned OpFlag =
Dan Gohmaneffb8942008-09-12 16:56:44 +00006571 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006572 if (InlineAsm::isRegDefKind(OpFlag) ||
6573 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
Evan Cheng2e559232009-03-20 18:03:34 +00006574 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Chris Lattner3c65a832010-04-08 00:09:16 +00006575 if (OpInfo.isIndirect) {
6576 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
Dan Gohman7c0303a2010-04-19 22:41:47 +00006577 LLVMContext &Ctx = *DAG.getContext();
Eric Christophere6656ac2013-07-31 01:26:24 +00006578 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6579 " don't know how to handle tied "
6580 "indirect register inputs");
6581 return;
Chris Lattner3c65a832010-04-08 00:09:16 +00006582 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006583
Dan Gohman575fad32008-09-03 16:12:24 +00006584 RegsForValue MatchedRegs;
Dan Gohman575fad32008-09-03 16:12:24 +00006585 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00006586 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
Evan Cheng968c3b02009-03-23 08:01:15 +00006587 MatchedRegs.RegVTs.push_back(RegVT);
6588 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng2e559232009-03-20 18:03:34 +00006589 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Chad Rosier108d5a62013-04-24 22:53:10 +00006590 i != e; ++i) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006591 if (const TargetRegisterClass *RC = TLI->getRegClassFor(RegVT))
Chad Rosier108d5a62013-04-24 22:53:10 +00006592 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6593 else {
6594 LLVMContext &Ctx = *DAG.getContext();
Eric Christophere6656ac2013-07-31 01:26:24 +00006595 Ctx.emitError(CS.getInstruction(),
6596 "inline asm error: This value"
Chad Rosier108d5a62013-04-24 22:53:10 +00006597 " type register class is not natively supported!");
Eric Christophere6656ac2013-07-31 01:26:24 +00006598 return;
Chad Rosier108d5a62013-04-24 22:53:10 +00006599 }
6600 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006601 // Use the produced MatchedRegs object to
Andrew Trickef9de2a2013-05-25 02:42:55 +00006602 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
Bill Wendling5def8912012-09-26 06:16:18 +00006603 Chain, &Flag, CS.getInstruction());
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006604 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
Evan Cheng968c3b02009-03-23 08:01:15 +00006605 true, OpInfo.getMatchedOperand(),
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006606 DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006607 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006608 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006609
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006610 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6611 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6612 "Unexpected number of operands");
6613 // Add information to the INLINEASM node to know about this input.
6614 // See InlineAsm.h isUseOperandTiedToDef.
6615 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6616 OpInfo.getMatchedOperand());
6617 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006618 TLI->getPointerTy()));
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006619 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6620 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006621 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006622
Dale Johannesencaca5482010-07-13 20:17:05 +00006623 // Treat indirect 'X' constraint as memory.
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006624 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6625 OpInfo.isIndirect)
Dale Johannesencaca5482010-07-13 20:17:05 +00006626 OpInfo.ConstraintType = TargetLowering::C_Memory;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006627
Dale Johannesencaca5482010-07-13 20:17:05 +00006628 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Dan Gohman575fad32008-09-03 16:12:24 +00006629 std::vector<SDValue> Ops;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006630 TLI->LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6631 Ops, DAG);
Chris Lattner6b77a072012-01-03 23:51:01 +00006632 if (Ops.empty()) {
6633 LLVMContext &Ctx = *DAG.getContext();
6634 Ctx.emitError(CS.getInstruction(),
6635 "invalid operand for inline asm constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006636 Twine(OpInfo.ConstraintCode) + "'");
6637 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006638 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006639
Dan Gohman575fad32008-09-03 16:12:24 +00006640 // Add information to the INLINEASM node to know about this input.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006641 unsigned ResOpType =
6642 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006643 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006644 TLI->getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006645 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6646 break;
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006647 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006648
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006649 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Dan Gohman575fad32008-09-03 16:12:24 +00006650 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006651 assert(InOperandVal.getValueType() == TLI->getPointerTy() &&
Dan Gohman575fad32008-09-03 16:12:24 +00006652 "Memory operands expect pointer values");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006653
Dan Gohman575fad32008-09-03 16:12:24 +00006654 // Add information to the INLINEASM node to know about this input.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006655 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
Dale Johannesenc36660d2008-09-24 01:07:17 +00006656 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006657 TLI->getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006658 AsmNodeOperands.push_back(InOperandVal);
6659 break;
6660 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006661
Dan Gohman575fad32008-09-03 16:12:24 +00006662 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6663 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6664 "Unknown constraint type!");
Eric Christopherdd8638f2012-07-02 21:16:43 +00006665
6666 // TODO: Support this.
6667 if (OpInfo.isIndirect) {
6668 LLVMContext &Ctx = *DAG.getContext();
6669 Ctx.emitError(CS.getInstruction(),
6670 "Don't know how to handle indirect register inputs yet "
Eric Christophere6656ac2013-07-31 01:26:24 +00006671 "for constraint '" +
6672 Twine(OpInfo.ConstraintCode) + "'");
6673 return;
Eric Christopherdd8638f2012-07-02 21:16:43 +00006674 }
Dan Gohman575fad32008-09-03 16:12:24 +00006675
6676 // Copy the input into the appropriate registers.
Chris Lattner6b77a072012-01-03 23:51:01 +00006677 if (OpInfo.AssignedRegs.Regs.empty()) {
6678 LLVMContext &Ctx = *DAG.getContext();
Stephen Lincfe7f352013-07-08 00:37:03 +00006679 Ctx.emitError(CS.getInstruction(),
Chris Lattner6b77a072012-01-03 23:51:01 +00006680 "couldn't allocate input reg for constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006681 Twine(OpInfo.ConstraintCode) + "'");
6682 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006683 }
Dan Gohman575fad32008-09-03 16:12:24 +00006684
Andrew Trickef9de2a2013-05-25 02:42:55 +00006685 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
Bill Wendling5def8912012-09-26 06:16:18 +00006686 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006687
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006688 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006689 DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006690 break;
6691 }
6692 case InlineAsm::isClobber: {
6693 // Add the clobbered value to the operand list, so that the register
6694 // allocator is aware that the physreg got clobbered.
6695 if (!OpInfo.AssignedRegs.Regs.empty())
Jakob Stoklund Olesen537a3022011-06-27 04:08:33 +00006696 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006697 false, 0, DAG,
Bill Wendlingac087582009-12-22 01:25:10 +00006698 AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006699 break;
6700 }
6701 }
6702 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006703
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006704 // Finish up input operands. Set the input chain and add the flag last.
Dale Johannesen4d887f7c2010-07-02 20:16:09 +00006705 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
Dan Gohman575fad32008-09-03 16:12:24 +00006706 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006707
Andrew Trickef9de2a2013-05-25 02:42:55 +00006708 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
Chris Lattner3e5fbd72010-12-21 02:38:05 +00006709 DAG.getVTList(MVT::Other, MVT::Glue),
Dan Gohman575fad32008-09-03 16:12:24 +00006710 &AsmNodeOperands[0], AsmNodeOperands.size());
6711 Flag = Chain.getValue(1);
6712
6713 // If this asm returns a register value, copy the result from that register
6714 // and set it as the value of the call.
6715 if (!RetValRegs.Regs.empty()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006716 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
Bill Wendling81406f62012-09-26 04:04:19 +00006717 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006718
Chris Lattner160e8ab2008-10-18 18:49:30 +00006719 // FIXME: Why don't we do this for inline asms with MRVs?
6720 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006721 EVT ResultType = TLI->getValueType(CS.getType());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006722
Chris Lattner160e8ab2008-10-18 18:49:30 +00006723 // If any of the results of the inline asm is a vector, it may have the
6724 // wrong width/num elts. This can happen for register classes that can
6725 // contain multiple different value types. The preg or vreg allocated may
6726 // not have the same VT as was expected. Convert it to the right type
6727 // with bit_convert.
6728 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006729 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00006730 ResultType, Val);
Dan Gohman6de25562008-10-18 01:03:45 +00006731
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006732 } else if (ResultType != Val.getValueType() &&
Chris Lattner160e8ab2008-10-18 18:49:30 +00006733 ResultType.isInteger() && Val.getValueType().isInteger()) {
6734 // If a result value was tied to an input value, the computed result may
6735 // have a wider width than the expected result. Extract the relevant
6736 // portion.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006737 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
Dan Gohman6de25562008-10-18 01:03:45 +00006738 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006739
Chris Lattner160e8ab2008-10-18 18:49:30 +00006740 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner052092b2008-10-17 17:52:49 +00006741 }
Dan Gohman6de25562008-10-18 01:03:45 +00006742
Dan Gohman575fad32008-09-03 16:12:24 +00006743 setValue(CS.getInstruction(), Val);
Dale Johannesen83593f42009-04-14 00:56:56 +00006744 // Don't need to use this as a chain in this case.
6745 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6746 return;
Dan Gohman575fad32008-09-03 16:12:24 +00006747 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006748
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006749 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006750
Dan Gohman575fad32008-09-03 16:12:24 +00006751 // Process indirect outputs, first output all of the flagged copies out of
6752 // physregs.
6753 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6754 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006755 const Value *Ptr = IndirectStoresToEmit[i].second;
Andrew Trickef9de2a2013-05-25 02:42:55 +00006756 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
Bill Wendling81406f62012-09-26 04:04:19 +00006757 Chain, &Flag, IA);
Dan Gohman575fad32008-09-03 16:12:24 +00006758 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6759 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006760
Dan Gohman575fad32008-09-03 16:12:24 +00006761 // Emit the non-flagged stores from the physregs.
6762 SmallVector<SDValue, 8> OutChains;
Bill Wendlingac087582009-12-22 01:25:10 +00006763 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006764 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
Bill Wendlingac087582009-12-22 01:25:10 +00006765 StoresToEmit[i].first,
6766 getValue(StoresToEmit[i].second),
Chris Lattnera4f19972010-09-21 18:58:22 +00006767 MachinePointerInfo(StoresToEmit[i].second),
David Greene39c6d012010-02-15 17:00:31 +00006768 false, false, 0);
Bill Wendlingac087582009-12-22 01:25:10 +00006769 OutChains.push_back(Val);
Bill Wendlingac087582009-12-22 01:25:10 +00006770 }
6771
Dan Gohman575fad32008-09-03 16:12:24 +00006772 if (!OutChains.empty())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006773 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Dan Gohman575fad32008-09-03 16:12:24 +00006774 &OutChains[0], OutChains.size());
Bill Wendlingac087582009-12-22 01:25:10 +00006775
Dan Gohman575fad32008-09-03 16:12:24 +00006776 DAG.setRoot(Chain);
6777}
6778
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006779void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006780 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006781 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006782 getValue(I.getArgOperand(0)),
6783 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00006784}
6785
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006786void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006787 const TargetLowering *TLI = TM.getTargetLowering();
Rafael Espindola5f57f462014-02-21 18:34:28 +00006788 const DataLayout &DL = *TLI->getDataLayout();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006789 SDValue V = DAG.getVAArg(TLI->getValueType(I.getType()), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00006790 getRoot(), getValue(I.getOperand(0)),
Rafael Espindolaa76eccf2010-07-11 04:01:49 +00006791 DAG.getSrcValue(I.getOperand(0)),
Rafael Espindola5f57f462014-02-21 18:34:28 +00006792 DL.getABITypeAlignment(I.getType()));
Dan Gohman575fad32008-09-03 16:12:24 +00006793 setValue(&I, V);
6794 DAG.setRoot(V.getValue(1));
6795}
6796
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006797void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006798 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006799 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006800 getValue(I.getArgOperand(0)),
6801 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00006802}
6803
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006804void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006805 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006806 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006807 getValue(I.getArgOperand(0)),
6808 getValue(I.getArgOperand(1)),
6809 DAG.getSrcValue(I.getArgOperand(0)),
6810 DAG.getSrcValue(I.getArgOperand(1))));
Dan Gohman575fad32008-09-03 16:12:24 +00006811}
6812
Andrew Trick74f4c742013-10-31 17:18:24 +00006813/// \brief Lower an argument list according to the target calling convention.
6814///
6815/// \return A tuple of <return-value, token-chain>
6816///
6817/// This is a helper for lowering intrinsics that follow a target calling
6818/// convention or require stack pointer adjustment. Only a subset of the
6819/// intrinsic's operands need to participate in the calling convention.
6820std::pair<SDValue, SDValue>
6821SelectionDAGBuilder::LowerCallOperands(const CallInst &CI, unsigned ArgIdx,
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006822 unsigned NumArgs, SDValue Callee,
6823 bool useVoidTy) {
Andrew Trick74f4c742013-10-31 17:18:24 +00006824 TargetLowering::ArgListTy Args;
6825 Args.reserve(NumArgs);
6826
6827 // Populate the argument list.
6828 // Attributes for args start at offset 1, after the return attribute.
6829 ImmutableCallSite CS(&CI);
6830 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6831 ArgI != ArgE; ++ArgI) {
6832 const Value *V = CI.getOperand(ArgI);
6833
6834 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6835
6836 TargetLowering::ArgListEntry Entry;
6837 Entry.Node = getValue(V);
6838 Entry.Ty = V->getType();
6839 Entry.setAttributes(&CS, AttrI);
6840 Args.push_back(Entry);
6841 }
6842
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006843 Type *retTy = useVoidTy ? Type::getVoidTy(*DAG.getContext()) : CI.getType();
6844 TargetLowering::CallLoweringInfo CLI(getRoot(), retTy, /*retSExt*/ false,
6845 /*retZExt*/ false, /*isVarArg*/ false, /*isInReg*/ false, NumArgs,
6846 CI.getCallingConv(), /*isTailCall*/ false, /*doesNotReturn*/ false,
Andrew Trick74f4c742013-10-31 17:18:24 +00006847 /*isReturnValueUsed*/ CI.use_empty(), Callee, Args, DAG, getCurSDLoc());
6848
6849 const TargetLowering *TLI = TM.getTargetLowering();
6850 return TLI->LowerCallTo(CLI);
6851}
6852
Andrew Trick4a1abb72013-11-22 19:07:36 +00006853/// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6854/// or patchpoint target node's operand list.
Andrew Trick391dbad2013-11-26 02:03:25 +00006855///
6856/// Constants are converted to TargetConstants purely as an optimization to
6857/// avoid constant materialization and register allocation.
6858///
6859/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6860/// generate addess computation nodes, and so ExpandISelPseudo can convert the
6861/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6862/// address materialization and register allocation, but may also be required
6863/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6864/// alloca in the entry block, then the runtime may assume that the alloca's
6865/// StackMap location can be read immediately after compilation and that the
6866/// location is valid at any point during execution (this is similar to the
6867/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6868/// only available in a register, then the runtime would need to trap when
6869/// execution reaches the StackMap in order to read the alloca's location.
Andrew Trick4a1abb72013-11-22 19:07:36 +00006870static void addStackMapLiveVars(const CallInst &CI, unsigned StartIdx,
6871 SmallVectorImpl<SDValue> &Ops,
6872 SelectionDAGBuilder &Builder) {
6873 for (unsigned i = StartIdx, e = CI.getNumArgOperands(); i != e; ++i) {
6874 SDValue OpVal = Builder.getValue(CI.getArgOperand(i));
6875 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6876 Ops.push_back(
6877 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
6878 Ops.push_back(
6879 Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
Andrew Trick391dbad2013-11-26 02:03:25 +00006880 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6881 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6882 Ops.push_back(
6883 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
Andrew Trick4a1abb72013-11-22 19:07:36 +00006884 } else
6885 Ops.push_back(OpVal);
6886 }
6887}
6888
Andrew Trick74f4c742013-10-31 17:18:24 +00006889/// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6890void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6891 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6892 // [live variables...])
6893
6894 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6895
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006896 SDValue Chain, InFlag, Callee, NullPtr;
6897 SmallVector<SDValue, 32> Ops;
Andrew Trick74f4c742013-10-31 17:18:24 +00006898
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006899 SDLoc DL = getCurSDLoc();
6900 Callee = getValue(CI.getCalledValue());
6901 NullPtr = DAG.getIntPtrConstant(0, true);
Andrew Trick74f4c742013-10-31 17:18:24 +00006902
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006903 // The stackmap intrinsic only records the live variables (the arguemnts
6904 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
6905 // intrinsic, this won't be lowered to a function call. This means we don't
6906 // have to worry about calling conventions and target specific lowering code.
6907 // Instead we perform the call lowering right here.
6908 //
6909 // chain, flag = CALLSEQ_START(chain, 0)
6910 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
6911 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
6912 //
6913 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
6914 InFlag = Chain.getValue(1);
Andrew Trick74f4c742013-10-31 17:18:24 +00006915
Juergen Ributzkaaa30da32014-02-12 22:17:10 +00006916 // Add the <id> and <numBytes> constants.
6917 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
6918 Ops.push_back(DAG.getTargetConstant(
6919 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
6920 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
6921 Ops.push_back(DAG.getTargetConstant(
6922 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006923
Andrew Trick74f4c742013-10-31 17:18:24 +00006924 // Push live variables for the stack map.
Andrew Trick4a1abb72013-11-22 19:07:36 +00006925 addStackMapLiveVars(CI, 2, Ops, *this);
Andrew Trick74f4c742013-10-31 17:18:24 +00006926
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006927 // We are not pushing any register mask info here on the operands list,
6928 // because the stackmap doesn't clobber anything.
Andrew Trick74f4c742013-10-31 17:18:24 +00006929
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006930 // Push the chain and the glue flag.
6931 Ops.push_back(Chain);
6932 Ops.push_back(InFlag);
Andrew Trick74f4c742013-10-31 17:18:24 +00006933
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006934 // Create the STACKMAP node.
Andrew Trick74f4c742013-10-31 17:18:24 +00006935 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006936 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
6937 Chain = SDValue(SM, 0);
6938 InFlag = Chain.getValue(1);
Andrew Trick6664df12013-11-05 22:44:04 +00006939
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006940 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
Andrew Trick6664df12013-11-05 22:44:04 +00006941
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006942 // Stackmaps don't generate values, so nothing goes into the NodeMap.
Andrew Trick6664df12013-11-05 22:44:04 +00006943
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006944 // Set the root to the target-lowered call chain.
6945 DAG.setRoot(Chain);
Juergen Ributzkae8294752013-12-14 06:53:06 +00006946
6947 // Inform the Frame Information that we have a stackmap in this function.
6948 FuncInfo.MF->getFrameInfo()->setHasStackMap();
Andrew Trick74f4c742013-10-31 17:18:24 +00006949}
6950
6951/// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
6952void SelectionDAGBuilder::visitPatchpoint(const CallInst &CI) {
Andrew Tricke8cba372013-12-13 18:37:10 +00006953 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
Andrew Trick561f2212013-11-14 06:54:10 +00006954 // i32 <numBytes>,
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006955 // i8* <target>,
6956 // i32 <numArgs>,
6957 // [Args...],
6958 // [live variables...])
Andrew Trick74f4c742013-10-31 17:18:24 +00006959
Juergen Ributzka87ed9062013-11-09 01:51:33 +00006960 CallingConv::ID CC = CI.getCallingConv();
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006961 bool isAnyRegCC = CC == CallingConv::AnyReg;
6962 bool hasDef = !CI.getType()->isVoidTy();
Andrew Trick74f4c742013-10-31 17:18:24 +00006963 SDValue Callee = getValue(CI.getOperand(2)); // <target>
6964
6965 // Get the real number of arguments participating in the call <numArgs>
Andrew Tricka2428e02013-11-22 19:07:33 +00006966 SDValue NArgVal = getValue(CI.getArgOperand(PatchPointOpers::NArgPos));
6967 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
Andrew Trick74f4c742013-10-31 17:18:24 +00006968
6969 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
Andrew Tricka2428e02013-11-22 19:07:33 +00006970 // Intrinsics include all meta-operands up to but not including CC.
6971 unsigned NumMetaOpers = PatchPointOpers::CCPos;
6972 assert(CI.getNumArgOperands() >= NumMetaOpers + NumArgs &&
Andrew Trick74f4c742013-10-31 17:18:24 +00006973 "Not enough arguments provided to the patchpoint intrinsic");
6974
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006975 // For AnyRegCC the arguments are lowered later on manually.
6976 unsigned NumCallArgs = isAnyRegCC ? 0 : NumArgs;
Andrew Trick74f4c742013-10-31 17:18:24 +00006977 std::pair<SDValue, SDValue> Result =
Andrew Tricka2428e02013-11-22 19:07:33 +00006978 LowerCallOperands(CI, NumMetaOpers, NumCallArgs, Callee, isAnyRegCC);
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006979
Andrew Trick74f4c742013-10-31 17:18:24 +00006980 // Set the root to the target-lowered call chain.
6981 SDValue Chain = Result.second;
6982 DAG.setRoot(Chain);
6983
6984 SDNode *CallEnd = Chain.getNode();
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006985 if (hasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
6986 CallEnd = CallEnd->getOperand(0).getNode();
6987
Andrew Trick74f4c742013-10-31 17:18:24 +00006988 /// Get a call instruction from the call sequence chain.
6989 /// Tail calls are not allowed.
6990 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6991 "Expected a callseq node.");
6992 SDNode *Call = CallEnd->getOperand(0).getNode();
6993 bool hasGlue = Call->getGluedNode();
6994
6995 // Replace the target specific call node with the patchable intrinsic.
6996 SmallVector<SDValue, 8> Ops;
6997
Andrew Tricka2428e02013-11-22 19:07:33 +00006998 // Add the <id> and <numBytes> constants.
6999 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7000 Ops.push_back(DAG.getTargetConstant(
Andrew Tricke8cba372013-12-13 18:37:10 +00007001 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
Andrew Tricka2428e02013-11-22 19:07:33 +00007002 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7003 Ops.push_back(DAG.getTargetConstant(
7004 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
7005
Andrew Trick74f4c742013-10-31 17:18:24 +00007006 // Assume that the Callee is a constant address.
Andrew Tricka2428e02013-11-22 19:07:33 +00007007 // FIXME: handle function symbols in the future.
Andrew Trick74f4c742013-10-31 17:18:24 +00007008 Ops.push_back(
Juergen Ributzka87ed9062013-11-09 01:51:33 +00007009 DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
7010 /*isTarget=*/true));
Andrew Trick74f4c742013-10-31 17:18:24 +00007011
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007012 // Adjust <numArgs> to account for any arguments that have been passed on the
7013 // stack instead.
Andrew Trick74f4c742013-10-31 17:18:24 +00007014 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007015 unsigned NumCallRegArgs = Call->getNumOperands() - (hasGlue ? 4 : 3);
7016 NumCallRegArgs = isAnyRegCC ? NumArgs : NumCallRegArgs;
7017 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
7018
7019 // Add the calling convention
Juergen Ributzka87ed9062013-11-09 01:51:33 +00007020 Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007021
7022 // Add the arguments we omitted previously. The register allocator should
7023 // place these in any free register.
7024 if (isAnyRegCC)
Andrew Tricka2428e02013-11-22 19:07:33 +00007025 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007026 Ops.push_back(getValue(CI.getArgOperand(i)));
Andrew Trick74f4c742013-10-31 17:18:24 +00007027
Andrew Tricka2428e02013-11-22 19:07:33 +00007028 // Push the arguments from the call instruction up to the register mask.
Andrew Trick74f4c742013-10-31 17:18:24 +00007029 SDNode::op_iterator e = hasGlue ? Call->op_end()-2 : Call->op_end()-1;
7030 for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
7031 Ops.push_back(*i);
7032
7033 // Push live variables for the stack map.
Andrew Trick4a1abb72013-11-22 19:07:36 +00007034 addStackMapLiveVars(CI, NumMetaOpers + NumArgs, Ops, *this);
Andrew Trick74f4c742013-10-31 17:18:24 +00007035
7036 // Push the register mask info.
7037 if (hasGlue)
7038 Ops.push_back(*(Call->op_end()-2));
7039 else
7040 Ops.push_back(*(Call->op_end()-1));
7041
7042 // Push the chain (this is originally the first operand of the call, but
7043 // becomes now the last or second to last operand).
7044 Ops.push_back(*(Call->op_begin()));
7045
7046 // Push the glue flag (last operand).
7047 if (hasGlue)
7048 Ops.push_back(*(Call->op_end()-1));
7049
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007050 SDVTList NodeTys;
7051 if (isAnyRegCC && hasDef) {
7052 // Create the return types based on the intrinsic definition
7053 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7054 SmallVector<EVT, 3> ValueVTs;
7055 ComputeValueVTs(TLI, CI.getType(), ValueVTs);
7056 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
Andrew Trick6664df12013-11-05 22:44:04 +00007057
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007058 // There is always a chain and a glue type at the end
7059 ValueVTs.push_back(MVT::Other);
7060 ValueVTs.push_back(MVT::Glue);
7061 NodeTys = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
7062 } else
7063 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7064
7065 // Replace the target specific call node with a PATCHPOINT node.
Andrew Trick6664df12013-11-05 22:44:04 +00007066 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7067 getCurSDLoc(), NodeTys, Ops);
7068
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007069 // Update the NodeMap.
7070 if (hasDef) {
7071 if (isAnyRegCC)
7072 setValue(&CI, SDValue(MN, 0));
7073 else
7074 setValue(&CI, Result.first);
7075 }
Andrew Trick6664df12013-11-05 22:44:04 +00007076
7077 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007078 // call sequence. Furthermore the location of the chain and glue can change
7079 // when the AnyReg calling convention is used and the intrinsic returns a
7080 // value.
7081 if (isAnyRegCC && hasDef) {
7082 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7083 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7084 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7085 } else
7086 DAG.ReplaceAllUsesWith(Call, MN);
Andrew Trick6664df12013-11-05 22:44:04 +00007087 DAG.DeleteNode(Call);
Juergen Ributzkae8294752013-12-14 06:53:06 +00007088
7089 // Inform the Frame Information that we have a patchpoint in this function.
7090 FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
Andrew Trick74f4c742013-10-31 17:18:24 +00007091}
7092
Dan Gohman575fad32008-09-03 16:12:24 +00007093/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007094/// implementation, which just calls LowerCall.
7095/// FIXME: When all targets are
7096/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohman575fad32008-09-03 16:12:24 +00007097std::pair<SDValue, SDValue>
Justin Holewinskiaa583972012-05-25 16:35:28 +00007098TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
Stephen Lin699808c2013-04-30 22:49:28 +00007099 // Handle the incoming return values from the call.
7100 CLI.Ins.clear();
7101 SmallVector<EVT, 4> RetTys;
7102 ComputeValueVTs(*this, CLI.RetTy, RetTys);
7103 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7104 EVT VT = RetTys[I];
7105 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7106 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7107 for (unsigned i = 0; i != NumRegs; ++i) {
7108 ISD::InputArg MyFlags;
7109 MyFlags.VT = RegisterVT;
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007110 MyFlags.ArgVT = VT;
Stephen Lin699808c2013-04-30 22:49:28 +00007111 MyFlags.Used = CLI.IsReturnValueUsed;
7112 if (CLI.RetSExt)
7113 MyFlags.Flags.setSExt();
7114 if (CLI.RetZExt)
7115 MyFlags.Flags.setZExt();
7116 if (CLI.IsInReg)
7117 MyFlags.Flags.setInReg();
7118 CLI.Ins.push_back(MyFlags);
7119 }
7120 }
7121
Dan Gohman575fad32008-09-03 16:12:24 +00007122 // Handle all of the outgoing arguments.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007123 CLI.Outs.clear();
7124 CLI.OutVals.clear();
7125 ArgListTy &Args = CLI.Args;
Dan Gohman575fad32008-09-03 16:12:24 +00007126 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007127 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00007128 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
7129 for (unsigned Value = 0, NumValues = ValueVTs.size();
7130 Value != NumValues; ++Value) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007131 EVT VT = ValueVTs[Value];
Justin Holewinskiaa583972012-05-25 16:35:28 +00007132 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
Chris Lattner160e8ab2008-10-18 18:49:30 +00007133 SDValue Op = SDValue(Args[i].Node.getNode(),
7134 Args[i].Node.getResNo() + Value);
Dan Gohman575fad32008-09-03 16:12:24 +00007135 ISD::ArgFlagsTy Flags;
7136 unsigned OriginalAlignment =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00007137 getDataLayout()->getABITypeAlignment(ArgTy);
Dan Gohman575fad32008-09-03 16:12:24 +00007138
7139 if (Args[i].isZExt)
7140 Flags.setZExt();
7141 if (Args[i].isSExt)
7142 Flags.setSExt();
7143 if (Args[i].isInReg)
7144 Flags.setInReg();
7145 if (Args[i].isSRet)
7146 Flags.setSRet();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007147 if (Args[i].isByVal)
Dan Gohman575fad32008-09-03 16:12:24 +00007148 Flags.setByVal();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007149 if (Args[i].isInAlloca) {
7150 Flags.setInAlloca();
7151 // Set the byval flag for CCAssignFn callbacks that don't know about
7152 // inalloca. This way we can know how many bytes we should've allocated
7153 // and how many bytes a callee cleanup function will pop. If we port
7154 // inalloca to more targets, we'll have to add custom inalloca handling
7155 // in the various CC lowering callbacks.
7156 Flags.setByVal();
7157 }
7158 if (Args[i].isByVal || Args[i].isInAlloca) {
Chris Lattner229907c2011-07-18 04:54:35 +00007159 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7160 Type *ElementTy = Ty->getElementType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00007161 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
Dan Gohman575fad32008-09-03 16:12:24 +00007162 // For ByVal, alignment should come from FE. BE will guess if this
7163 // info is not there but there are cases it cannot get right.
Chris Lattner68254fc2011-05-22 23:23:02 +00007164 unsigned FrameAlign;
Dan Gohman575fad32008-09-03 16:12:24 +00007165 if (Args[i].Alignment)
7166 FrameAlign = Args[i].Alignment;
Chris Lattner68254fc2011-05-22 23:23:02 +00007167 else
7168 FrameAlign = getByValTypeAlignment(ElementTy);
Dan Gohman575fad32008-09-03 16:12:24 +00007169 Flags.setByValAlign(FrameAlign);
Dan Gohman575fad32008-09-03 16:12:24 +00007170 }
7171 if (Args[i].isNest)
7172 Flags.setNest();
7173 Flags.setOrigAlign(OriginalAlignment);
7174
Patrik Hagglundbad545c2012-12-19 11:48:16 +00007175 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
Justin Holewinskiaa583972012-05-25 16:35:28 +00007176 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohman575fad32008-09-03 16:12:24 +00007177 SmallVector<SDValue, 4> Parts(NumParts);
7178 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7179
7180 if (Args[i].isSExt)
7181 ExtendKind = ISD::SIGN_EXTEND;
7182 else if (Args[i].isZExt)
7183 ExtendKind = ISD::ZERO_EXTEND;
7184
Stephen Lin699808c2013-04-30 22:49:28 +00007185 // Conservatively only handle 'returned' on non-vectors for now
7186 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7187 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7188 "unexpected use of 'returned'");
7189 // Before passing 'returned' to the target lowering code, ensure that
7190 // either the register MVT and the actual EVT are the same size or that
7191 // the return value and argument are extended in the same way; in these
7192 // cases it's safe to pass the argument register value unchanged as the
7193 // return register value (although it's at the target's option whether
7194 // to do so)
7195 // TODO: allow code generation to take advantage of partially preserved
7196 // registers rather than clobbering the entire register when the
7197 // parameter extension method is not compatible with the return
7198 // extension method
7199 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7200 (ExtendKind != ISD::ANY_EXTEND &&
7201 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7202 Flags.setReturned();
7203 }
7204
Justin Holewinskiaa583972012-05-25 16:35:28 +00007205 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts,
Bill Wendling5def8912012-09-26 06:16:18 +00007206 PartVT, CLI.CS ? CLI.CS->getInstruction() : 0, ExtendKind);
Dan Gohman575fad32008-09-03 16:12:24 +00007207
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007208 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohman575fad32008-09-03 16:12:24 +00007209 // if it isn't first piece, alignment must be 1
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007210 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
Manman Ren3d5af272012-11-01 23:49:58 +00007211 i < CLI.NumFixedArgs,
7212 i, j*Parts[j].getValueType().getStoreSize());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007213 if (NumParts > 1 && j == 0)
7214 MyFlags.Flags.setSplit();
7215 else if (j != 0)
7216 MyFlags.Flags.setOrigAlign(1);
Dan Gohman575fad32008-09-03 16:12:24 +00007217
Justin Holewinskiaa583972012-05-25 16:35:28 +00007218 CLI.Outs.push_back(MyFlags);
7219 CLI.OutVals.push_back(Parts[j]);
Dan Gohman575fad32008-09-03 16:12:24 +00007220 }
7221 }
7222 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007223
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007224 SmallVector<SDValue, 4> InVals;
Justin Holewinskiaa583972012-05-25 16:35:28 +00007225 CLI.Chain = LowerCall(CLI, InVals);
Dan Gohman695d8112009-08-06 15:37:27 +00007226
7227 // Verify that the target's LowerCall behaved as expected.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007228 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00007229 "LowerCall didn't return a valid chain!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007230 assert((!CLI.IsTailCall || InVals.empty()) &&
Dan Gohman695d8112009-08-06 15:37:27 +00007231 "LowerCall emitted a return value for a tail call!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007232 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
Dan Gohman695d8112009-08-06 15:37:27 +00007233 "LowerCall didn't emit the correct number of values!");
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007234
7235 // For a tail call, the return value is merely live-out and there aren't
7236 // any nodes in the DAG representing it. Return a special value to
7237 // indicate that a tail call has been emitted and no more Instructions
7238 // should be processed in the current block.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007239 if (CLI.IsTailCall) {
7240 CLI.DAG.setRoot(CLI.Chain);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007241 return std::make_pair(SDValue(), SDValue());
7242 }
7243
Justin Holewinskiaa583972012-05-25 16:35:28 +00007244 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
Evan Cheng180704d2010-03-11 19:38:18 +00007245 assert(InVals[i].getNode() &&
7246 "LowerCall emitted a null value!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007247 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
Evan Cheng180704d2010-03-11 19:38:18 +00007248 "LowerCall emitted a value with the wrong type!");
7249 });
7250
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007251 // Collect the legal value parts into potentially illegal values
7252 // that correspond to the original function's return values.
7253 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Justin Holewinskiaa583972012-05-25 16:35:28 +00007254 if (CLI.RetSExt)
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007255 AssertOp = ISD::AssertSext;
Justin Holewinskiaa583972012-05-25 16:35:28 +00007256 else if (CLI.RetZExt)
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007257 AssertOp = ISD::AssertZext;
7258 SmallVector<SDValue, 4> ReturnValues;
7259 unsigned CurReg = 0;
7260 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007261 EVT VT = RetTys[I];
Patrik Hagglundbad545c2012-12-19 11:48:16 +00007262 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
Justin Holewinskiaa583972012-05-25 16:35:28 +00007263 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007264
Justin Holewinskiaa583972012-05-25 16:35:28 +00007265 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
Bill Wendling81406f62012-09-26 04:04:19 +00007266 NumRegs, RegisterVT, VT, NULL,
Bill Wendling954cb182010-01-28 21:51:40 +00007267 AssertOp));
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007268 CurReg += NumRegs;
7269 }
7270
7271 // For a function returning void, there is no return value. We can't create
7272 // such a node, so we just return a null return value in that case. In
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00007273 // that case, nothing will actually look at the value.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007274 if (ReturnValues.empty())
Justin Holewinskiaa583972012-05-25 16:35:28 +00007275 return std::make_pair(SDValue(), CLI.Chain);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007276
Justin Holewinskiaa583972012-05-25 16:35:28 +00007277 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7278 CLI.DAG.getVTList(&RetTys[0], RetTys.size()),
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007279 &ReturnValues[0], ReturnValues.size());
Justin Holewinskiaa583972012-05-25 16:35:28 +00007280 return std::make_pair(Res, CLI.Chain);
Dan Gohman575fad32008-09-03 16:12:24 +00007281}
7282
Duncan Sandsbe7e4142009-01-21 09:00:29 +00007283void TargetLowering::LowerOperationWrapper(SDNode *N,
7284 SmallVectorImpl<SDValue> &Results,
Dan Gohman21cea8a2010-04-17 15:26:15 +00007285 SelectionDAG &DAG) const {
Duncan Sandsbe7e4142009-01-21 09:00:29 +00007286 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptaa70798c2009-01-21 04:48:39 +00007287 if (Res.getNode())
7288 Results.push_back(Res);
7289}
7290
Dan Gohman21cea8a2010-04-17 15:26:15 +00007291SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
Torok Edwinfbcc6632009-07-14 16:55:14 +00007292 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohman575fad32008-09-03 16:12:24 +00007293}
7294
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007295void
7296SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
Dan Gohmand4322232010-07-01 01:59:43 +00007297 SDValue Op = getNonRegisterValue(V);
Dan Gohman575fad32008-09-03 16:12:24 +00007298 assert((Op.getOpcode() != ISD::CopyFromReg ||
7299 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7300 "Copy from a reg to the same reg!");
7301 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7302
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007303 const TargetLowering *TLI = TM.getTargetLowering();
7304 RegsForValue RFV(V->getContext(), *TLI, Reg, V->getType());
Dan Gohman575fad32008-09-03 16:12:24 +00007305 SDValue Chain = DAG.getEntryNode();
Andrew Trickef9de2a2013-05-25 02:42:55 +00007306 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, 0, V);
Dan Gohman575fad32008-09-03 16:12:24 +00007307 PendingExports.push_back(Chain);
7308}
7309
7310#include "llvm/CodeGen/SelectionDAGISel.h"
7311
Eli Friedman441a01a2011-05-05 16:53:34 +00007312/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7313/// entry block, return true. This includes arguments used by switches, since
7314/// the switch may expand into multiple basic blocks.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007315static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007316 // With FastISel active, we may be splitting blocks, so force creation
7317 // of virtual registers for all non-dead arguments.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007318 if (FastISel)
Eli Friedman441a01a2011-05-05 16:53:34 +00007319 return A->use_empty();
7320
7321 const BasicBlock *Entry = A->getParent()->begin();
Chandler Carruthcdf47882014-03-09 03:16:01 +00007322 for (const User *U : A->users())
Eli Friedman441a01a2011-05-05 16:53:34 +00007323 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7324 return false; // Use not in entry block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00007325
Eli Friedman441a01a2011-05-05 16:53:34 +00007326 return true;
7327}
7328
Eli Bendersky33ebf832013-02-28 23:09:18 +00007329void SelectionDAGISel::LowerArguments(const Function &F) {
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007330 SelectionDAG &DAG = SDB->DAG;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007331 SDLoc dl = SDB->getCurSDLoc();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007332 const TargetLowering *TLI = getTargetLowering();
Rafael Espindola5f57f462014-02-21 18:34:28 +00007333 const DataLayout *DL = TLI->getDataLayout();
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007334 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohman575fad32008-09-03 16:12:24 +00007335
Dan Gohmand16aa542010-05-29 17:03:36 +00007336 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007337 // Put in an sret pointer parameter before all the other parameters.
7338 SmallVector<EVT, 1> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007339 ComputeValueVTs(*getTargetLowering(),
7340 PointerType::getUnqual(F.getReturnType()), ValueVTs);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007341
7342 // NOTE: Assuming that a pointer will never break down to more than one VT
7343 // or one register.
7344 ISD::ArgFlagsTy Flags;
7345 Flags.setSRet();
Bill Wendlingf7719082013-06-06 00:43:09 +00007346 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007347 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007348 Ins.push_back(RetArg);
7349 }
Kenneth Uildriks07119732009-11-07 02:11:54 +00007350
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007351 // Set up the incoming argument description vector.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007352 unsigned Idx = 1;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007353 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007354 I != E; ++I, ++Idx) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007355 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007356 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007357 bool isArgValueUsed = !I->use_empty();
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007358 unsigned PartBase = 0;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007359 for (unsigned Value = 0, NumValues = ValueVTs.size();
7360 Value != NumValues; ++Value) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007361 EVT VT = ValueVTs[Value];
Chris Lattner229907c2011-07-18 04:54:35 +00007362 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007363 ISD::ArgFlagsTy Flags;
7364 unsigned OriginalAlignment =
Rafael Espindola5f57f462014-02-21 18:34:28 +00007365 DL->getABITypeAlignment(ArgTy);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007366
Bill Wendling94dcaf82012-12-30 12:45:13 +00007367 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007368 Flags.setZExt();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007369 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007370 Flags.setSExt();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007371 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007372 Flags.setInReg();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007373 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007374 Flags.setSRet();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007375 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007376 Flags.setByVal();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007377 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7378 Flags.setInAlloca();
7379 // Set the byval flag for CCAssignFn callbacks that don't know about
7380 // inalloca. This way we can know how many bytes we should've allocated
7381 // and how many bytes a callee cleanup function will pop. If we port
7382 // inalloca to more targets, we'll have to add custom inalloca handling
7383 // in the various CC lowering callbacks.
7384 Flags.setByVal();
7385 }
7386 if (Flags.isByVal() || Flags.isInAlloca()) {
Chris Lattner229907c2011-07-18 04:54:35 +00007387 PointerType *Ty = cast<PointerType>(I->getType());
7388 Type *ElementTy = Ty->getElementType();
Rafael Espindola5f57f462014-02-21 18:34:28 +00007389 Flags.setByValSize(DL->getTypeAllocSize(ElementTy));
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007390 // For ByVal, alignment should be passed from FE. BE will guess if
7391 // this info is not there but there are cases it cannot get right.
Chris Lattner68254fc2011-05-22 23:23:02 +00007392 unsigned FrameAlign;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007393 if (F.getParamAlignment(Idx))
7394 FrameAlign = F.getParamAlignment(Idx);
Chris Lattner68254fc2011-05-22 23:23:02 +00007395 else
Bill Wendlingf7719082013-06-06 00:43:09 +00007396 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007397 Flags.setByValAlign(FrameAlign);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007398 }
Bill Wendling94dcaf82012-12-30 12:45:13 +00007399 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007400 Flags.setNest();
7401 Flags.setOrigAlign(OriginalAlignment);
7402
Bill Wendlingf7719082013-06-06 00:43:09 +00007403 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7404 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007405 for (unsigned i = 0; i != NumRegs; ++i) {
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007406 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7407 Idx-1, PartBase+i*RegisterVT.getStoreSize());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007408 if (NumRegs > 1 && i == 0)
7409 MyFlags.Flags.setSplit();
7410 // if it isn't first piece, alignment must be 1
7411 else if (i > 0)
7412 MyFlags.Flags.setOrigAlign(1);
7413 Ins.push_back(MyFlags);
7414 }
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007415 PartBase += VT.getStoreSize();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007416 }
7417 }
7418
7419 // Call the target to set up the argument values.
7420 SmallVector<SDValue, 8> InVals;
Bill Wendlingf7719082013-06-06 00:43:09 +00007421 SDValue NewRoot = TLI->LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
7422 F.isVarArg(), Ins,
7423 dl, DAG, InVals);
Dan Gohman695d8112009-08-06 15:37:27 +00007424
7425 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson9f944592009-08-11 20:47:22 +00007426 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00007427 "LowerFormalArguments didn't return a valid chain!");
7428 assert(InVals.size() == Ins.size() &&
7429 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendlingd8549812009-12-22 21:35:02 +00007430 DEBUG({
7431 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7432 assert(InVals[i].getNode() &&
7433 "LowerFormalArguments emitted a null value!");
Duncan Sandsf5dda012010-11-03 11:35:31 +00007434 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
Bill Wendlingd8549812009-12-22 21:35:02 +00007435 "LowerFormalArguments emitted a value with the wrong type!");
7436 }
7437 });
Bill Wendling919b7aa2009-12-22 02:10:19 +00007438
Dan Gohman695d8112009-08-06 15:37:27 +00007439 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007440 DAG.setRoot(NewRoot);
7441
7442 // Set up the argument values.
7443 unsigned i = 0;
7444 Idx = 1;
Dan Gohmand16aa542010-05-29 17:03:36 +00007445 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007446 // Create a virtual register for the sret pointer, and put in a copy
7447 // from the sret argument into it.
7448 SmallVector<EVT, 1> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007449 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00007450 MVT VT = ValueVTs[0].getSimpleVT();
Bill Wendlingf7719082013-06-06 00:43:09 +00007451 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007452 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling78c5b7a2010-03-02 01:55:18 +00007453 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
Bill Wendling81406f62012-09-26 04:04:19 +00007454 RegVT, VT, NULL, AssertOp);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007455
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007456 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007457 MachineRegisterInfo& RegInfo = MF.getRegInfo();
Bill Wendlingf7719082013-06-06 00:43:09 +00007458 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
Dan Gohmand16aa542010-05-29 17:03:36 +00007459 FuncInfo->DemoteRegister = SRetReg;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007460 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(),
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00007461 SRetReg, ArgValue);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007462 DAG.setRoot(NewRoot);
Bill Wendling919b7aa2009-12-22 02:10:19 +00007463
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007464 // i indexes lowered arguments. Bump it past the hidden sret argument.
7465 // Idx indexes LLVM arguments. Don't touch it.
7466 ++i;
7467 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007468
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007469 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007470 ++I, ++Idx) {
7471 SmallVector<SDValue, 4> ArgValues;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007472 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007473 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00007474 unsigned NumValues = ValueVTs.size();
Devang Patelb0c76392010-06-01 19:59:01 +00007475
7476 // If this argument is unused then remember its value. It is used to generate
7477 // debugging information.
Adrian Prantl9c930592013-05-16 23:44:12 +00007478 if (I->use_empty() && NumValues) {
Devang Patelb0c76392010-06-01 19:59:01 +00007479 SDB->setUnusedArgValue(I, InVals[i]);
7480
Adrian Prantl9c930592013-05-16 23:44:12 +00007481 // Also remember any frame index for use in FastISel.
7482 if (FrameIndexSDNode *FI =
7483 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7484 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7485 }
7486
Eli Friedman441a01a2011-05-05 16:53:34 +00007487 for (unsigned Val = 0; Val != NumValues; ++Val) {
7488 EVT VT = ValueVTs[Val];
Bill Wendlingf7719082013-06-06 00:43:09 +00007489 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7490 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007491
7492 if (!I->use_empty()) {
7493 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling94dcaf82012-12-30 12:45:13 +00007494 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007495 AssertOp = ISD::AssertSext;
Bill Wendling94dcaf82012-12-30 12:45:13 +00007496 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007497 AssertOp = ISD::AssertZext;
7498
Bill Wendling78c5b7a2010-03-02 01:55:18 +00007499 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
Bill Wendling919b7aa2009-12-22 02:10:19 +00007500 NumParts, PartVT, VT,
Bill Wendling81406f62012-09-26 04:04:19 +00007501 NULL, AssertOp));
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007502 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007503
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007504 i += NumParts;
7505 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007506
Eli Friedman441a01a2011-05-05 16:53:34 +00007507 // We don't need to do anything else for unused arguments.
7508 if (ArgValues.empty())
7509 continue;
7510
Devang Patel9d904e12011-09-08 22:59:09 +00007511 // Note down frame index.
7512 if (FrameIndexSDNode *FI =
Bill Wendlingd1634052012-07-19 00:04:14 +00007513 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
Devang Patel9d904e12011-09-08 22:59:09 +00007514 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
Devang Patel86ec8b32010-08-31 22:22:42 +00007515
Eli Friedman441a01a2011-05-05 16:53:34 +00007516 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007517 SDB->getCurSDLoc());
Devang Patel9d904e12011-09-08 22:59:09 +00007518
Eli Friedman441a01a2011-05-05 16:53:34 +00007519 SDB->setValue(I, Res);
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007520 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007521 if (LoadSDNode *LNode =
Devang Patel9d904e12011-09-08 22:59:09 +00007522 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7523 if (FrameIndexSDNode *FI =
7524 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7525 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7526 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007527
Eli Friedman441a01a2011-05-05 16:53:34 +00007528 // If this argument is live outside of the entry block, insert a copy from
7529 // wherever we got it to the vreg that other BB's will reference it as.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007530 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007531 // If we can, though, try to skip creating an unnecessary vreg.
7532 // FIXME: This isn't very clean... it would be nice to make this more
Eli Friedman768de0a2011-05-10 21:50:58 +00007533 // general. It's also subtly incompatible with the hacks FastISel
7534 // uses with vregs.
Eli Friedman441a01a2011-05-05 16:53:34 +00007535 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7536 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7537 FuncInfo->ValueMap[I] = Reg;
7538 continue;
7539 }
7540 }
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007541 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007542 FuncInfo->InitializeRegForValue(I);
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007543 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohman575fad32008-09-03 16:12:24 +00007544 }
Dan Gohman575fad32008-09-03 16:12:24 +00007545 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007546
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007547 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohman575fad32008-09-03 16:12:24 +00007548
7549 // Finally, if the target has anything special to do, allow it to do so.
7550 // FIXME: this should insert code into the DAG!
Dan Gohmanc87b74d2010-04-14 20:17:22 +00007551 EmitFunctionEntryCode();
Dan Gohman575fad32008-09-03 16:12:24 +00007552}
7553
7554/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7555/// ensure constants are generated when needed. Remember the virtual registers
7556/// that need to be added to the Machine PHI nodes as input. We cannot just
7557/// directly add them, because expansion might result in multiple MBB's for one
7558/// BB. As such, the start of the BB might correspond to a different MBB than
7559/// the end.
7560///
7561void
Dan Gohmanc594eab2010-04-22 20:46:50 +00007562SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007563 const TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohman575fad32008-09-03 16:12:24 +00007564
7565 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7566
7567 // Check successor nodes' PHI nodes that expect a constant to be available
7568 // from this block.
7569 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007570 const BasicBlock *SuccBB = TI->getSuccessor(succ);
Dan Gohman575fad32008-09-03 16:12:24 +00007571 if (!isa<PHINode>(SuccBB->begin())) continue;
Dan Gohmanc594eab2010-04-22 20:46:50 +00007572 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007573
Dan Gohman575fad32008-09-03 16:12:24 +00007574 // If this terminator has multiple identical successors (common for
7575 // switches), only handle each succ once.
7576 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007577
Dan Gohman575fad32008-09-03 16:12:24 +00007578 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Dan Gohman575fad32008-09-03 16:12:24 +00007579
7580 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7581 // nodes and Machine PHI nodes, but the incoming operands have not been
7582 // emitted yet.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007583 for (BasicBlock::const_iterator I = SuccBB->begin();
7584 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohman575fad32008-09-03 16:12:24 +00007585 // Ignore dead phi's.
7586 if (PN->use_empty()) continue;
7587
Rafael Espindolae53b7d12011-05-13 15:18:06 +00007588 // Skip empty types
7589 if (PN->getType()->isEmptyTy())
7590 continue;
7591
Dan Gohman575fad32008-09-03 16:12:24 +00007592 unsigned Reg;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007593 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00007594
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007595 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohmanc594eab2010-04-22 20:46:50 +00007596 unsigned &RegOut = ConstantsOut[C];
Dan Gohman575fad32008-09-03 16:12:24 +00007597 if (RegOut == 0) {
Dan Gohman93f59202010-07-02 00:10:16 +00007598 RegOut = FuncInfo.CreateRegs(C->getType());
Dan Gohmanc594eab2010-04-22 20:46:50 +00007599 CopyValueToVirtualRegister(C, RegOut);
Dan Gohman575fad32008-09-03 16:12:24 +00007600 }
7601 Reg = RegOut;
7602 } else {
Dan Gohman9576645a2010-07-01 01:33:21 +00007603 DenseMap<const Value *, unsigned>::iterator I =
7604 FuncInfo.ValueMap.find(PHIOp);
7605 if (I != FuncInfo.ValueMap.end())
7606 Reg = I->second;
7607 else {
Dan Gohman575fad32008-09-03 16:12:24 +00007608 assert(isa<AllocaInst>(PHIOp) &&
Dan Gohmanc594eab2010-04-22 20:46:50 +00007609 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
Dan Gohman575fad32008-09-03 16:12:24 +00007610 "Didn't codegen value into a register!??");
Dan Gohman93f59202010-07-02 00:10:16 +00007611 Reg = FuncInfo.CreateRegs(PHIOp->getType());
Dan Gohmanc594eab2010-04-22 20:46:50 +00007612 CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohman575fad32008-09-03 16:12:24 +00007613 }
7614 }
7615
7616 // Remember that this register needs to added to the machine PHI node as
7617 // the input for this MBB.
Owen Anderson53aa7a92009-08-10 22:56:29 +00007618 SmallVector<EVT, 4> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007619 const TargetLowering *TLI = TM.getTargetLowering();
7620 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00007621 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007622 EVT VT = ValueVTs[vti];
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007623 unsigned NumRegisters = TLI->getNumRegisters(*DAG.getContext(), VT);
Dan Gohman575fad32008-09-03 16:12:24 +00007624 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohmanc594eab2010-04-22 20:46:50 +00007625 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohman575fad32008-09-03 16:12:24 +00007626 Reg += NumRegisters;
7627 }
7628 }
7629 }
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007630
Dan Gohmanc594eab2010-04-22 20:46:50 +00007631 ConstantsOut.clear();
Dan Gohman7bda51f2008-09-03 23:12:08 +00007632}
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00007633
7634/// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7635/// is 0.
7636MachineBasicBlock *
7637SelectionDAGBuilder::StackProtectorDescriptor::
7638AddSuccessorMBB(const BasicBlock *BB,
7639 MachineBasicBlock *ParentMBB,
7640 MachineBasicBlock *SuccMBB) {
7641 // If SuccBB has not been created yet, create it.
7642 if (!SuccMBB) {
7643 MachineFunction *MF = ParentMBB->getParent();
7644 MachineFunction::iterator BBI = ParentMBB;
7645 SuccMBB = MF->CreateMachineBasicBlock(BB);
7646 MF->insert(++BBI, SuccMBB);
7647 }
7648 // Add it as a successor of ParentMBB.
7649 ParentMBB->addSuccessor(SuccMBB);
7650 return SuccMBB;
7651}