blob: cc6eac70ba7b64e2920cffcc47c962813355f4a7 [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
Dan Gohman1a6c47f2009-11-23 18:04:58 +000014#include "SelectionDAGBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "SDNodeDbgValue.h"
Dan Gohman575fad32008-09-03 16:12:24 +000016#include "llvm/ADT/BitVector.h"
David Blaikie0252265b2013-06-16 20:34:15 +000017#include "llvm/ADT/Optional.h"
Dan Gohman5eba3bc2008-09-04 20:49:27 +000018#include "llvm/ADT/SmallSet.h"
Dan Gohman575fad32008-09-03 16:12:24 +000019#include "llvm/Analysis/AliasAnalysis.h"
Jakub Staszaka9286e92013-01-10 22:13:13 +000020#include "llvm/Analysis/BranchProbabilityInfo.h"
Chris Lattner1a32ede2009-12-24 00:37:38 +000021#include "llvm/Analysis/ConstantFolding.h"
Nadav Rotem7c277da2012-09-06 09:17:37 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/CodeGen/Analysis.h"
24#include "llvm/CodeGen/FastISel.h"
25#include "llvm/CodeGen/FunctionLoweringInfo.h"
26#include "llvm/CodeGen/GCMetadata.h"
27#include "llvm/CodeGen/GCStrategy.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineInstrBuilder.h"
31#include "llvm/CodeGen/MachineJumpTableInfo.h"
32#include "llvm/CodeGen/MachineModuleInfo.h"
33#include "llvm/CodeGen/MachineRegisterInfo.h"
34#include "llvm/CodeGen/SelectionDAG.h"
Andrew Trick153ebe62013-10-31 22:11:56 +000035#include "llvm/CodeGen/StackMaps.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/CallingConv.h"
37#include "llvm/IR/Constants.h"
38#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000039#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/DerivedTypes.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/GlobalVariable.h"
43#include "llvm/IR/InlineAsm.h"
44#include "llvm/IR/Instructions.h"
45#include "llvm/IR/IntrinsicInst.h"
46#include "llvm/IR/Intrinsics.h"
47#include "llvm/IR/LLVMContext.h"
48#include "llvm/IR/Module.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000049#include "llvm/Support/CommandLine.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000052#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov2f931282011-01-10 12:39:04 +000054#include "llvm/Target/TargetFrameLowering.h"
Dan Gohman575fad32008-09-03 16:12:24 +000055#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesenb842d522009-02-05 01:49:45 +000056#include "llvm/Target/TargetIntrinsicInfo.h"
Owen Andersonbb15fec2011-12-08 22:15:21 +000057#include "llvm/Target/TargetLibraryInfo.h"
Dan Gohman575fad32008-09-03 16:12:24 +000058#include "llvm/Target/TargetLowering.h"
Dan Gohman575fad32008-09-03 16:12:24 +000059#include "llvm/Target/TargetOptions.h"
Richard Sandiford564681c2013-08-12 10:28:10 +000060#include "llvm/Target/TargetSelectionDAGInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000061#include "llvm/Target/TargetSubtargetInfo.h"
Dan Gohman575fad32008-09-03 16:12:24 +000062#include <algorithm>
63using namespace llvm;
64
Chandler Carruth1b9dde02014-04-22 02:02:50 +000065#define DEBUG_TYPE "isel"
66
Dale Johannesenf2a52bb2008-09-05 01:48:15 +000067/// LimitFloatPrecision - Generate low-precision inline sequences for
68/// some float libcalls (6, 8 or 12 bits).
69static unsigned LimitFloatPrecision;
70
71static cl::opt<unsigned, true>
72LimitFPPrecision("limit-float-precision",
73 cl::desc("Generate low-precision inline sequences "
74 "for some float libcalls"),
75 cl::location(LimitFloatPrecision),
76 cl::init(0));
77
Andrew Trick116efac2010-11-12 17:50:46 +000078// Limit the width of DAG chains. This is important in general to prevent
79// prevent DAG-based analysis from blowing up. For example, alias analysis and
80// load clustering may not complete in reasonable time. It is difficult to
81// recognize and avoid this situation within each individual analysis, and
82// future analyses are likely to have the same behavior. Limiting DAG width is
Andrew Trickcf7fefb2010-11-20 07:26:51 +000083// the safe approach, and will be especially important with global DAGs.
Andrew Trick116efac2010-11-12 17:50:46 +000084//
85// MaxParallelChains default is arbitrarily high to avoid affecting
86// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
Andrew Trickcf7fefb2010-11-20 07:26:51 +000087// sequence over this should have been converted to llvm.memcpy by the
88// frontend. It easy to induce this behavior with .ll code such as:
89// %buffer = alloca [4096 x i8]
90// %data = load [4096 x i8]* %argPtr
91// store [4096 x i8] %data, [4096 x i8]* %buffer
Andrew Trick710d5da2011-03-11 17:46:59 +000092static const unsigned MaxParallelChains = 64;
Andrew Trick116efac2010-11-12 17:50:46 +000093
Andrew Trickef9de2a2013-05-25 02:42:55 +000094static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner05bcb482010-08-24 23:20:40 +000095 const SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +000096 MVT PartVT, EVT ValueVT, const Value *V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +000097
Dan Gohman575fad32008-09-03 16:12:24 +000098/// getCopyFromParts - Create a value that contains the specified legal parts
99/// combined into the value they represent. If the parts combine to a type
100/// larger then ValueVT then AssertOp can be used to specify whether the extra
101/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
102/// (ISD::AssertSext).
Andrew Trickef9de2a2013-05-25 02:42:55 +0000103static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
Dale Johannesendb7c5f62009-01-31 02:22:37 +0000104 const SDValue *Parts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000105 unsigned NumParts, MVT PartVT, EVT ValueVT,
Bill Wendling81406f62012-09-26 04:04:19 +0000106 const Value *V,
Duncan Sandsba21b7d2009-01-28 14:42:54 +0000107 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000108 if (ValueVT.isVector())
Bill Wendling81406f62012-09-26 04:04:19 +0000109 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
110 PartVT, ValueVT, V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000111
Dan Gohman575fad32008-09-03 16:12:24 +0000112 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohman91febd12009-01-15 16:58:17 +0000113 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +0000114 SDValue Val = Parts[0];
115
116 if (NumParts > 1) {
117 // Assemble the value from multiple parts.
Chris Lattner05bcb482010-08-24 23:20:40 +0000118 if (ValueVT.isInteger()) {
Dan Gohman575fad32008-09-03 16:12:24 +0000119 unsigned PartBits = PartVT.getSizeInBits();
120 unsigned ValueBits = ValueVT.getSizeInBits();
121
122 // Assemble the power of 2 part.
123 unsigned RoundParts = NumParts & (NumParts - 1) ?
124 1 << Log2_32(NumParts) : NumParts;
125 unsigned RoundBits = PartBits * RoundParts;
Owen Anderson53aa7a92009-08-10 22:56:29 +0000126 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson117c9e82009-08-12 00:36:31 +0000127 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohman575fad32008-09-03 16:12:24 +0000128 SDValue Lo, Hi;
129
Owen Anderson117c9e82009-08-12 00:36:31 +0000130 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sands17e678b2008-10-29 14:22:20 +0000131
Dan Gohman575fad32008-09-03 16:12:24 +0000132 if (RoundParts > 2) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000133 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
Bill Wendling81406f62012-09-26 04:04:19 +0000134 PartVT, HalfVT, V);
Chris Lattner05bcb482010-08-24 23:20:40 +0000135 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
Bill Wendling81406f62012-09-26 04:04:19 +0000136 RoundParts / 2, PartVT, HalfVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000137 } else {
Wesley Peck527da1b2010-11-23 03:31:01 +0000138 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
139 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
Dan Gohman575fad32008-09-03 16:12:24 +0000140 }
Bill Wendling919b7aa2009-12-22 02:10:19 +0000141
Dan Gohman575fad32008-09-03 16:12:24 +0000142 if (TLI.isBigEndian())
143 std::swap(Lo, Hi);
Bill Wendling919b7aa2009-12-22 02:10:19 +0000144
Chris Lattner05bcb482010-08-24 23:20:40 +0000145 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
Dan Gohman575fad32008-09-03 16:12:24 +0000146
147 if (RoundParts < NumParts) {
148 // Assemble the trailing non-power-of-2 part.
149 unsigned OddParts = NumParts - RoundParts;
Owen Anderson117c9e82009-08-12 00:36:31 +0000150 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Chris Lattner05bcb482010-08-24 23:20:40 +0000151 Hi = getCopyFromParts(DAG, DL,
Bill Wendling81406f62012-09-26 04:04:19 +0000152 Parts + RoundParts, OddParts, PartVT, OddVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000153
154 // Combine the round and odd parts.
155 Lo = Val;
156 if (TLI.isBigEndian())
157 std::swap(Lo, Hi);
Owen Anderson117c9e82009-08-12 00:36:31 +0000158 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Chris Lattner05bcb482010-08-24 23:20:40 +0000159 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
160 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
Dan Gohman575fad32008-09-03 16:12:24 +0000161 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands41826032009-01-31 15:50:11 +0000162 TLI.getPointerTy()));
Chris Lattner05bcb482010-08-24 23:20:40 +0000163 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
164 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
Dan Gohman575fad32008-09-03 16:12:24 +0000165 }
Eli Friedman9030c352009-05-20 06:02:09 +0000166 } else if (PartVT.isFloatingPoint()) {
167 // FP split into multiple FP parts (for ppcf128)
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000168 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
Eli Friedman9030c352009-05-20 06:02:09 +0000169 "Unexpected split");
170 SDValue Lo, Hi;
Wesley Peck527da1b2010-11-23 03:31:01 +0000171 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
172 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
Ulrich Weigandf236bb12014-07-03 15:06:47 +0000173 if (TLI.hasBigEndianPartOrdering(ValueVT))
Eli Friedman9030c352009-05-20 06:02:09 +0000174 std::swap(Lo, Hi);
Chris Lattner05bcb482010-08-24 23:20:40 +0000175 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
Eli Friedman9030c352009-05-20 06:02:09 +0000176 } else {
177 // FP split into integer parts (soft fp)
178 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
179 !PartVT.isVector() && "Unexpected split");
Owen Anderson117c9e82009-08-12 00:36:31 +0000180 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Bill Wendling81406f62012-09-26 04:04:19 +0000181 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000182 }
183 }
184
185 // There is now one part, held in Val. Correct it to match ValueVT.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000186 EVT PartEVT = Val.getValueType();
Dan Gohman575fad32008-09-03 16:12:24 +0000187
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000188 if (PartEVT == ValueVT)
Dan Gohman575fad32008-09-03 16:12:24 +0000189 return Val;
190
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000191 if (PartEVT.isInteger() && ValueVT.isInteger()) {
192 if (ValueVT.bitsLT(PartEVT)) {
Dan Gohman575fad32008-09-03 16:12:24 +0000193 // For a truncate, see if we have any information to
194 // indicate whether the truncated bits will always be
195 // zero or sign-extension.
196 if (AssertOp != ISD::DELETED_NODE)
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000197 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
Dan Gohman575fad32008-09-03 16:12:24 +0000198 DAG.getValueType(ValueVT));
Chris Lattner05bcb482010-08-24 23:20:40 +0000199 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000200 }
Chris Lattner05bcb482010-08-24 23:20:40 +0000201 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000202 }
203
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000204 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000205 // FP_ROUND's are always exact here.
206 if (ValueVT.bitsLT(Val.getValueType()))
207 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
Pete Coopere3d305a2012-01-17 01:54:07 +0000208 DAG.getTargetConstant(1, TLI.getPointerTy()));
Bill Wendling919b7aa2009-12-22 02:10:19 +0000209
Chris Lattner05bcb482010-08-24 23:20:40 +0000210 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000211 }
212
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000213 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
Wesley Peck527da1b2010-11-23 03:31:01 +0000214 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000215
Torok Edwinfbcc6632009-07-14 16:55:14 +0000216 llvm_unreachable("Unknown mismatch!");
Dan Gohman575fad32008-09-03 16:12:24 +0000217}
218
Benjamin Kramerfd719b92014-03-29 16:54:29 +0000219static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
220 const Twine &ErrMsg) {
221 const Instruction *I = dyn_cast_or_null<Instruction>(V);
222 if (!V)
223 return Ctx.emitError(ErrMsg);
224
225 const char *AsmError = ", possible invalid constraint for vector type";
226 if (const CallInst *CI = dyn_cast<CallInst>(I))
227 if (isa<InlineAsm>(CI->getCalledValue()))
228 return Ctx.emitError(I, ErrMsg + AsmError);
229
230 return Ctx.emitError(I, ErrMsg);
231}
232
Bill Wendling81406f62012-09-26 04:04:19 +0000233/// getCopyFromPartsVector - Create a value that contains the specified legal
234/// parts combined into the value they represent. If the parts combine to a
235/// type larger then ValueVT then AssertOp can be used to specify whether the
236/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
237/// ValueVT (ISD::AssertSext).
Andrew Trickef9de2a2013-05-25 02:42:55 +0000238static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner05bcb482010-08-24 23:20:40 +0000239 const SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000240 MVT PartVT, EVT ValueVT, const Value *V) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000241 assert(ValueVT.isVector() && "Not a vector value");
242 assert(NumParts > 0 && "No parts to assemble!");
243 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
244 SDValue Val = Parts[0];
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000245
Chris Lattner05bcb482010-08-24 23:20:40 +0000246 // Handle a multi-element vector.
247 if (NumParts > 1) {
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000248 EVT IntermediateVT;
249 MVT RegisterVT;
Chris Lattner05bcb482010-08-24 23:20:40 +0000250 unsigned NumIntermediates;
251 unsigned NumRegs =
252 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
253 NumIntermediates, RegisterVT);
254 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
255 NumParts = NumRegs; // Silence a compiler warning.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000256 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000257 assert(RegisterVT == Parts[0].getSimpleValueType() &&
Chris Lattner05bcb482010-08-24 23:20:40 +0000258 "Part type doesn't match part!");
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000259
Chris Lattner05bcb482010-08-24 23:20:40 +0000260 // Assemble the parts into intermediate operands.
261 SmallVector<SDValue, 8> Ops(NumIntermediates);
262 if (NumIntermediates == NumParts) {
263 // If the register was not expanded, truncate or copy the value,
264 // as appropriate.
265 for (unsigned i = 0; i != NumParts; ++i)
266 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
Bill Wendling81406f62012-09-26 04:04:19 +0000267 PartVT, IntermediateVT, V);
Chris Lattner05bcb482010-08-24 23:20:40 +0000268 } else if (NumParts > 0) {
269 // If the intermediate type was expanded, build the intermediate
270 // operands from the parts.
271 assert(NumParts % NumIntermediates == 0 &&
272 "Must expand into a divisible number of parts!");
273 unsigned Factor = NumParts / NumIntermediates;
274 for (unsigned i = 0; i != NumIntermediates; ++i)
275 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
Bill Wendling81406f62012-09-26 04:04:19 +0000276 PartVT, IntermediateVT, V);
Chris Lattner05bcb482010-08-24 23:20:40 +0000277 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000278
Chris Lattner05bcb482010-08-24 23:20:40 +0000279 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
280 // intermediate operands.
Craig Topper48d114b2014-04-26 18:35:24 +0000281 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
282 : ISD::BUILD_VECTOR,
283 DL, ValueVT, Ops);
Chris Lattner05bcb482010-08-24 23:20:40 +0000284 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000285
Chris Lattner05bcb482010-08-24 23:20:40 +0000286 // There is now one part, held in Val. Correct it to match ValueVT.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000287 EVT PartEVT = Val.getValueType();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000288
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000289 if (PartEVT == ValueVT)
Chris Lattner05bcb482010-08-24 23:20:40 +0000290 return Val;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000291
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000292 if (PartEVT.isVector()) {
Chris Lattner75ff0532010-08-25 22:49:25 +0000293 // If the element type of the source/dest vectors are the same, but the
294 // parts vector has more elements than the value vector, then we have a
295 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
296 // elements we want.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000297 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
298 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
Chris Lattner75ff0532010-08-25 22:49:25 +0000299 "Cannot narrow, it would be a lossy transformation");
300 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
Tom Stellardd42c5942013-08-05 22:22:01 +0000301 DAG.getConstant(0, TLI.getVectorIdxTy()));
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000302 }
303
Chris Lattner75ff0532010-08-25 22:49:25 +0000304 // Vector/Vector bitcast.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000305 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000306 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
307
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000308 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000309 "Cannot handle this kind of promotion");
310 // Promoted vector extract
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000311 bool Smaller = ValueVT.bitsLE(PartEVT);
Nadav Rotem083837e2011-06-12 14:49:38 +0000312 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
313 DL, ValueVT, Val);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000314
Chris Lattner75ff0532010-08-25 22:49:25 +0000315 }
Eric Christopher0713a9d2011-06-08 23:55:35 +0000316
Eric Christopher690030c2011-06-01 19:55:10 +0000317 // Trivial bitcast if the types are the same size and the destination
318 // vector type is legal.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000319 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
Eric Christopher690030c2011-06-01 19:55:10 +0000320 TLI.isTypeLegal(ValueVT))
321 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000322
Nadav Rotem083837e2011-06-12 14:49:38 +0000323 // Handle cases such as i8 -> <1 x i1>
Bill Wendling81406f62012-09-26 04:04:19 +0000324 if (ValueVT.getVectorNumElements() != 1) {
Benjamin Kramerfd719b92014-03-29 16:54:29 +0000325 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
326 "non-trivial scalar-to-vector conversion");
Chad Rosier8e4824f2013-05-01 19:49:26 +0000327 return DAG.getUNDEF(ValueVT);
Bill Wendling81406f62012-09-26 04:04:19 +0000328 }
Nadav Rotem083837e2011-06-12 14:49:38 +0000329
330 if (ValueVT.getVectorNumElements() == 1 &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000331 ValueVT.getVectorElementType() != PartEVT) {
332 bool Smaller = ValueVT.bitsLE(PartEVT);
Nadav Rotem083837e2011-06-12 14:49:38 +0000333 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
334 DL, ValueVT.getScalarType(), Val);
335 }
336
Chris Lattner05bcb482010-08-24 23:20:40 +0000337 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
338}
339
Andrew Trickef9de2a2013-05-25 02:42:55 +0000340static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
Chris Lattner96a77eb2010-08-24 23:10:06 +0000341 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000342 MVT PartVT, const Value *V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000343
Dan Gohman575fad32008-09-03 16:12:24 +0000344/// getCopyToParts - Create a series of nodes that contain the specified value
345/// split into legal parts. If the parts contain more bits than Val, then, for
346/// integers, ExtendKind can be used to specify how to generate the extra bits.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000347static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
Bill Wendling919b7aa2009-12-22 02:10:19 +0000348 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000349 MVT PartVT, const Value *V,
Dan Gohman575fad32008-09-03 16:12:24 +0000350 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000351 EVT ValueVT = Val.getValueType();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000352
Chris Lattner96a77eb2010-08-24 23:10:06 +0000353 // Handle the vector case separately.
354 if (ValueVT.isVector())
Bill Wendling5def8912012-09-26 06:16:18 +0000355 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000356
Chris Lattner96a77eb2010-08-24 23:10:06 +0000357 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +0000358 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen7d12ea02009-02-25 22:39:13 +0000359 unsigned OrigNumParts = NumParts;
Dan Gohman575fad32008-09-03 16:12:24 +0000360 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
361
Chris Lattner96a77eb2010-08-24 23:10:06 +0000362 if (NumParts == 0)
Dan Gohman575fad32008-09-03 16:12:24 +0000363 return;
364
Chris Lattner96a77eb2010-08-24 23:10:06 +0000365 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000366 EVT PartEVT = PartVT;
367 if (PartEVT == ValueVT) {
Chris Lattner96a77eb2010-08-24 23:10:06 +0000368 assert(NumParts == 1 && "No-op copy with multiple parts!");
Dan Gohman575fad32008-09-03 16:12:24 +0000369 Parts[0] = Val;
370 return;
371 }
372
Chris Lattner96a77eb2010-08-24 23:10:06 +0000373 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
374 // If the parts cover more bits than the value has, promote the value.
375 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
376 assert(NumParts == 1 && "Do not know what to promote to!");
377 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
378 } else {
Bill Wendling38b31612012-02-23 23:25:25 +0000379 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
380 ValueVT.isInteger() &&
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000381 "Unknown mismatch!");
Chris Lattner96a77eb2010-08-24 23:10:06 +0000382 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
383 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
Bill Wendling38b31612012-02-23 23:25:25 +0000384 if (PartVT == MVT::x86mmx)
385 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000386 }
387 } else if (PartBits == ValueVT.getSizeInBits()) {
388 // Different types of the same size.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000389 assert(NumParts == 1 && PartEVT != ValueVT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000390 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000391 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
392 // If the parts cover less bits than value has, truncate the value.
Bill Wendling38b31612012-02-23 23:25:25 +0000393 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
394 ValueVT.isInteger() &&
Chris Lattner96a77eb2010-08-24 23:10:06 +0000395 "Unknown mismatch!");
396 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
397 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Bill Wendling38b31612012-02-23 23:25:25 +0000398 if (PartVT == MVT::x86mmx)
399 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000400 }
401
402 // The value may have changed - recompute ValueVT.
403 ValueVT = Val.getValueType();
404 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
405 "Failed to tile the value with PartVT!");
406
407 if (NumParts == 1) {
Benjamin Kramerfd719b92014-03-29 16:54:29 +0000408 if (PartEVT != ValueVT)
409 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
410 "scalar-to-vector conversion failed");
Bill Wendling5def8912012-09-26 06:16:18 +0000411
Chris Lattner96a77eb2010-08-24 23:10:06 +0000412 Parts[0] = Val;
413 return;
414 }
415
416 // Expand the value into multiple parts.
417 if (NumParts & (NumParts - 1)) {
418 // The number of parts is not a power of 2. Split off and copy the tail.
419 assert(PartVT.isInteger() && ValueVT.isInteger() &&
420 "Do not know what to expand to!");
421 unsigned RoundParts = 1 << Log2_32(NumParts);
422 unsigned RoundBits = RoundParts * PartBits;
423 unsigned OddParts = NumParts - RoundParts;
424 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
425 DAG.getIntPtrConstant(RoundBits));
Bill Wendling5def8912012-09-26 06:16:18 +0000426 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000427
428 if (TLI.isBigEndian())
429 // The odd parts were reversed by getCopyToParts - unreverse them.
430 std::reverse(Parts + RoundParts, Parts + NumParts);
431
432 NumParts = RoundParts;
433 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
434 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
435 }
436
437 // The number of parts is a power of 2. Repeatedly bisect the value using
438 // EXTRACT_ELEMENT.
Wesley Peck527da1b2010-11-23 03:31:01 +0000439 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
Chris Lattner96a77eb2010-08-24 23:10:06 +0000440 EVT::getIntegerVT(*DAG.getContext(),
441 ValueVT.getSizeInBits()),
442 Val);
443
444 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
445 for (unsigned i = 0; i < NumParts; i += StepSize) {
446 unsigned ThisBits = StepSize * PartBits / 2;
447 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
448 SDValue &Part0 = Parts[i];
449 SDValue &Part1 = Parts[i+StepSize/2];
450
451 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
452 ThisVT, Part0, DAG.getIntPtrConstant(1));
453 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
454 ThisVT, Part0, DAG.getIntPtrConstant(0));
455
456 if (ThisBits == PartBits && ThisVT != PartVT) {
Wesley Peck527da1b2010-11-23 03:31:01 +0000457 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
458 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000459 }
460 }
461 }
462
463 if (TLI.isBigEndian())
464 std::reverse(Parts, Parts + OrigNumParts);
465}
466
467
468/// getCopyToPartsVector - Create a series of nodes that contain the specified
469/// value split into legal parts.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000470static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner96a77eb2010-08-24 23:10:06 +0000471 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000472 MVT PartVT, const Value *V) {
Chris Lattner96a77eb2010-08-24 23:10:06 +0000473 EVT ValueVT = Val.getValueType();
474 assert(ValueVT.isVector() && "Not a vector");
475 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000476
Chris Lattner96a77eb2010-08-24 23:10:06 +0000477 if (NumParts == 1) {
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000478 EVT PartEVT = PartVT;
479 if (PartEVT == ValueVT) {
Chris Lattner75ff0532010-08-25 22:49:25 +0000480 // Nothing to do.
481 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
482 // Bitconvert vector->vector case.
Wesley Peck527da1b2010-11-23 03:31:01 +0000483 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner75ff0532010-08-25 22:49:25 +0000484 } else if (PartVT.isVector() &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000485 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
486 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
Chris Lattner75ff0532010-08-25 22:49:25 +0000487 EVT ElementVT = PartVT.getVectorElementType();
488 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
489 // undef elements.
490 SmallVector<SDValue, 16> Ops;
491 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
492 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellardd42c5942013-08-05 22:22:01 +0000493 ElementVT, Val, DAG.getConstant(i,
494 TLI.getVectorIdxTy())));
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000495
Chris Lattner75ff0532010-08-25 22:49:25 +0000496 for (unsigned i = ValueVT.getVectorNumElements(),
497 e = PartVT.getVectorNumElements(); i != e; ++i)
498 Ops.push_back(DAG.getUNDEF(ElementVT));
499
Craig Topper48d114b2014-04-26 18:35:24 +0000500 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
Chris Lattner75ff0532010-08-25 22:49:25 +0000501
502 // FIXME: Use CONCAT for 2x -> 4x.
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000503
Chris Lattner75ff0532010-08-25 22:49:25 +0000504 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
505 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000506 } else if (PartVT.isVector() &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000507 PartEVT.getVectorElementType().bitsGE(
Nadav Rotem083837e2011-06-12 14:49:38 +0000508 ValueVT.getVectorElementType()) &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000509 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000510
511 // Promoted vector extract
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000512 bool Smaller = PartEVT.bitsLE(ValueVT);
Nadav Rotem36896bf2011-06-19 08:49:38 +0000513 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
514 DL, PartVT, Val);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000515 } else{
Chris Lattner75ff0532010-08-25 22:49:25 +0000516 // Vector -> scalar conversion.
Nadav Rotem083837e2011-06-12 14:49:38 +0000517 assert(ValueVT.getVectorNumElements() == 1 &&
Chris Lattner75ff0532010-08-25 22:49:25 +0000518 "Only trivial vector-to-scalar conversions should get here!");
519 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellardd42c5942013-08-05 22:22:01 +0000520 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
Nadav Rotem083837e2011-06-12 14:49:38 +0000521
522 bool Smaller = ValueVT.bitsLE(PartVT);
523 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
524 DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000525 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000526
Chris Lattner96a77eb2010-08-24 23:10:06 +0000527 Parts[0] = Val;
528 return;
529 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000530
Dan Gohman575fad32008-09-03 16:12:24 +0000531 // Handle a multi-element vector.
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000532 EVT IntermediateVT;
533 MVT RegisterVT;
Dan Gohman575fad32008-09-03 16:12:24 +0000534 unsigned NumIntermediates;
Owen Anderson117c9e82009-08-12 00:36:31 +0000535 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
Devang Patel977057f2010-08-26 20:32:32 +0000536 IntermediateVT,
537 NumIntermediates, RegisterVT);
Dan Gohman575fad32008-09-03 16:12:24 +0000538 unsigned NumElements = ValueVT.getVectorNumElements();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000539
Dan Gohman575fad32008-09-03 16:12:24 +0000540 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
541 NumParts = NumRegs; // Silence a compiler warning.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000542 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000543
Dan Gohman575fad32008-09-03 16:12:24 +0000544 // Split the vector into intermediate operands.
545 SmallVector<SDValue, 8> Ops(NumIntermediates);
Bill Wendling919b7aa2009-12-22 02:10:19 +0000546 for (unsigned i = 0; i != NumIntermediates; ++i) {
Dan Gohman575fad32008-09-03 16:12:24 +0000547 if (IntermediateVT.isVector())
Chris Lattner96a77eb2010-08-24 23:10:06 +0000548 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
Dan Gohman575fad32008-09-03 16:12:24 +0000549 IntermediateVT, Val,
Tom Stellardd42c5942013-08-05 22:22:01 +0000550 DAG.getConstant(i * (NumElements / NumIntermediates),
551 TLI.getVectorIdxTy()));
Dan Gohman575fad32008-09-03 16:12:24 +0000552 else
Chris Lattner96a77eb2010-08-24 23:10:06 +0000553 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellardd42c5942013-08-05 22:22:01 +0000554 IntermediateVT, Val,
555 DAG.getConstant(i, TLI.getVectorIdxTy()));
Bill Wendling919b7aa2009-12-22 02:10:19 +0000556 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000557
Dan Gohman575fad32008-09-03 16:12:24 +0000558 // Split the intermediate operands into legal parts.
559 if (NumParts == NumIntermediates) {
560 // If the register was not expanded, promote or copy the value,
561 // as appropriate.
562 for (unsigned i = 0; i != NumParts; ++i)
Bill Wendling5def8912012-09-26 06:16:18 +0000563 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000564 } else if (NumParts > 0) {
565 // If the intermediate type was expanded, split each the value into
566 // legal parts.
567 assert(NumParts % NumIntermediates == 0 &&
568 "Must expand into a divisible number of parts!");
569 unsigned Factor = NumParts / NumIntermediates;
570 for (unsigned i = 0; i != NumIntermediates; ++i)
Bill Wendling5def8912012-09-26 06:16:18 +0000571 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000572 }
573}
574
Dan Gohman4db93c92010-05-29 17:53:24 +0000575namespace {
576 /// RegsForValue - This struct represents the registers (physical or virtual)
577 /// that a particular set of values is assigned, and the type information
578 /// about the value. The most common situation is to represent one value at a
579 /// time, but struct or array values are handled element-wise as multiple
580 /// values. The splitting of aggregates is performed recursively, so that we
581 /// never have aggregate-typed registers. The values at this point do not
582 /// necessarily have legal types, so each value may require one or more
583 /// registers of some legal type.
584 ///
585 struct RegsForValue {
586 /// ValueVTs - The value types of the values, which may not be legal, and
587 /// may need be promoted or synthesized from one or more registers.
588 ///
589 SmallVector<EVT, 4> ValueVTs;
590
591 /// RegVTs - The value types of the registers. This is the same size as
592 /// ValueVTs and it records, for each value, what the type of the assigned
593 /// register or registers are. (Individual values are never synthesized
594 /// from more than one type of register.)
595 ///
596 /// With virtual registers, the contents of RegVTs is redundant with TLI's
597 /// getRegisterType member function, however when with physical registers
598 /// it is necessary to have a separate record of the types.
599 ///
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000600 SmallVector<MVT, 4> RegVTs;
Dan Gohman4db93c92010-05-29 17:53:24 +0000601
602 /// Regs - This list holds the registers assigned to the values.
603 /// Each legal or promoted value requires one register, and each
604 /// expanded value requires multiple registers.
605 ///
606 SmallVector<unsigned, 4> Regs;
607
608 RegsForValue() {}
609
610 RegsForValue(const SmallVector<unsigned, 4> &regs,
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000611 MVT regvt, EVT valuevt)
Dan Gohman4db93c92010-05-29 17:53:24 +0000612 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
613
Dan Gohman4db93c92010-05-29 17:53:24 +0000614 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
Chris Lattner229907c2011-07-18 04:54:35 +0000615 unsigned Reg, Type *Ty) {
Dan Gohman4db93c92010-05-29 17:53:24 +0000616 ComputeValueVTs(tli, Ty, ValueVTs);
617
618 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
619 EVT ValueVT = ValueVTs[Value];
620 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
Patrik Hagglundbad545c2012-12-19 11:48:16 +0000621 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
Dan Gohman4db93c92010-05-29 17:53:24 +0000622 for (unsigned i = 0; i != NumRegs; ++i)
623 Regs.push_back(Reg + i);
624 RegVTs.push_back(RegisterVT);
625 Reg += NumRegs;
626 }
627 }
628
Dan Gohman4db93c92010-05-29 17:53:24 +0000629 /// append - Add the specified values to this one.
630 void append(const RegsForValue &RHS) {
631 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
632 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
633 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
634 }
635
636 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
637 /// this value and returns the result as a ValueVTs value. This uses
638 /// Chain/Flag as the input and updates them for the output Chain/Flag.
639 /// If the Flag pointer is NULL, no flag is used.
640 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000641 SDLoc dl,
Bill Wendling81406f62012-09-26 04:04:19 +0000642 SDValue &Chain, SDValue *Flag,
Craig Topperc0196b12014-04-14 00:51:57 +0000643 const Value *V = nullptr) const;
Dan Gohman4db93c92010-05-29 17:53:24 +0000644
645 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
646 /// specified value into the registers specified by this object. This uses
647 /// Chain/Flag as the input and updates them for the output Chain/Flag.
648 /// If the Flag pointer is NULL, no flag is used.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000649 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
Bill Wendling5def8912012-09-26 06:16:18 +0000650 SDValue &Chain, SDValue *Flag, const Value *V) const;
Dan Gohman4db93c92010-05-29 17:53:24 +0000651
652 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
653 /// operand list. This adds the code marker, matching input operand index
654 /// (if applicable), and includes the number of values added into it.
655 void AddInlineAsmOperands(unsigned Kind,
656 bool HasMatching, unsigned MatchingIdx,
657 SelectionDAG &DAG,
658 std::vector<SDValue> &Ops) const;
659 };
660}
661
662/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
663/// this value and returns the result as a ValueVT value. This uses
664/// Chain/Flag as the input and updates them for the output Chain/Flag.
665/// If the Flag pointer is NULL, no flag is used.
666SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
667 FunctionLoweringInfo &FuncInfo,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000668 SDLoc dl,
Bill Wendling81406f62012-09-26 04:04:19 +0000669 SDValue &Chain, SDValue *Flag,
670 const Value *V) const {
Dan Gohman2810bac2010-07-26 18:15:41 +0000671 // A Value with type {} or [0 x %t] needs no registers.
672 if (ValueVTs.empty())
673 return SDValue();
674
Dan Gohman4db93c92010-05-29 17:53:24 +0000675 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
676
677 // Assemble the legal parts into the final values.
678 SmallVector<SDValue, 4> Values(ValueVTs.size());
679 SmallVector<SDValue, 8> Parts;
680 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
681 // Copy the legal parts from the registers.
682 EVT ValueVT = ValueVTs[Value];
683 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000684 MVT RegisterVT = RegVTs[Value];
Dan Gohman4db93c92010-05-29 17:53:24 +0000685
686 Parts.resize(NumRegs);
687 for (unsigned i = 0; i != NumRegs; ++i) {
688 SDValue P;
Craig Topperc0196b12014-04-14 00:51:57 +0000689 if (!Flag) {
Dan Gohman4db93c92010-05-29 17:53:24 +0000690 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
691 } else {
692 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
693 *Flag = P.getValue(2);
694 }
695
696 Chain = P.getValue(1);
Chris Lattnercb404362010-12-13 01:11:17 +0000697 Parts[i] = P;
Dan Gohman4db93c92010-05-29 17:53:24 +0000698
699 // If the source register was virtual and if we know something about it,
700 // add an assert node.
Chris Lattnercb404362010-12-13 01:11:17 +0000701 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
Cameron Zwarich64706472011-02-24 10:00:08 +0000702 !RegisterVT.isInteger() || RegisterVT.isVector())
Chris Lattnercb404362010-12-13 01:11:17 +0000703 continue;
Cameron Zwarich64706472011-02-24 10:00:08 +0000704
705 const FunctionLoweringInfo::LiveOutInfo *LOI =
706 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
707 if (!LOI)
708 continue;
Dan Gohman4db93c92010-05-29 17:53:24 +0000709
Chris Lattnercb404362010-12-13 01:11:17 +0000710 unsigned RegSize = RegisterVT.getSizeInBits();
Cameron Zwarich64706472011-02-24 10:00:08 +0000711 unsigned NumSignBits = LOI->NumSignBits;
712 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
Dan Gohman4db93c92010-05-29 17:53:24 +0000713
Quentin Colombetb51a6862013-06-18 20:14:39 +0000714 if (NumZeroBits == RegSize) {
715 // The current value is a zero.
716 // Explicitly express that as it would be easier for
717 // optimizations to kick in.
718 Parts[i] = DAG.getConstant(0, RegisterVT);
719 continue;
720 }
721
Chris Lattnercb404362010-12-13 01:11:17 +0000722 // FIXME: We capture more information than the dag can represent. For
723 // now, just use the tightest assertzext/assertsext possible.
724 bool isSExt = true;
725 EVT FromVT(MVT::Other);
726 if (NumSignBits == RegSize)
727 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
728 else if (NumZeroBits >= RegSize-1)
729 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
730 else if (NumSignBits > RegSize-8)
731 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
732 else if (NumZeroBits >= RegSize-8)
733 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
734 else if (NumSignBits > RegSize-16)
735 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
736 else if (NumZeroBits >= RegSize-16)
737 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
738 else if (NumSignBits > RegSize-32)
739 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
740 else if (NumZeroBits >= RegSize-32)
741 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
742 else
743 continue;
Dan Gohman4db93c92010-05-29 17:53:24 +0000744
Chris Lattnercb404362010-12-13 01:11:17 +0000745 // Add an assertion node.
746 assert(FromVT != MVT::Other);
747 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
748 RegisterVT, P, DAG.getValueType(FromVT));
Dan Gohman4db93c92010-05-29 17:53:24 +0000749 }
750
751 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Bill Wendling81406f62012-09-26 04:04:19 +0000752 NumRegs, RegisterVT, ValueVT, V);
Dan Gohman4db93c92010-05-29 17:53:24 +0000753 Part += NumRegs;
754 Parts.clear();
755 }
756
Craig Topper48d114b2014-04-26 18:35:24 +0000757 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
Dan Gohman4db93c92010-05-29 17:53:24 +0000758}
759
760/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
761/// specified value into the registers specified by this object. This uses
762/// Chain/Flag as the input and updates them for the output Chain/Flag.
763/// If the Flag pointer is NULL, no flag is used.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000764void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
Bill Wendling5def8912012-09-26 06:16:18 +0000765 SDValue &Chain, SDValue *Flag,
766 const Value *V) const {
Dan Gohman4db93c92010-05-29 17:53:24 +0000767 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
768
769 // Get the list of the values's legal parts.
770 unsigned NumRegs = Regs.size();
771 SmallVector<SDValue, 8> Parts(NumRegs);
772 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
773 EVT ValueVT = ValueVTs[Value];
774 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000775 MVT RegisterVT = RegVTs[Value];
Evan Cheng9ec512d2012-12-06 19:13:27 +0000776 ISD::NodeType ExtendKind =
777 TLI.isZExtFree(Val, RegisterVT)? ISD::ZERO_EXTEND: ISD::ANY_EXTEND;
Dan Gohman4db93c92010-05-29 17:53:24 +0000778
Chris Lattner05bcb482010-08-24 23:20:40 +0000779 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Evan Cheng9ec512d2012-12-06 19:13:27 +0000780 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
Dan Gohman4db93c92010-05-29 17:53:24 +0000781 Part += NumParts;
782 }
783
784 // Copy the parts into the registers.
785 SmallVector<SDValue, 8> Chains(NumRegs);
786 for (unsigned i = 0; i != NumRegs; ++i) {
787 SDValue Part;
Craig Topperc0196b12014-04-14 00:51:57 +0000788 if (!Flag) {
Dan Gohman4db93c92010-05-29 17:53:24 +0000789 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
790 } else {
791 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
792 *Flag = Part.getValue(1);
793 }
794
795 Chains[i] = Part.getValue(0);
796 }
797
798 if (NumRegs == 1 || Flag)
799 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
800 // flagged to it. That is the CopyToReg nodes and the user are considered
801 // a single scheduling unit. If we create a TokenFactor and return it as
802 // chain, then the TokenFactor is both a predecessor (operand) of the
803 // user as well as a successor (the TF operands are flagged to the user).
804 // c1, f1 = CopyToReg
805 // c2, f2 = CopyToReg
806 // c3 = TokenFactor c1, c2
807 // ...
808 // = op c3, ..., f2
809 Chain = Chains[NumRegs-1];
810 else
Craig Topper48d114b2014-04-26 18:35:24 +0000811 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
Dan Gohman4db93c92010-05-29 17:53:24 +0000812}
813
814/// AddInlineAsmOperands - Add this value to the specified inlineasm node
815/// operand list. This adds the code marker and includes the number of
816/// values added into it.
817void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
818 unsigned MatchingIdx,
819 SelectionDAG &DAG,
820 std::vector<SDValue> &Ops) const {
821 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
822
823 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
824 if (HasMatching)
825 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
Jakob Stoklund Olesen24abd9d2011-10-12 23:37:29 +0000826 else if (!Regs.empty() &&
827 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
828 // Put the register class of the virtual registers in the flag word. That
829 // way, later passes can recompute register class constraints for inline
830 // assembly as well as normal instructions.
831 // Don't do this for tied operands that can use the regclass information
832 // from the def.
833 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
834 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
835 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
836 }
837
Dan Gohman4db93c92010-05-29 17:53:24 +0000838 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
839 Ops.push_back(Res);
840
Reid Kleckneree088972013-12-10 18:27:32 +0000841 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
Dan Gohman4db93c92010-05-29 17:53:24 +0000842 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
843 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000844 MVT RegisterVT = RegVTs[Value];
Dan Gohman4db93c92010-05-29 17:53:24 +0000845 for (unsigned i = 0; i != NumRegs; ++i) {
846 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Reid Kleckneree088972013-12-10 18:27:32 +0000847 unsigned TheReg = Regs[Reg++];
848 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
849
Reid Kleckneree088972013-12-10 18:27:32 +0000850 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000851 // If we clobbered the stack pointer, MFI should know about it.
852 assert(DAG.getMachineFunction().getFrameInfo()->
853 hasInlineAsmWithSPAdjust());
Reid Kleckneree088972013-12-10 18:27:32 +0000854 }
Dan Gohman4db93c92010-05-29 17:53:24 +0000855 }
856 }
857}
Dan Gohman575fad32008-09-03 16:12:24 +0000858
Owen Andersonbb15fec2011-12-08 22:15:21 +0000859void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
860 const TargetLibraryInfo *li) {
Dan Gohman575fad32008-09-03 16:12:24 +0000861 AA = &aa;
862 GFI = gfi;
Owen Andersonbb15fec2011-12-08 22:15:21 +0000863 LibInfo = li;
Eric Christopherfc6de422014-08-05 02:39:49 +0000864 DL = DAG.getSubtarget().getDataLayout();
Richard Smith3fb20472012-08-22 00:42:39 +0000865 Context = DAG.getContext();
Bill Wendling2730a002011-10-15 01:00:26 +0000866 LPadToCallSiteMap.clear();
Dan Gohman575fad32008-09-03 16:12:24 +0000867}
868
Dan Gohmanf5cca352010-04-14 18:24:06 +0000869/// clear - Clear out the current SelectionDAG and the associated
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000870/// state and prepare this SelectionDAGBuilder object to be used
Dan Gohman575fad32008-09-03 16:12:24 +0000871/// for a new block. This doesn't clear out information about
872/// additional blocks that are needed to complete switch lowering
873/// or PHI node updating; that information is cleared out as it is
874/// consumed.
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000875void SelectionDAGBuilder::clear() {
Dan Gohman575fad32008-09-03 16:12:24 +0000876 NodeMap.clear();
Devang Patelb0c76392010-06-01 19:59:01 +0000877 UnusedArgNodeMap.clear();
Dan Gohman575fad32008-09-03 16:12:24 +0000878 PendingLoads.clear();
879 PendingExports.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000880 CurInst = nullptr;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +0000881 HasTailCall = false;
Nico Rieckb5262d62014-01-12 14:09:17 +0000882 SDNodeOrder = LowestSDNodeOrder;
Dan Gohman575fad32008-09-03 16:12:24 +0000883}
884
Devang Patel799288382011-05-23 17:44:13 +0000885/// clearDanglingDebugInfo - Clear the dangling debug information
Benjamin Kramerbde91762012-06-02 10:20:22 +0000886/// map. This function is separated from the clear so that debug
Devang Patel799288382011-05-23 17:44:13 +0000887/// information that is dangling in a basic block can be properly
888/// resolved in a different basic block. This allows the
889/// SelectionDAG to resolve dangling debug information attached
890/// to PHI nodes.
891void SelectionDAGBuilder::clearDanglingDebugInfo() {
892 DanglingDebugInfoMap.clear();
893}
894
Dan Gohman575fad32008-09-03 16:12:24 +0000895/// getRoot - Return the current virtual root of the Selection DAG,
896/// flushing any PendingLoad items. This must be done before emitting
897/// a store or any other node that may need to be ordered after any
898/// prior load instructions.
899///
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000900SDValue SelectionDAGBuilder::getRoot() {
Dan Gohman575fad32008-09-03 16:12:24 +0000901 if (PendingLoads.empty())
902 return DAG.getRoot();
903
904 if (PendingLoads.size() == 1) {
905 SDValue Root = PendingLoads[0];
906 DAG.setRoot(Root);
907 PendingLoads.clear();
908 return Root;
909 }
910
911 // Otherwise, we have to make a token factor node.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000912 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +0000913 PendingLoads);
Dan Gohman575fad32008-09-03 16:12:24 +0000914 PendingLoads.clear();
915 DAG.setRoot(Root);
916 return Root;
917}
918
919/// getControlRoot - Similar to getRoot, but instead of flushing all the
920/// PendingLoad items, flush all the PendingExports items. It is necessary
921/// to do this before emitting a terminator instruction.
922///
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000923SDValue SelectionDAGBuilder::getControlRoot() {
Dan Gohman575fad32008-09-03 16:12:24 +0000924 SDValue Root = DAG.getRoot();
925
926 if (PendingExports.empty())
927 return Root;
928
929 // Turn all of the CopyToReg chains into one factored node.
930 if (Root.getOpcode() != ISD::EntryToken) {
931 unsigned i = 0, e = PendingExports.size();
932 for (; i != e; ++i) {
933 assert(PendingExports[i].getNode()->getNumOperands() > 1);
934 if (PendingExports[i].getNode()->getOperand(0) == Root)
935 break; // Don't add the root if we already indirectly depend on it.
936 }
937
938 if (i == e)
939 PendingExports.push_back(Root);
940 }
941
Andrew Trickef9de2a2013-05-25 02:42:55 +0000942 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +0000943 PendingExports);
Dan Gohman575fad32008-09-03 16:12:24 +0000944 PendingExports.clear();
945 DAG.setRoot(Root);
946 return Root;
947}
948
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000949void SelectionDAGBuilder::visit(const Instruction &I) {
Dan Gohman5b43aa02010-04-22 20:55:53 +0000950 // Set up outgoing PHI node register values before emitting the terminator.
951 if (isa<TerminatorInst>(&I))
952 HandlePHINodesInSuccessorBlocks(I.getParent());
953
Andrew Tricke2431c62013-05-25 03:08:10 +0000954 ++SDNodeOrder;
955
Andrew Trick175143b2013-05-25 02:20:36 +0000956 CurInst = &I;
Dan Gohmane450d742010-04-20 00:48:35 +0000957
Dan Gohman575fad32008-09-03 16:12:24 +0000958 visit(I.getOpcode(), I);
Dan Gohmane450d742010-04-20 00:48:35 +0000959
Dan Gohman950fe782010-04-20 15:03:56 +0000960 if (!isa<TerminatorInst>(&I) && !HasTailCall)
961 CopyToExportRegsIfNeeded(&I);
962
Craig Topperc0196b12014-04-14 00:51:57 +0000963 CurInst = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +0000964}
965
Dan Gohmanf41ad472010-04-20 15:00:41 +0000966void SelectionDAGBuilder::visitPHI(const PHINode &) {
967 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
968}
969
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000970void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +0000971 // Note: this doesn't use InstVisitor, because it has to work with
972 // ConstantExpr's in addition to instructions.
973 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000974 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohman575fad32008-09-03 16:12:24 +0000975 // Build the switch statement using the Instruction.def file.
976#define HANDLE_INST(NUM, OPCODE, CLASS) \
Galina Kistanovaaaf97352012-07-19 04:50:12 +0000977 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000978#include "llvm/IR/Instruction.def"
Dan Gohman575fad32008-09-03 16:12:24 +0000979 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +0000980}
Dan Gohman575fad32008-09-03 16:12:24 +0000981
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000982// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
983// generate the debug data structures now that we've seen its definition.
984void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
985 SDValue Val) {
986 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
Devang Patelb12ff592010-08-26 23:35:15 +0000987 if (DDI.getDI()) {
988 const DbgValueInst *DI = DDI.getDI();
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000989 DebugLoc dl = DDI.getdl();
990 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
Devang Patelb12ff592010-08-26 23:35:15 +0000991 MDNode *Variable = DI->getVariable();
992 uint64_t Offset = DI->getOffset();
Adrian Prantl32da8892014-04-25 20:49:25 +0000993 // A dbg.value for an alloca is always indirect.
994 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000995 SDDbgValue *SDV;
996 if (Val.getNode()) {
Adrian Prantl32da8892014-04-25 20:49:25 +0000997 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, IsIndirect, Val)) {
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000998 SDV = DAG.getDbgValue(Variable, Val.getNode(),
Adrian Prantl32da8892014-04-25 20:49:25 +0000999 Val.getResNo(), IsIndirect,
1000 Offset, dl, DbgSDNodeOrder);
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001001 DAG.AddDbgValue(SDV, Val.getNode(), false);
1002 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00001003 } else
Adrian Prantl0d1e5592013-05-22 18:02:19 +00001004 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001005 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1006 }
1007}
1008
Nick Lewyckyf40df1d2011-09-30 22:19:53 +00001009/// getValue - Return an SDValue for the given Value.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001010SDValue SelectionDAGBuilder::getValue(const Value *V) {
Dan Gohmand4322232010-07-01 01:59:43 +00001011 // If we already have an SDValue for this value, use it. It's important
1012 // to do this first, so that we don't create a CopyFromReg if we already
1013 // have a regular SDValue.
Dan Gohman575fad32008-09-03 16:12:24 +00001014 SDValue &N = NodeMap[V];
1015 if (N.getNode()) return N;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001016
Dan Gohmand4322232010-07-01 01:59:43 +00001017 // If there's a virtual register allocated and initialized for this
1018 // value, use it.
1019 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1020 if (It != FuncInfo.ValueMap.end()) {
1021 unsigned InReg = It->second;
Eric Christopherd9134482014-08-04 21:25:23 +00001022 RegsForValue RFV(*DAG.getContext(),
1023 *TM.getSubtargetImpl()->getTargetLowering(), InReg,
1024 V->getType());
Dan Gohmand4322232010-07-01 01:59:43 +00001025 SDValue Chain = DAG.getEntryNode();
Craig Topperc0196b12014-04-14 00:51:57 +00001026 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 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) {
Eric Christopherd9134482014-08-04 21:25:23 +00001055 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001056
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
Craig Topper64941d92014-04-27 19:20:57 +00001097 return DAG.getMergeValues(Constants, getCurSDLoc());
Dan Gohman575fad32008-09-03 16:12:24 +00001098 }
Stephen Lincfe7f352013-07-08 00:37:03 +00001099
Chris Lattner00245f42012-01-24 13:41:11 +00001100 if (const ConstantDataSequential *CDS =
1101 dyn_cast<ConstantDataSequential>(C)) {
1102 SmallVector<SDValue, 4> Ops;
Chris Lattner9be59592012-01-25 01:27:20 +00001103 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +00001104 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1105 // Add each leaf value from the operand to the Constants list
1106 // to form a flattened list of all the values.
1107 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1108 Ops.push_back(SDValue(Val, i));
1109 }
1110
1111 if (isa<ArrayType>(CDS->getType()))
Craig Topper64941d92014-04-27 19:20:57 +00001112 return DAG.getMergeValues(Ops, getCurSDLoc());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001113 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00001114 VT, Ops);
Chris Lattner00245f42012-01-24 13:41:11 +00001115 }
Dan Gohman575fad32008-09-03 16:12:24 +00001116
Duncan Sands19d0b472010-02-16 11:11:14 +00001117 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
Dan Gohman575fad32008-09-03 16:12:24 +00001118 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1119 "Unknown struct or array constant!");
1120
Owen Anderson53aa7a92009-08-10 22:56:29 +00001121 SmallVector<EVT, 4> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001122 ComputeValueVTs(*TLI, C->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00001123 unsigned NumElts = ValueVTs.size();
1124 if (NumElts == 0)
1125 return SDValue(); // empty struct
1126 SmallVector<SDValue, 4> Constants(NumElts);
1127 for (unsigned i = 0; i != NumElts; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001128 EVT EltVT = ValueVTs[i];
Dan Gohman575fad32008-09-03 16:12:24 +00001129 if (isa<UndefValue>(C))
Dale Johannesen84935752009-02-06 23:05:02 +00001130 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohman575fad32008-09-03 16:12:24 +00001131 else if (EltVT.isFloatingPoint())
1132 Constants[i] = DAG.getConstantFP(0, EltVT);
1133 else
1134 Constants[i] = DAG.getConstant(0, EltVT);
1135 }
Bill Wendlingc6b47342009-12-21 23:47:40 +00001136
Craig Topper64941d92014-04-27 19:20:57 +00001137 return DAG.getMergeValues(Constants, getCurSDLoc());
Dan Gohman575fad32008-09-03 16:12:24 +00001138 }
1139
Dan Gohman8422e572010-04-17 15:32:28 +00001140 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
Dan Gohman7a6611792009-11-20 23:18:13 +00001141 return DAG.getBlockAddress(BA, VT);
Dan Gohman6c938802009-10-30 01:27:03 +00001142
Chris Lattner229907c2011-07-18 04:54:35 +00001143 VectorType *VecTy = cast<VectorType>(V->getType());
Dan Gohman575fad32008-09-03 16:12:24 +00001144 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001145
Dan Gohman575fad32008-09-03 16:12:24 +00001146 // Now that we know the number and type of the elements, get that number of
1147 // elements into the Ops array based on what kind of constant it is.
1148 SmallVector<SDValue, 16> Ops;
Chris Lattner00245f42012-01-24 13:41:11 +00001149 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
Dan Gohman575fad32008-09-03 16:12:24 +00001150 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner00245f42012-01-24 13:41:11 +00001151 Ops.push_back(getValue(CV->getOperand(i)));
Dan Gohman575fad32008-09-03 16:12:24 +00001152 } else {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00001153 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001154 EVT EltVT = TLI->getValueType(VecTy->getElementType());
Dan Gohman575fad32008-09-03 16:12:24 +00001155
1156 SDValue Op;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00001157 if (EltVT.isFloatingPoint())
Dan Gohman575fad32008-09-03 16:12:24 +00001158 Op = DAG.getConstantFP(0, EltVT);
1159 else
1160 Op = DAG.getConstant(0, EltVT);
1161 Ops.assign(NumElements, Op);
1162 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001163
Dan Gohman575fad32008-09-03 16:12:24 +00001164 // Create a BUILD_VECTOR node.
Craig Topper48d114b2014-04-26 18:35:24 +00001165 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
Dan Gohman575fad32008-09-03 16:12:24 +00001166 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001167
Dan Gohman575fad32008-09-03 16:12:24 +00001168 // If this is a static alloca, generate it as the frameindex instead of
1169 // computation.
1170 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1171 DenseMap<const AllocaInst*, int>::iterator SI =
1172 FuncInfo.StaticAllocaMap.find(AI);
1173 if (SI != FuncInfo.StaticAllocaMap.end())
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001174 return DAG.getFrameIndex(SI->second, TLI->getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00001175 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001176
Dan Gohmand4322232010-07-01 01:59:43 +00001177 // If this is an instruction which fast-isel has deferred, select it now.
1178 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001179 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001180 RegsForValue RFV(*DAG.getContext(), *TLI, InReg, Inst->getType());
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001181 SDValue Chain = DAG.getEntryNode();
Craig Topperc0196b12014-04-14 00:51:57 +00001182 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
Dan Gohmand4322232010-07-01 01:59:43 +00001183 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001184
Dan Gohmand4322232010-07-01 01:59:43 +00001185 llvm_unreachable("Can't get register for value!");
Dan Gohman575fad32008-09-03 16:12:24 +00001186}
1187
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001188void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
Eric Christopherd9134482014-08-04 21:25:23 +00001189 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001190 SDValue Chain = getControlRoot();
1191 SmallVector<ISD::OutputArg, 8> Outs;
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001192 SmallVector<SDValue, 8> OutVals;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00001193
Dan Gohmand16aa542010-05-29 17:03:36 +00001194 if (!FuncInfo.CanLowerReturn) {
1195 unsigned DemoteReg = FuncInfo.DemoteRegister;
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001196 const Function *F = I.getParent()->getParent();
1197
1198 // Emit a store of the return value through the virtual register.
1199 // Leave Outs empty so that LowerReturn won't try to load return
1200 // registers the usual way.
1201 SmallVector<EVT, 1> PtrValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001202 ComputeValueVTs(*TLI, PointerType::getUnqual(F->getReturnType()),
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001203 PtrValueVTs);
1204
1205 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1206 SDValue RetOp = getValue(I.getOperand(0));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00001207
Owen Anderson53aa7a92009-08-10 22:56:29 +00001208 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001209 SmallVector<uint64_t, 4> Offsets;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001210 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman8b44b882008-10-21 20:00:42 +00001211 unsigned NumValues = ValueVTs.size();
Dan Gohman8b44b882008-10-21 20:00:42 +00001212
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001213 SmallVector<SDValue, 4> Chains(NumValues);
Bill Wendlingc6b47342009-12-21 23:47:40 +00001214 for (unsigned i = 0; i != NumValues; ++i) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001215 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
Chris Lattner96a77eb2010-08-24 23:10:06 +00001216 RetPtr.getValueType(), RetPtr,
1217 DAG.getIntPtrConstant(Offsets[i]));
Bill Wendlingc6b47342009-12-21 23:47:40 +00001218 Chains[i] =
Andrew Trickef9de2a2013-05-25 02:42:55 +00001219 DAG.getStore(Chain, getCurSDLoc(),
Bill Wendlingc6b47342009-12-21 23:47:40 +00001220 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
Chris Lattnera4f19972010-09-21 18:58:22 +00001221 // FIXME: better loc info would be nice.
1222 Add, MachinePointerInfo(), false, false, 0);
Bill Wendlingc6b47342009-12-21 23:47:40 +00001223 }
1224
Andrew Trickef9de2a2013-05-25 02:42:55 +00001225 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00001226 MVT::Other, Chains);
Chris Lattnerb1af8652010-02-28 18:53:13 +00001227 } else if (I.getNumOperands() != 0) {
1228 SmallVector<EVT, 4> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001229 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs);
Chris Lattnerb1af8652010-02-28 18:53:13 +00001230 unsigned NumValues = ValueVTs.size();
1231 if (NumValues) {
1232 SDValue RetOp = getValue(I.getOperand(0));
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001233 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1234 EVT VT = ValueVTs[j];
Dan Gohman575fad32008-09-03 16:12:24 +00001235
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001236 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001237
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001238 const Function *F = I.getParent()->getParent();
Bill Wendling74dba872012-12-30 13:01:51 +00001239 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1240 Attribute::SExt))
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001241 ExtendKind = ISD::SIGN_EXTEND;
Bill Wendling74dba872012-12-30 13:01:51 +00001242 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1243 Attribute::ZExt))
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001244 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohman575fad32008-09-03 16:12:24 +00001245
Cameron Zwarich2ef0c692011-03-17 14:53:37 +00001246 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001247 VT = TLI->getTypeForExtArgOrReturn(VT.getSimpleVT(), ExtendKind);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001248
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001249 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), VT);
1250 MVT PartVT = TLI->getRegisterType(*DAG.getContext(), VT);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001251 SmallVector<SDValue, 4> Parts(NumParts);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001252 getCopyToParts(DAG, getCurSDLoc(),
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001253 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Bill Wendling5def8912012-09-26 06:16:18 +00001254 &Parts[0], NumParts, PartVT, &I, ExtendKind);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001255
1256 // 'inreg' on function refers to return value
1257 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Bill Wendling74dba872012-12-30 13:01:51 +00001258 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1259 Attribute::InReg))
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001260 Flags.setInReg();
1261
1262 // Propagate extension type if any
Cameron Zwarichd1ad9bc2011-03-16 22:20:07 +00001263 if (ExtendKind == ISD::SIGN_EXTEND)
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001264 Flags.setSExt();
Cameron Zwarichd1ad9bc2011-03-16 22:20:07 +00001265 else if (ExtendKind == ISD::ZERO_EXTEND)
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001266 Flags.setZExt();
1267
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001268 for (unsigned i = 0; i < NumParts; ++i) {
1269 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
Tom Stellard8d7d4de2013-10-23 00:44:24 +00001270 VT, /*isfixed=*/true, 0, 0));
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001271 OutVals.push_back(Parts[i]);
1272 }
Evan Cheng2e9f42b2009-03-25 20:20:11 +00001273 }
Dan Gohman575fad32008-09-03 16:12:24 +00001274 }
1275 }
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001276
1277 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel68c5f472009-09-02 08:44:58 +00001278 CallingConv::ID CallConv =
1279 DAG.getMachineFunction().getFunction()->getCallingConv();
Eric Christopherd9134482014-08-04 21:25:23 +00001280 Chain = TM.getSubtargetImpl()->getTargetLowering()->LowerReturn(
1281 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
Dan Gohman695d8112009-08-06 15:37:27 +00001282
1283 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson9f944592009-08-11 20:47:22 +00001284 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00001285 "LowerReturn didn't return a valid chain!");
1286
1287 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001288 DAG.setRoot(Chain);
Dan Gohman575fad32008-09-03 16:12:24 +00001289}
1290
Dan Gohman9478c3f2009-04-23 23:13:24 +00001291/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1292/// created for it, emit nodes to copy the value into the virtual
1293/// registers.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001294void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
Rafael Espindolae53b7d12011-05-13 15:18:06 +00001295 // Skip empty types
1296 if (V->getType()->isEmptyTy())
1297 return;
1298
Dan Gohman3a7ee8e2010-04-16 17:15:02 +00001299 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1300 if (VMI != FuncInfo.ValueMap.end()) {
1301 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1302 CopyValueToVirtualRegister(V, VMI->second);
Dan Gohman9478c3f2009-04-23 23:13:24 +00001303 }
1304}
1305
Dan Gohman575fad32008-09-03 16:12:24 +00001306/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1307/// the current basic block, add it to ValueMap now so that we'll get a
1308/// CopyTo/FromReg.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001309void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
Dan Gohman575fad32008-09-03 16:12:24 +00001310 // No need to export constants.
1311 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001312
Dan Gohman575fad32008-09-03 16:12:24 +00001313 // Already exported?
1314 if (FuncInfo.isExportedInst(V)) return;
1315
1316 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1317 CopyValueToVirtualRegister(V, Reg);
1318}
1319
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001320bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001321 const BasicBlock *FromBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001322 // The operands of the setcc have to be in this block. We don't know
1323 // how to export them from some other block.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001324 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
Dan Gohman575fad32008-09-03 16:12:24 +00001325 // Can export from current BB.
1326 if (VI->getParent() == FromBB)
1327 return true;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001328
Dan Gohman575fad32008-09-03 16:12:24 +00001329 // Is already exported, noop.
1330 return FuncInfo.isExportedInst(V);
1331 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001332
Dan Gohman575fad32008-09-03 16:12:24 +00001333 // If this is an argument, we can export it if the BB is the entry block or
1334 // if it is already exported.
1335 if (isa<Argument>(V)) {
1336 if (FromBB == &FromBB->getParent()->getEntryBlock())
1337 return true;
1338
1339 // Otherwise, can only export this if it is already exported.
1340 return FuncInfo.isExportedInst(V);
1341 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001342
Dan Gohman575fad32008-09-03 16:12:24 +00001343 // Otherwise, constants can always be exported.
1344 return true;
1345}
1346
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001347/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
Jakub Staszak96f8c552011-12-20 20:03:10 +00001348uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1349 const MachineBasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001350 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1351 if (!BPI)
1352 return 0;
Jakub Staszak539db982011-07-29 20:05:36 +00001353 const BasicBlock *SrcBB = Src->getBasicBlock();
1354 const BasicBlock *DstBB = Dst->getBasicBlock();
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001355 return BPI->getEdgeWeight(SrcBB, DstBB);
1356}
1357
Jakub Staszak0480a8f2011-07-29 22:25:21 +00001358void SelectionDAGBuilder::
1359addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1360 uint32_t Weight /* = 0 */) {
1361 if (!Weight)
1362 Weight = getEdgeWeight(Src, Dst);
1363 Src->addSuccessor(Dst, Weight);
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001364}
1365
1366
Dan Gohman575fad32008-09-03 16:12:24 +00001367static bool InBlock(const Value *V, const BasicBlock *BB) {
1368 if (const Instruction *I = dyn_cast<Instruction>(V))
1369 return I->getParent() == BB;
1370 return true;
1371}
1372
Dan Gohmand01ddb52008-10-17 21:16:08 +00001373/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1374/// This function emits a branch and is used at the leaves of an OR or an
1375/// AND operator tree.
1376///
1377void
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001378SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001379 MachineBasicBlock *TBB,
1380 MachineBasicBlock *FBB,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001381 MachineBasicBlock *CurBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001382 MachineBasicBlock *SwitchBB,
1383 uint32_t TWeight,
1384 uint32_t FWeight) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001385 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohman575fad32008-09-03 16:12:24 +00001386
Dan Gohmand01ddb52008-10-17 21:16:08 +00001387 // If the leaf of the tree is a comparison, merge the condition into
1388 // the caseblock.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001389 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001390 // The operands of the cmp have to be in this block. We don't know
1391 // how to export them from some other block. If this is the first block
1392 // of the sequence, no exporting is needed.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001393 if (CurBB == SwitchBB ||
Dan Gohmand01ddb52008-10-17 21:16:08 +00001394 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1395 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohman575fad32008-09-03 16:12:24 +00001396 ISD::CondCode Condition;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001397 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman293abcc2008-10-17 18:18:45 +00001398 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001399 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman293abcc2008-10-17 18:18:45 +00001400 Condition = getFCmpCondCode(FC->getPredicate());
Nick Lewycky50f02cb2011-12-02 22:16:29 +00001401 if (TM.Options.NoNaNsFPMath)
1402 Condition = getFCmpCodeWithoutNaN(Condition);
Dan Gohman575fad32008-09-03 16:12:24 +00001403 } else {
1404 Condition = ISD::SETEQ; // silence warning.
Torok Edwinfbcc6632009-07-14 16:55:14 +00001405 llvm_unreachable("Unknown compare instruction");
Dan Gohman575fad32008-09-03 16:12:24 +00001406 }
Dan Gohmand01ddb52008-10-17 21:16:08 +00001407
Craig Topperc0196b12014-04-14 00:51:57 +00001408 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1409 TBB, FBB, CurBB, TWeight, FWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001410 SwitchCases.push_back(CB);
1411 return;
1412 }
Dan Gohmand01ddb52008-10-17 21:16:08 +00001413 }
1414
1415 // Create a CaseBlock record representing this branch.
Owen Anderson23a204d2009-07-31 17:39:07 +00001416 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Craig Topperc0196b12014-04-14 00:51:57 +00001417 nullptr, TBB, FBB, CurBB, TWeight, FWeight);
Dan Gohmand01ddb52008-10-17 21:16:08 +00001418 SwitchCases.push_back(CB);
1419}
1420
Manman Ren4ece7452014-01-31 00:42:44 +00001421/// Scale down both weights to fit into uint32_t.
1422static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1423 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1424 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1425 NewTrue = NewTrue / Scale;
1426 NewFalse = NewFalse / Scale;
1427}
1428
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001429/// FindMergedConditions - If Cond is an expression like
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001430void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001431 MachineBasicBlock *TBB,
1432 MachineBasicBlock *FBB,
1433 MachineBasicBlock *CurBB,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001434 MachineBasicBlock *SwitchBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001435 unsigned Opc, uint32_t TWeight,
1436 uint32_t FWeight) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001437 // If this node is not part of the or/and tree, emit it as a branch.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001438 const Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001439 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmand01ddb52008-10-17 21:16:08 +00001440 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1441 BOp->getParent() != CurBB->getBasicBlock() ||
1442 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1443 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Manman Ren4ece7452014-01-31 00:42:44 +00001444 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1445 TWeight, FWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001446 return;
1447 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001448
Dan Gohman575fad32008-09-03 16:12:24 +00001449 // Create TmpBB after CurBB.
1450 MachineFunction::iterator BBI = CurBB;
1451 MachineFunction &MF = DAG.getMachineFunction();
1452 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1453 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001454
Dan Gohman575fad32008-09-03 16:12:24 +00001455 if (Opc == Instruction::Or) {
1456 // Codegen X | Y as:
Manman Ren4ece7452014-01-31 00:42:44 +00001457 // BB1:
Dan Gohman575fad32008-09-03 16:12:24 +00001458 // jmp_if_X TBB
1459 // jmp TmpBB
1460 // TmpBB:
1461 // jmp_if_Y TBB
1462 // jmp FBB
1463 //
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001464
Manman Ren4ece7452014-01-31 00:42:44 +00001465 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1466 // The requirement is that
1467 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1468 // = TrueProb for orignal BB.
1469 // Assuming the orignal weights are A and B, one choice is to set BB1's
1470 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1471 // assumes that
1472 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1473 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1474 // TmpBB, but the math is more complicated.
Manman Ren104e0c82014-01-30 00:24:37 +00001475
Manman Ren4ece7452014-01-31 00:42:44 +00001476 uint64_t NewTrueWeight = TWeight;
1477 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1478 ScaleWeights(NewTrueWeight, NewFalseWeight);
1479 // Emit the LHS condition.
1480 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1481 NewTrueWeight, NewFalseWeight);
1482
1483 NewTrueWeight = TWeight;
1484 NewFalseWeight = 2 * (uint64_t)FWeight;
1485 ScaleWeights(NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001486 // Emit the RHS condition into TmpBB.
Manman Ren4ece7452014-01-31 00:42:44 +00001487 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1488 NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001489 } else {
1490 assert(Opc == Instruction::And && "Unknown merge op!");
1491 // Codegen X & Y as:
Manman Ren4ece7452014-01-31 00:42:44 +00001492 // BB1:
Dan Gohman575fad32008-09-03 16:12:24 +00001493 // jmp_if_X TmpBB
1494 // jmp FBB
1495 // TmpBB:
1496 // jmp_if_Y TBB
1497 // jmp FBB
1498 //
1499 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001500
Manman Ren4ece7452014-01-31 00:42:44 +00001501 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1502 // The requirement is that
1503 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1504 // = FalseProb for orignal BB.
1505 // Assuming the orignal weights are A and B, one choice is to set BB1's
1506 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1507 // assumes that
1508 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
Manman Ren104e0c82014-01-30 00:24:37 +00001509
Manman Ren4ece7452014-01-31 00:42:44 +00001510 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1511 uint64_t NewFalseWeight = FWeight;
1512 ScaleWeights(NewTrueWeight, NewFalseWeight);
1513 // Emit the LHS condition.
1514 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1515 NewTrueWeight, NewFalseWeight);
1516
1517 NewTrueWeight = 2 * (uint64_t)TWeight;
1518 NewFalseWeight = FWeight;
1519 ScaleWeights(NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001520 // Emit the RHS condition into TmpBB.
Manman Ren4ece7452014-01-31 00:42:44 +00001521 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1522 NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001523 }
1524}
1525
1526/// If the set of cases should be emitted as a series of branches, return true.
1527/// If we should emit this as a bunch of and/or'd together conditions, return
1528/// false.
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001529bool
Stephen Lin6d715e82013-07-06 21:44:25 +00001530SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
Dan Gohman575fad32008-09-03 16:12:24 +00001531 if (Cases.size() != 2) return true;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001532
Dan Gohman575fad32008-09-03 16:12:24 +00001533 // If this is two comparisons of the same values or'd or and'd together, they
1534 // will get folded into a single comparison, so don't emit two blocks.
1535 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1536 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1537 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1538 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1539 return false;
1540 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001541
Chris Lattner1eea3b02010-01-02 00:00:03 +00001542 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1543 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1544 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1545 Cases[0].CC == Cases[1].CC &&
1546 isa<Constant>(Cases[0].CmpRHS) &&
1547 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1548 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1549 return false;
1550 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1551 return false;
1552 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00001553
Dan Gohman575fad32008-09-03 16:12:24 +00001554 return true;
1555}
1556
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001557void SelectionDAGBuilder::visitBr(const BranchInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001558 MachineBasicBlock *BrMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001559
Dan Gohman575fad32008-09-03 16:12:24 +00001560 // Update machine-CFG edges.
1561 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1562
1563 // Figure out which block is immediately after the current one.
Craig Topperc0196b12014-04-14 00:51:57 +00001564 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001565 MachineFunction::iterator BBI = BrMBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001566 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001567 NextBlock = BBI;
1568
1569 if (I.isUnconditional()) {
1570 // Update machine-CFG edges.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001571 BrMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001572
Eric Christopherbfb38ba2014-04-03 12:11:51 +00001573 // If this is not a fall-through branch or optimizations are switched off,
1574 // emit the branch.
1575 if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001576 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001577 MVT::Other, getControlRoot(),
Bill Wendling954cb182010-01-28 21:51:40 +00001578 DAG.getBasicBlock(Succ0MBB)));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001579
Dan Gohman575fad32008-09-03 16:12:24 +00001580 return;
1581 }
1582
1583 // If this condition is one of the special cases we handle, do special stuff
1584 // now.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001585 const Value *CondVal = I.getCondition();
Dan Gohman575fad32008-09-03 16:12:24 +00001586 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1587
1588 // If this is a series of conditions that are or'd or and'd together, emit
1589 // this as a sequence of branches instead of setcc's with and/or operations.
Chris Lattnerea41dfe2010-11-30 18:12:52 +00001590 // As long as jumps are not expensive, this should improve performance.
Dan Gohman575fad32008-09-03 16:12:24 +00001591 // For example, instead of something like:
1592 // cmp A, B
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001593 // C = seteq
Dan Gohman575fad32008-09-03 16:12:24 +00001594 // cmp D, E
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001595 // F = setle
Dan Gohman575fad32008-09-03 16:12:24 +00001596 // or C, F
1597 // jnz foo
1598 // Emit:
1599 // cmp A, B
1600 // je foo
1601 // cmp D, E
1602 // jle foo
1603 //
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001604 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Eric Christopherd9134482014-08-04 21:25:23 +00001605 if (!TM.getSubtargetImpl()->getTargetLowering()->isJumpExpensive() &&
1606 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1607 BOp->getOpcode() == Instruction::Or)) {
Dan Gohman7c0303a2010-04-19 22:41:47 +00001608 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001609 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1610 getEdgeWeight(BrMBB, Succ1MBB));
Dan Gohman575fad32008-09-03 16:12:24 +00001611 // If the compares in later blocks need to use values not currently
1612 // exported from this block, export them now. This block should always
1613 // be the first entry.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001614 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001615
Dan Gohman575fad32008-09-03 16:12:24 +00001616 // Allow some cases to be rejected.
1617 if (ShouldEmitAsBranches(SwitchCases)) {
1618 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1619 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1620 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1621 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001622
Dan Gohman575fad32008-09-03 16:12:24 +00001623 // Emit the branch for this block.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001624 visitSwitchCase(SwitchCases[0], BrMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001625 SwitchCases.erase(SwitchCases.begin());
1626 return;
1627 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001628
Dan Gohman575fad32008-09-03 16:12:24 +00001629 // Okay, we decided not to do this, remove any inserted MBB's and clear
1630 // SwitchCases.
1631 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohmane8c913e2009-08-15 02:06:22 +00001632 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001633
Dan Gohman575fad32008-09-03 16:12:24 +00001634 SwitchCases.clear();
1635 }
1636 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001637
Dan Gohman575fad32008-09-03 16:12:24 +00001638 // Create a CaseBlock record representing this branch.
Owen Anderson23a204d2009-07-31 17:39:07 +00001639 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Craig Topperc0196b12014-04-14 00:51:57 +00001640 nullptr, Succ0MBB, Succ1MBB, BrMBB);
Bill Wendling7f5eb532009-12-21 19:59:38 +00001641
Dan Gohman575fad32008-09-03 16:12:24 +00001642 // Use visitSwitchCase to actually insert the fast branch sequence for this
1643 // cond branch.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001644 visitSwitchCase(CB, BrMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001645}
1646
1647/// visitSwitchCase - Emits the necessary code to represent a single node in
1648/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001649void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1650 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001651 SDValue Cond;
1652 SDValue CondLHS = getValue(CB.CmpLHS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001653 SDLoc dl = getCurSDLoc();
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001654
1655 // Build the setcc now.
Craig Topperc0196b12014-04-14 00:51:57 +00001656 if (!CB.CmpMHS) {
Dan Gohman575fad32008-09-03 16:12:24 +00001657 // Fold "(X == true)" to X and "(X == false)" to !X to
1658 // handle common cases produced by branch lowering.
Owen Anderson23a204d2009-07-31 17:39:07 +00001659 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Anderson2ad52172009-07-21 02:47:59 +00001660 CB.CC == ISD::SETEQ)
Dan Gohman575fad32008-09-03 16:12:24 +00001661 Cond = CondLHS;
Owen Anderson23a204d2009-07-31 17:39:07 +00001662 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Anderson2ad52172009-07-21 02:47:59 +00001663 CB.CC == ISD::SETEQ) {
Dan Gohman575fad32008-09-03 16:12:24 +00001664 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001665 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohman575fad32008-09-03 16:12:24 +00001666 } else
Owen Anderson9f944592009-08-11 20:47:22 +00001667 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohman575fad32008-09-03 16:12:24 +00001668 } else {
Bob Wilsone4077362013-09-09 19:14:35 +00001669 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Dan Gohman575fad32008-09-03 16:12:24 +00001670
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001671 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1672 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00001673
1674 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001675 EVT VT = CmpOp.getValueType();
Stephen Lincfe7f352013-07-08 00:37:03 +00001676
Bob Wilsone4077362013-09-09 19:14:35 +00001677 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson9f944592009-08-11 20:47:22 +00001678 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Bob Wilsone4077362013-09-09 19:14:35 +00001679 ISD::SETLE);
Dan Gohman575fad32008-09-03 16:12:24 +00001680 } else {
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001681 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesened255b32009-01-30 01:34:22 +00001682 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson9f944592009-08-11 20:47:22 +00001683 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohman575fad32008-09-03 16:12:24 +00001684 DAG.getConstant(High-Low, VT), ISD::SETULE);
1685 }
1686 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001687
Dan Gohman575fad32008-09-03 16:12:24 +00001688 // Update successor info
Jakub Staszak0480a8f2011-07-29 22:25:21 +00001689 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
Jakob Stoklund Olesen7d33c572012-08-20 21:39:52 +00001690 // TrueBB and FalseBB are always different unless the incoming IR is
1691 // degenerate. This only happens when running llc on weird IR.
1692 if (CB.TrueBB != CB.FalseBB)
1693 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001694
Dan Gohman575fad32008-09-03 16:12:24 +00001695 // Set NextBlock to be the MBB immediately after the current one, if any.
1696 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001697 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001698 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001699 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001700 NextBlock = BBI;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001701
Dan Gohman575fad32008-09-03 16:12:24 +00001702 // If the lhs block is the next block, invert the condition so that we can
1703 // fall through to the lhs instead of the rhs block.
1704 if (CB.TrueBB == NextBlock) {
1705 std::swap(CB.TrueBB, CB.FalseBB);
1706 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001707 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohman575fad32008-09-03 16:12:24 +00001708 }
Bill Wendling7f5eb532009-12-21 19:59:38 +00001709
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001710 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson9f944592009-08-11 20:47:22 +00001711 MVT::Other, getControlRoot(), Cond,
Dale Johannesened255b32009-01-30 01:34:22 +00001712 DAG.getBasicBlock(CB.TrueBB));
Bill Wendlingc6b47342009-12-21 23:47:40 +00001713
Evan Cheng79687dd2010-09-23 06:51:55 +00001714 // Insert the false branch. Do this even if it's a fall through branch,
1715 // this makes it easier to do DAG optimizations which require inverting
1716 // the branch condition.
1717 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1718 DAG.getBasicBlock(CB.FalseBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001719
1720 DAG.setRoot(BrCond);
Dan Gohman575fad32008-09-03 16:12:24 +00001721}
1722
1723/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001724void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
Dan Gohman575fad32008-09-03 16:12:24 +00001725 // Emit the code for the jump table
1726 assert(JT.Reg != -1U && "Should lower JT Header first!");
Eric Christopherd9134482014-08-04 21:25:23 +00001727 EVT PTy = TM.getSubtargetImpl()->getTargetLowering()->getPointerTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001728 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00001729 JT.Reg, PTy);
Dan Gohman575fad32008-09-03 16:12:24 +00001730 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001731 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
Bill Wendling7f5eb532009-12-21 19:59:38 +00001732 MVT::Other, Index.getValue(1),
1733 Table, Index);
1734 DAG.setRoot(BrJumpTable);
Dan Gohman575fad32008-09-03 16:12:24 +00001735}
1736
1737/// visitJumpTableHeader - This function emits necessary code to produce index
1738/// in the JumpTable from switch case.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001739void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001740 JumpTableHeader &JTH,
1741 MachineBasicBlock *SwitchBB) {
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001742 // Subtract the lowest switch case value from the value being switched on and
1743 // conditional branch to default mbb if the result is greater than the
Dan Gohman575fad32008-09-03 16:12:24 +00001744 // difference between smallest and largest cases.
1745 SDValue SwitchOp = getValue(JTH.SValue);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001746 EVT VT = SwitchOp.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001747 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001748 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001749
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001750 // The SDNode we just created, which holds the value being switched on minus
Dan Gohman4a618822010-02-10 16:03:48 +00001751 // the smallest case value, needs to be copied to a virtual register so it
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001752 // can be used as an index into the jump table in a subsequent basic block.
1753 // This value may be smaller or larger than the target's pointer type, and
1754 // therefore require extension or truncating.
Eric Christopherd9134482014-08-04 21:25:23 +00001755 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001756 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI->getPointerTy());
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001757
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001758 unsigned JumpTableReg = FuncInfo.CreateReg(TLI->getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001759 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00001760 JumpTableReg, SwitchOp);
Dan Gohman575fad32008-09-03 16:12:24 +00001761 JT.Reg = JumpTableReg;
1762
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001763 // Emit the range check for the jump table, and branch to the default block
1764 // for the switch statement if the value being switched on exceeds the largest
1765 // case in the switch.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001766 SDValue CMP = DAG.getSetCC(getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001767 TLI->getSetCCResultType(*DAG.getContext(),
1768 Sub.getValueType()),
Matt Arsenault758659232013-05-18 00:21:46 +00001769 Sub,
1770 DAG.getConstant(JTH.Last - JTH.First,VT),
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001771 ISD::SETUGT);
Dan Gohman575fad32008-09-03 16:12:24 +00001772
1773 // Set NextBlock to be the MBB immediately after the current one, if any.
1774 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001775 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001776 MachineFunction::iterator BBI = SwitchBB;
Bill Wendlingc6b47342009-12-21 23:47:40 +00001777
Dan Gohmane8c913e2009-08-15 02:06:22 +00001778 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001779 NextBlock = BBI;
1780
Andrew Trickef9de2a2013-05-25 02:42:55 +00001781 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001782 MVT::Other, CopyTo, CMP,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001783 DAG.getBasicBlock(JT.Default));
Dan Gohman575fad32008-09-03 16:12:24 +00001784
Bill Wendling954cb182010-01-28 21:51:40 +00001785 if (JT.MBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001786 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
Bill Wendling7f5eb532009-12-21 19:59:38 +00001787 DAG.getBasicBlock(JT.MBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001788
Bill Wendlingc6b47342009-12-21 23:47:40 +00001789 DAG.setRoot(BrCond);
Dan Gohman575fad32008-09-03 16:12:24 +00001790}
1791
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001792/// Codegen a new tail for a stack protector check ParentMBB which has had its
1793/// tail spliced into a stack protector check success bb.
1794///
1795/// For a high level explanation of how this fits into the stack protector
1796/// generation see the comment on the declaration of class
1797/// StackProtectorDescriptor.
1798void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1799 MachineBasicBlock *ParentBB) {
1800
1801 // First create the loads to the guard/stack slot for the comparison.
Eric Christopherd9134482014-08-04 21:25:23 +00001802 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001803 EVT PtrTy = TLI->getPointerTy();
1804
1805 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1806 int FI = MFI->getStackProtectorIndex();
1807
1808 const Value *IRGuard = SPD.getGuard();
1809 SDValue GuardPtr = getValue(IRGuard);
1810 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1811
1812 unsigned Align =
1813 TLI->getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00001814
1815 SDValue Guard;
1816
1817 // If useLoadStackGuardNode returns true, retrieve the guard value from
1818 // the virtual register holding the value. Otherwise, emit a volatile load
1819 // to retrieve the stack guard value.
1820 if (TLI->useLoadStackGuardNode())
1821 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1822 SPD.getGuardReg(), PtrTy);
1823 else
1824 Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1825 GuardPtr, MachinePointerInfo(IRGuard, 0),
1826 true, false, false, Align);
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001827
1828 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1829 StackSlotPtr,
1830 MachinePointerInfo::getFixedStack(FI),
1831 true, false, false, Align);
1832
1833 // Perform the comparison via a subtract/getsetcc.
1834 EVT VT = Guard.getValueType();
1835 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1836
1837 SDValue Cmp = DAG.getSetCC(getCurSDLoc(),
1838 TLI->getSetCCResultType(*DAG.getContext(),
1839 Sub.getValueType()),
1840 Sub, DAG.getConstant(0, VT),
1841 ISD::SETNE);
1842
1843 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1844 // branch to failure MBB.
1845 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1846 MVT::Other, StackSlot.getOperand(0),
1847 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1848 // Otherwise branch to success MBB.
1849 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1850 MVT::Other, BrCond,
1851 DAG.getBasicBlock(SPD.getSuccessMBB()));
1852
1853 DAG.setRoot(Br);
1854}
1855
1856/// Codegen the failure basic block for a stack protector check.
1857///
1858/// A failure stack protector machine basic block consists simply of a call to
1859/// __stack_chk_fail().
1860///
1861/// For a high level explanation of how this fits into the stack protector
1862/// generation see the comment on the declaration of class
1863/// StackProtectorDescriptor.
1864void
1865SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
Eric Christopherd9134482014-08-04 21:25:23 +00001866 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001867 SDValue Chain = TLI->makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
Craig Topperc0196b12014-04-14 00:51:57 +00001868 MVT::isVoid, nullptr, 0, false,
1869 getCurSDLoc(), false, false).second;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001870 DAG.setRoot(Chain);
1871}
1872
Dan Gohman575fad32008-09-03 16:12:24 +00001873/// visitBitTestHeader - This function emits necessary code to produce value
1874/// suitable for "bit tests"
Dan Gohman7c0303a2010-04-19 22:41:47 +00001875void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1876 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001877 // Subtract the minimum value
1878 SDValue SwitchOp = getValue(B.SValue);
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00001879 EVT VT = SwitchOp.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001880 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001881 DAG.getConstant(B.First, VT));
Dan Gohman575fad32008-09-03 16:12:24 +00001882
1883 // Check range
Eric Christopherd9134482014-08-04 21:25:23 +00001884 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001885 SDValue RangeCmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001886 TLI->getSetCCResultType(*DAG.getContext(),
Matt Arsenault758659232013-05-18 00:21:46 +00001887 Sub.getValueType()),
Bill Wendlingc6b47342009-12-21 23:47:40 +00001888 Sub, DAG.getConstant(B.Range, VT),
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001889 ISD::SETUGT);
Dan Gohman575fad32008-09-03 16:12:24 +00001890
Evan Chengac730dd2011-01-06 01:02:44 +00001891 // Determine the type of the test operands.
1892 bool UsePtrType = false;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001893 if (!TLI->isTypeLegal(VT))
Evan Chengac730dd2011-01-06 01:02:44 +00001894 UsePtrType = true;
1895 else {
1896 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
Eli Friedman979009e2011-10-12 22:46:45 +00001897 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
Evan Chengac730dd2011-01-06 01:02:44 +00001898 // Switch table case range are encoded into series of masks.
1899 // Just use pointer type, it's guaranteed to fit.
1900 UsePtrType = true;
1901 break;
1902 }
1903 }
1904 if (UsePtrType) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001905 VT = TLI->getPointerTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001906 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
Evan Chengac730dd2011-01-06 01:02:44 +00001907 }
Dan Gohman575fad32008-09-03 16:12:24 +00001908
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00001909 B.RegVT = VT.getSimpleVT();
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00001910 B.Reg = FuncInfo.CreateReg(B.RegVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001911 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001912 B.Reg, Sub);
Dan Gohman575fad32008-09-03 16:12:24 +00001913
1914 // Set NextBlock to be the MBB immediately after the current one, if any.
1915 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001916 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001917 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001918 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001919 NextBlock = BBI;
1920
1921 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1922
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001923 addSuccessorWithWeight(SwitchBB, B.Default);
1924 addSuccessorWithWeight(SwitchBB, MBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001925
Andrew Trickef9de2a2013-05-25 02:42:55 +00001926 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001927 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001928 DAG.getBasicBlock(B.Default));
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001929
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001930 if (MBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001931 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001932 DAG.getBasicBlock(MBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001933
Bill Wendlingc6b47342009-12-21 23:47:40 +00001934 DAG.setRoot(BrRange);
Dan Gohman575fad32008-09-03 16:12:24 +00001935}
1936
1937/// visitBitTestCase - this function produces one "bit test"
Evan Chengac730dd2011-01-06 01:02:44 +00001938void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1939 MachineBasicBlock* NextMBB,
Manman Rencf104462012-08-24 18:14:27 +00001940 uint32_t BranchWeightToNext,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001941 unsigned Reg,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001942 BitTestCase &B,
1943 MachineBasicBlock *SwitchBB) {
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00001944 MVT VT = BB.RegVT;
Andrew Trickef9de2a2013-05-25 02:42:55 +00001945 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001946 Reg, VT);
Dan Gohman0695e092010-06-24 02:06:24 +00001947 SDValue Cmp;
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001948 unsigned PopCount = CountPopulation_64(B.Mask);
Eric Christopherd9134482014-08-04 21:25:23 +00001949 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001950 if (PopCount == 1) {
Dan Gohman0695e092010-06-24 02:06:24 +00001951 // Testing for a single bit; just compare the shift count with what it
1952 // would need to be to shift a 1 bit in that position.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001953 Cmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001954 TLI->getSetCCResultType(*DAG.getContext(), VT),
Dan Gohman0695e092010-06-24 02:06:24 +00001955 ShiftOp,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001956 DAG.getConstant(countTrailingZeros(B.Mask), VT),
Dan Gohman0695e092010-06-24 02:06:24 +00001957 ISD::SETEQ);
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001958 } else if (PopCount == BB.Range) {
1959 // There is only one zero bit in the range, test for it directly.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001960 Cmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001961 TLI->getSetCCResultType(*DAG.getContext(), VT),
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001962 ShiftOp,
1963 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1964 ISD::SETNE);
Dan Gohman0695e092010-06-24 02:06:24 +00001965 } else {
1966 // Make desired shift
Andrew Trickef9de2a2013-05-25 02:42:55 +00001967 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
Evan Chengac730dd2011-01-06 01:02:44 +00001968 DAG.getConstant(1, VT), ShiftOp);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001969
Dan Gohman0695e092010-06-24 02:06:24 +00001970 // Emit bit tests and jumps
Andrew Trickef9de2a2013-05-25 02:42:55 +00001971 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001972 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001973 Cmp = DAG.getSetCC(getCurSDLoc(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001974 TLI->getSetCCResultType(*DAG.getContext(), VT),
Evan Chengac730dd2011-01-06 01:02:44 +00001975 AndOp, DAG.getConstant(0, VT),
Dan Gohman0695e092010-06-24 02:06:24 +00001976 ISD::SETNE);
1977 }
Dan Gohman575fad32008-09-03 16:12:24 +00001978
Manman Rencf104462012-08-24 18:14:27 +00001979 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1980 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1981 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1982 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001983
Andrew Trickef9de2a2013-05-25 02:42:55 +00001984 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001985 MVT::Other, getControlRoot(),
Dan Gohman0695e092010-06-24 02:06:24 +00001986 Cmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohman575fad32008-09-03 16:12:24 +00001987
1988 // Set NextBlock to be the MBB immediately after the current one, if any.
1989 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001990 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001991 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001992 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001993 NextBlock = BBI;
1994
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001995 if (NextMBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001996 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001997 DAG.getBasicBlock(NextMBB));
Bill Wendling28727f32009-12-21 21:59:52 +00001998
Bill Wendlingc6b47342009-12-21 23:47:40 +00001999 DAG.setRoot(BrAnd);
Dan Gohman575fad32008-09-03 16:12:24 +00002000}
2001
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002002void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00002003 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002004
Dan Gohman575fad32008-09-03 16:12:24 +00002005 // Retrieve successors.
2006 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2007 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2008
Gabor Greif08a4c282009-01-15 11:10:44 +00002009 const Value *Callee(I.getCalledValue());
Nuno Lopesec9653b2012-06-28 22:30:12 +00002010 const Function *Fn = dyn_cast<Function>(Callee);
Gabor Greif08a4c282009-01-15 11:10:44 +00002011 if (isa<InlineAsm>(Callee))
Dan Gohman575fad32008-09-03 16:12:24 +00002012 visitInlineAsm(&I);
Nuno Lopesec9653b2012-06-28 22:30:12 +00002013 else if (Fn && Fn->isIntrinsic()) {
2014 assert(Fn->getIntrinsicID() == Intrinsic::donothing);
Nuno Lopes21514972012-07-18 00:07:17 +00002015 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
Nuno Lopesec9653b2012-06-28 22:30:12 +00002016 } else
Gabor Greif08a4c282009-01-15 11:10:44 +00002017 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohman575fad32008-09-03 16:12:24 +00002018
2019 // If the value of the invoke is used outside of its defining block, make it
2020 // available as a virtual register.
Dan Gohman9478c3f2009-04-23 23:13:24 +00002021 CopyToExportRegsIfNeeded(&I);
Dan Gohman575fad32008-09-03 16:12:24 +00002022
2023 // Update successor info
Chandler Carruthe2530dc2011-11-22 11:37:46 +00002024 addSuccessorWithWeight(InvokeMBB, Return);
2025 addSuccessorWithWeight(InvokeMBB, LandingPad);
Dan Gohman575fad32008-09-03 16:12:24 +00002026
2027 // Drop into normal successor.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002028 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002029 MVT::Other, getControlRoot(),
2030 DAG.getBasicBlock(Return)));
Dan Gohman575fad32008-09-03 16:12:24 +00002031}
2032
Bill Wendlingf891bf82011-07-31 06:30:59 +00002033void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2034 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2035}
2036
Bill Wendling247fd3b2011-08-17 21:56:44 +00002037void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2038 assert(FuncInfo.MBB->isLandingPad() &&
2039 "Call to landingpad not in landing pad!");
2040
2041 MachineBasicBlock *MBB = FuncInfo.MBB;
2042 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2043 AddLandingPadInfo(LP, MMI, MBB);
2044
Bill Wendling05d6f2f2012-02-13 23:47:16 +00002045 // If there aren't registers to copy the values into (e.g., during SjLj
2046 // exceptions), then don't bother to create these DAG nodes.
Eric Christopherd9134482014-08-04 21:25:23 +00002047 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002048 if (TLI->getExceptionPointerRegister() == 0 &&
2049 TLI->getExceptionSelectorRegister() == 0)
Bill Wendling05d6f2f2012-02-13 23:47:16 +00002050 return;
2051
Bill Wendling247fd3b2011-08-17 21:56:44 +00002052 SmallVector<EVT, 2> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002053 ComputeValueVTs(*TLI, LP.getType(), ValueVTs);
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002054 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
Bill Wendling247fd3b2011-08-17 21:56:44 +00002055
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002056 // Get the two live-in registers as SDValues. The physregs have already been
2057 // copied into virtual registers.
Bill Wendling247fd3b2011-08-17 21:56:44 +00002058 SDValue Ops[2];
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002059 Ops[0] = DAG.getZExtOrTrunc(
2060 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2061 FuncInfo.ExceptionPointerVirtReg, TLI->getPointerTy()),
2062 getCurSDLoc(), ValueVTs[0]);
2063 Ops[1] = DAG.getZExtOrTrunc(
2064 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2065 FuncInfo.ExceptionSelectorVirtReg, TLI->getPointerTy()),
2066 getCurSDLoc(), ValueVTs[1]);
Bill Wendling247fd3b2011-08-17 21:56:44 +00002067
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002068 // Merge into one.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002069 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00002070 DAG.getVTList(ValueVTs), Ops);
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002071 setValue(&LP, Res);
Bill Wendling247fd3b2011-08-17 21:56:44 +00002072}
2073
Dan Gohman575fad32008-09-03 16:12:24 +00002074/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2075/// small case ranges).
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002076bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2077 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002078 const Value* SV,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002079 MachineBasicBlock *Default,
2080 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002081 // Size is the number of Cases represented by this range.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002082 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohman575fad32008-09-03 16:12:24 +00002083 if (Size > 3)
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002084 return false;
2085
Dan Gohman575fad32008-09-03 16:12:24 +00002086 // Get the MachineFunction which holds the current MBB. This is used when
2087 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002088 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002089
2090 // Figure out which block is immediately after the current one.
Craig Topperc0196b12014-04-14 00:51:57 +00002091 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00002092 MachineFunction::iterator BBI = CR.CaseBB;
2093
Dan Gohmane8c913e2009-08-15 02:06:22 +00002094 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00002095 NextBlock = BBI;
2096
Manman Rencf104462012-08-24 18:14:27 +00002097 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Benjamin Kramer24656c92010-11-22 09:45:38 +00002098 // If any two of the cases has the same destination, and if one value
Dan Gohman575fad32008-09-03 16:12:24 +00002099 // is the same as the other, but has one bit unset that the other has set,
2100 // use bit manipulation to do two compares at once. For example:
2101 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Benjamin Kramer24656c92010-11-22 09:45:38 +00002102 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2103 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2104 if (Size == 2 && CR.CaseBB == SwitchBB) {
2105 Case &Small = *CR.Range.first;
2106 Case &Big = *(CR.Range.second-1);
2107
2108 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2109 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2110 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2111
2112 // Check that there is only one bit different.
2113 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2114 (SmallValue | BigValue) == BigValue) {
2115 // Isolate the common bit.
2116 APInt CommonBit = BigValue & ~SmallValue;
2117 assert((SmallValue | CommonBit) == BigValue &&
2118 CommonBit.countPopulation() == 1 && "Not a common bit?");
2119
2120 SDValue CondLHS = getValue(SV);
2121 EVT VT = CondLHS.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002122 SDLoc DL = getCurSDLoc();
Benjamin Kramer24656c92010-11-22 09:45:38 +00002123
2124 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2125 DAG.getConstant(CommonBit, VT));
2126 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2127 Or, DAG.getConstant(BigValue, VT),
2128 ISD::SETEQ);
2129
2130 // Update successor info.
Manman Rencf104462012-08-24 18:14:27 +00002131 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2132 addSuccessorWithWeight(SwitchBB, Small.BB,
2133 Small.ExtraWeight + Big.ExtraWeight);
2134 addSuccessorWithWeight(SwitchBB, Default,
2135 // The default destination is the first successor in IR.
2136 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
Benjamin Kramer24656c92010-11-22 09:45:38 +00002137
2138 // Insert the true branch.
2139 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2140 getControlRoot(), Cond,
2141 DAG.getBasicBlock(Small.BB));
2142
2143 // Insert the false branch.
2144 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2145 DAG.getBasicBlock(Default));
2146
2147 DAG.setRoot(BrCond);
2148 return true;
2149 }
2150 }
2151 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002152
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002153 // Order cases by weight so the most likely case will be checked first.
Manman Rencf104462012-08-24 18:14:27 +00002154 uint32_t UnhandledWeights = 0;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002155 if (BPI) {
2156 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
Manman Rencf104462012-08-24 18:14:27 +00002157 uint32_t IWeight = I->ExtraWeight;
2158 UnhandledWeights += IWeight;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002159 for (CaseItr J = CR.Range.first; J < I; ++J) {
Manman Rencf104462012-08-24 18:14:27 +00002160 uint32_t JWeight = J->ExtraWeight;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002161 if (IWeight > JWeight)
2162 std::swap(*I, *J);
2163 }
2164 }
2165 }
Dan Gohman575fad32008-09-03 16:12:24 +00002166 // Rearrange the case blocks so that the last one falls through if possible.
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002167 Case &BackCase = *(CR.Range.second-1);
Benjamin Kramer5aad8722012-05-26 21:19:12 +00002168 if (Size > 1 &&
2169 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Dan Gohman575fad32008-09-03 16:12:24 +00002170 // The last case block won't fall through into 'NextBlock' if we emit the
2171 // branches in this order. See if rearranging a case value would help.
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002172 // We start at the bottom as it's the case with the least weight.
Stephen Lin6d715e82013-07-06 21:44:25 +00002173 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
Dan Gohman575fad32008-09-03 16:12:24 +00002174 if (I->BB == NextBlock) {
2175 std::swap(*I, BackCase);
2176 break;
2177 }
Dan Gohman575fad32008-09-03 16:12:24 +00002178 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002179
Dan Gohman575fad32008-09-03 16:12:24 +00002180 // Create a CaseBlock record representing a conditional branch to
2181 // the Case's target mbb if the value being switched on SV is equal
2182 // to C.
2183 MachineBasicBlock *CurBlock = CR.CaseBB;
2184 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2185 MachineBasicBlock *FallThrough;
2186 if (I != E-1) {
2187 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2188 CurMF->insert(BBI, FallThrough);
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002189
2190 // Put SV in a virtual register to make it available from the new blocks.
2191 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002192 } else {
2193 // If the last case doesn't match, go to the default block.
2194 FallThrough = Default;
2195 }
2196
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002197 const Value *RHS, *LHS, *MHS;
Dan Gohman575fad32008-09-03 16:12:24 +00002198 ISD::CondCode CC;
2199 if (I->High == I->Low) {
2200 // This is just small small case range :) containing exactly 1 case
2201 CC = ISD::SETEQ;
Craig Topperc0196b12014-04-14 00:51:57 +00002202 LHS = SV; RHS = I->High; MHS = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00002203 } else {
Bob Wilsone4077362013-09-09 19:14:35 +00002204 CC = ISD::SETLE;
Dan Gohman575fad32008-09-03 16:12:24 +00002205 LHS = I->Low; MHS = SV; RHS = I->High;
2206 }
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002207
Manman Rencf104462012-08-24 18:14:27 +00002208 // The false weight should be sum of all un-handled cases.
2209 UnhandledWeights -= I->ExtraWeight;
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002210 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2211 /* me */ CurBlock,
Manman Rencf104462012-08-24 18:14:27 +00002212 /* trueweight */ I->ExtraWeight,
2213 /* falseweight */ UnhandledWeights);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002214
Dan Gohman575fad32008-09-03 16:12:24 +00002215 // If emitting the first comparison, just call visitSwitchCase to emit the
2216 // code into the current block. Otherwise, push the CaseBlock onto the
2217 // vector to be later processed by SDISel, and insert the node's MBB
2218 // before the next MBB.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002219 if (CurBlock == SwitchBB)
2220 visitSwitchCase(CB, SwitchBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002221 else
2222 SwitchCases.push_back(CB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002223
Dan Gohman575fad32008-09-03 16:12:24 +00002224 CurBlock = FallThrough;
2225 }
2226
2227 return true;
2228}
2229
2230static inline bool areJTsAllowed(const TargetLowering &TLI) {
Evan Cheng39e90022012-07-02 22:39:56 +00002231 return TLI.supportJumpTables() &&
Owen Anderson9f944592009-08-11 20:47:22 +00002232 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2233 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohman575fad32008-09-03 16:12:24 +00002234}
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002235
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002236static APInt ComputeRange(const APInt &First, const APInt &Last) {
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002237 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
Bob Wilsone4077362013-09-09 19:14:35 +00002238 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002239 return (LastExt - FirstExt + 1ULL);
2240}
2241
Dan Gohman575fad32008-09-03 16:12:24 +00002242/// handleJTSwitchCase - Emit jumptable for current switch case range
Chris Lattnere74e0c82011-09-09 22:06:59 +00002243bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2244 CaseRecVector &WorkList,
2245 const Value *SV,
2246 MachineBasicBlock *Default,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002247 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002248 Case& FrontCase = *CR.Range.first;
2249 Case& BackCase = *(CR.Range.second-1);
2250
Chris Lattner8e1d7222009-11-07 07:50:34 +00002251 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2252 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00002253
Chris Lattner8e1d7222009-11-07 07:50:34 +00002254 APInt TSize(First.getBitWidth(), 0);
Chris Lattnere74e0c82011-09-09 22:06:59 +00002255 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
Dan Gohman575fad32008-09-03 16:12:24 +00002256 TSize += I->size();
2257
Eric Christopherd9134482014-08-04 21:25:23 +00002258 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002259 if (!areJTsAllowed(*TLI) || TSize.ult(TLI->getMinimumJumpTableEntries()))
Dan Gohman575fad32008-09-03 16:12:24 +00002260 return false;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002261
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002262 APInt Range = ComputeRange(First, Last);
Jakob Stoklund Olesene8261a22011-10-26 01:47:48 +00002263 // The density is TSize / Range. Require at least 40%.
2264 // It should not be possible for IntTSize to saturate for sane code, but make
2265 // sure we handle Range saturation correctly.
2266 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2267 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2268 if (IntTSize * 10 < IntRange * 4)
Dan Gohman575fad32008-09-03 16:12:24 +00002269 return false;
2270
David Greene5730f202010-01-05 01:24:57 +00002271 DEBUG(dbgs() << "Lowering jump table\n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002272 << "First entry: " << First << ". Last entry: " << Last << '\n'
Jakob Stoklund Olesene8261a22011-10-26 01:47:48 +00002273 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
Dan Gohman575fad32008-09-03 16:12:24 +00002274
2275 // Get the MachineFunction which holds the current MBB. This is used when
2276 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002277 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002278
2279 // Figure out which block is immediately after the current one.
Dan Gohman575fad32008-09-03 16:12:24 +00002280 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands3ee3c172009-09-06 18:03:32 +00002281 ++BBI;
Dan Gohman575fad32008-09-03 16:12:24 +00002282
2283 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2284
2285 // Create a new basic block to hold the code for loading the address
2286 // of the jump table, and jumping to it. Update successor information;
2287 // we will either branch to the default case for the switch, or the jump
2288 // table.
2289 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2290 CurMF->insert(BBI, JumpTableBB);
Jakub Staszak12a43bd2011-06-16 20:22:37 +00002291
2292 addSuccessorWithWeight(CR.CaseBB, Default);
2293 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002294
Dan Gohman575fad32008-09-03 16:12:24 +00002295 // Build a vector of destination BBs, corresponding to each target
2296 // of the jump table. If the value of the jump table slot corresponds to
2297 // a case statement, push the case's BB onto the vector, otherwise, push
2298 // the default BB.
2299 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002300 APInt TEI = First;
Dan Gohman575fad32008-09-03 16:12:24 +00002301 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Chris Lattnerb6db2c62010-01-25 23:26:13 +00002302 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2303 const APInt &High = cast<ConstantInt>(I->High)->getValue();
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002304
Bob Wilsone4077362013-09-09 19:14:35 +00002305 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002306 DestBBs.push_back(I->BB);
2307 if (TEI==High)
2308 ++I;
2309 } else {
2310 DestBBs.push_back(Default);
2311 }
2312 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002313
Manman Rencf104462012-08-24 18:14:27 +00002314 // Calculate weight for each unique destination in CR.
2315 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2316 if (FuncInfo.BPI)
2317 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2318 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2319 DestWeights.find(I->BB);
Stephen Lincfe7f352013-07-08 00:37:03 +00002320 if (Itr != DestWeights.end())
Manman Rencf104462012-08-24 18:14:27 +00002321 Itr->second += I->ExtraWeight;
2322 else
2323 DestWeights[I->BB] = I->ExtraWeight;
2324 }
2325
Dan Gohman575fad32008-09-03 16:12:24 +00002326 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002327 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2328 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohman575fad32008-09-03 16:12:24 +00002329 E = DestBBs.end(); I != E; ++I) {
2330 if (!SuccsHandled[(*I)->getNumber()]) {
2331 SuccsHandled[(*I)->getNumber()] = true;
Manman Rencf104462012-08-24 18:14:27 +00002332 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2333 DestWeights.find(*I);
2334 addSuccessorWithWeight(JumpTableBB, *I,
2335 Itr != DestWeights.end() ? Itr->second : 0);
Dan Gohman575fad32008-09-03 16:12:24 +00002336 }
2337 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002338
Bob Wilson3c7cde42010-03-18 18:42:41 +00002339 // Create a jump table index for this jump table.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002340 unsigned JTEncoding = TLI->getJumpTableEncoding();
Chris Lattnerb6db2c62010-01-25 23:26:13 +00002341 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
Bob Wilson3c7cde42010-03-18 18:42:41 +00002342 ->createJumpTableIndex(DestBBs);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002343
Dan Gohman575fad32008-09-03 16:12:24 +00002344 // Set the jump table information so that we can codegen it as a second
2345 // MachineBasicBlock
2346 JumpTable JT(-1U, JTI, JumpTableBB, Default);
Dan Gohman7c0303a2010-04-19 22:41:47 +00002347 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2348 if (CR.CaseBB == SwitchBB)
2349 visitJumpTableHeader(JT, JTH, SwitchBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002350
Dan Gohman575fad32008-09-03 16:12:24 +00002351 JTCases.push_back(JumpTableBlock(JTH, JT));
Dan Gohman575fad32008-09-03 16:12:24 +00002352 return true;
2353}
2354
2355/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2356/// 2 subtrees.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002357bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2358 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002359 const Value* SV,
Stephen Lin6d715e82013-07-06 21:44:25 +00002360 MachineBasicBlock* Default,
2361 MachineBasicBlock* SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002362 // Get the MachineFunction which holds the current MBB. This is used when
2363 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002364 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002365
2366 // Figure out which block is immediately after the current one.
Dan Gohman575fad32008-09-03 16:12:24 +00002367 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands3ee3c172009-09-06 18:03:32 +00002368 ++BBI;
Dan Gohman575fad32008-09-03 16:12:24 +00002369
2370 Case& FrontCase = *CR.Range.first;
2371 Case& BackCase = *(CR.Range.second-1);
2372 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2373
2374 // Size is the number of Cases represented by this range.
2375 unsigned Size = CR.Range.second - CR.Range.first;
2376
Chris Lattner8e1d7222009-11-07 07:50:34 +00002377 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2378 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00002379 double FMetric = 0;
2380 CaseItr Pivot = CR.Range.first + Size/2;
2381
2382 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2383 // (heuristically) allow us to emit JumpTable's later.
Chris Lattner8e1d7222009-11-07 07:50:34 +00002384 APInt TSize(First.getBitWidth(), 0);
Dan Gohman575fad32008-09-03 16:12:24 +00002385 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2386 I!=E; ++I)
2387 TSize += I->size();
2388
Chris Lattner8e1d7222009-11-07 07:50:34 +00002389 APInt LSize = FrontCase.size();
2390 APInt RSize = TSize-LSize;
David Greene5730f202010-01-05 01:24:57 +00002391 DEBUG(dbgs() << "Selecting best pivot: \n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002392 << "First: " << First << ", Last: " << Last <<'\n'
2393 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002394 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2395 J!=E; ++I, ++J) {
Chris Lattner8e1d7222009-11-07 07:50:34 +00002396 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2397 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002398 APInt Range = ComputeRange(LEnd, RBegin);
Stepan Dyatkovskiye01e9862012-05-15 06:50:18 +00002399 assert((Range - 2ULL).isNonNegative() &&
2400 "Invalid case distance");
Chris Lattnercfe5aa62011-04-09 06:57:13 +00002401 // Use volatile double here to avoid excess precision issues on some hosts,
2402 // e.g. that use 80-bit X87 registers.
2403 volatile double LDensity =
2404 (double)LSize.roundToDouble() /
Chris Lattner8e1d7222009-11-07 07:50:34 +00002405 (LEnd - First + 1ULL).roundToDouble();
Chris Lattnercfe5aa62011-04-09 06:57:13 +00002406 volatile double RDensity =
2407 (double)RSize.roundToDouble() /
Chris Lattner8e1d7222009-11-07 07:50:34 +00002408 (Last - RBegin + 1ULL).roundToDouble();
Rafael Espindolad50dbc72013-12-05 04:14:33 +00002409 volatile double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohman575fad32008-09-03 16:12:24 +00002410 // Should always split in some non-trivial place
David Greene5730f202010-01-05 01:24:57 +00002411 DEBUG(dbgs() <<"=>Step\n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002412 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2413 << "LDensity: " << LDensity
2414 << ", RDensity: " << RDensity << '\n'
2415 << "Metric: " << Metric << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002416 if (FMetric < Metric) {
2417 Pivot = J;
2418 FMetric = Metric;
David Greene5730f202010-01-05 01:24:57 +00002419 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002420 }
2421
2422 LSize += J->size();
2423 RSize -= J->size();
2424 }
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002425
Eric Christopherd9134482014-08-04 21:25:23 +00002426 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002427 if (areJTsAllowed(*TLI)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002428 // If our case is dense we *really* should handle it earlier!
2429 assert((FMetric > 0) && "Should handle dense range earlier!");
2430 } else {
2431 Pivot = CR.Range.first + Size/2;
2432 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002433
Dan Gohman575fad32008-09-03 16:12:24 +00002434 CaseRange LHSR(CR.Range.first, Pivot);
2435 CaseRange RHSR(Pivot, CR.Range.second);
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002436 const Constant *C = Pivot->Low;
Craig Topperc0196b12014-04-14 00:51:57 +00002437 MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002438
Dan Gohman575fad32008-09-03 16:12:24 +00002439 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002440 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohman575fad32008-09-03 16:12:24 +00002441 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002442 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohman575fad32008-09-03 16:12:24 +00002443 // Pivot's Value, then we can branch directly to the LHS's Target,
2444 // rather than creating a leaf node for it.
2445 if ((LHSR.second - LHSR.first) == 1 &&
2446 LHSR.first->High == CR.GE &&
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002447 cast<ConstantInt>(C)->getValue() ==
2448 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002449 TrueBB = LHSR.first->BB;
2450 } else {
2451 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2452 CurMF->insert(BBI, TrueBB);
2453 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002454
2455 // Put SV in a virtual register to make it available from the new blocks.
2456 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002457 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002458
Dan Gohman575fad32008-09-03 16:12:24 +00002459 // Similar to the optimization above, if the Value being switched on is
2460 // known to be less than the Constant CR.LT, and the current Case Value
2461 // is CR.LT - 1, then we can branch directly to the target block for
2462 // the current Case Value, rather than emitting a RHS leaf node for it.
2463 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002464 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2465 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002466 FalseBB = RHSR.first->BB;
2467 } else {
2468 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2469 CurMF->insert(BBI, FalseBB);
2470 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002471
2472 // Put SV in a virtual register to make it available from the new blocks.
2473 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002474 }
2475
2476 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002477 // the LHS node if the value being switched on SV is less than C.
Dan Gohman575fad32008-09-03 16:12:24 +00002478 // Otherwise, branch to LHS.
Craig Topperc0196b12014-04-14 00:51:57 +00002479 CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002480
Dan Gohman7c0303a2010-04-19 22:41:47 +00002481 if (CR.CaseBB == SwitchBB)
2482 visitSwitchCase(CB, SwitchBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002483 else
2484 SwitchCases.push_back(CB);
2485
2486 return true;
2487}
2488
2489/// handleBitTestsSwitchCase - if current case range has few destination and
2490/// range span less, than machine word bitwidth, encode case range into series
2491/// of masks and emit bit tests with these masks.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002492bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2493 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002494 const Value* SV,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002495 MachineBasicBlock* Default,
Stephen Lin6d715e82013-07-06 21:44:25 +00002496 MachineBasicBlock* SwitchBB) {
Eric Christopherd9134482014-08-04 21:25:23 +00002497 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002498 EVT PTy = TLI->getPointerTy();
Owen Andersonc30530d2009-08-10 18:56:59 +00002499 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohman575fad32008-09-03 16:12:24 +00002500
2501 Case& FrontCase = *CR.Range.first;
2502 Case& BackCase = *(CR.Range.second-1);
2503
2504 // Get the MachineFunction which holds the current MBB. This is used when
2505 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002506 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002507
Anton Korobeynikovc94dbf52009-05-08 18:51:34 +00002508 // If target does not have legal shift left, do not emit bit tests at all.
Matt Arsenaultbbd24902013-10-21 19:24:15 +00002509 if (!TLI->isOperationLegal(ISD::SHL, PTy))
Anton Korobeynikovc94dbf52009-05-08 18:51:34 +00002510 return false;
2511
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002512 size_t numCmps = 0;
Dan Gohman575fad32008-09-03 16:12:24 +00002513 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2514 I!=E; ++I) {
2515 // Single case counts one, case range - two.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002516 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohman575fad32008-09-03 16:12:24 +00002517 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002518
Dan Gohman575fad32008-09-03 16:12:24 +00002519 // Count unique destinations
2520 SmallSet<MachineBasicBlock*, 4> Dests;
2521 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2522 Dests.insert(I->BB);
2523 if (Dests.size() > 3)
2524 // Don't bother the code below, if there are too much unique destinations
2525 return false;
2526 }
David Greene5730f202010-01-05 01:24:57 +00002527 DEBUG(dbgs() << "Total number of unique destinations: "
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00002528 << Dests.size() << '\n'
2529 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002530
Dan Gohman575fad32008-09-03 16:12:24 +00002531 // Compute span of values.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002532 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2533 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002534 APInt cmpRange = maxValue - minValue;
2535
David Greene5730f202010-01-05 01:24:57 +00002536 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002537 << "Low bound: " << minValue << '\n'
2538 << "High bound: " << maxValue << '\n');
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002539
Dan Gohman4ce1fb12010-04-08 23:03:40 +00002540 if (cmpRange.uge(IntPtrBits) ||
Dan Gohman575fad32008-09-03 16:12:24 +00002541 (!(Dests.size() == 1 && numCmps >= 3) &&
2542 !(Dests.size() == 2 && numCmps >= 5) &&
2543 !(Dests.size() >= 3 && numCmps >= 6)))
2544 return false;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002545
David Greene5730f202010-01-05 01:24:57 +00002546 DEBUG(dbgs() << "Emitting bit tests\n");
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002547 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2548
Dan Gohman575fad32008-09-03 16:12:24 +00002549 // Optimize the case where all the case values fit in a
2550 // word without having to subtract minValue. In this case,
2551 // we can optimize away the subtraction.
Bob Wilsone4077362013-09-09 19:14:35 +00002552 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002553 cmpRange = maxValue;
Dan Gohman575fad32008-09-03 16:12:24 +00002554 } else {
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002555 lowBound = minValue;
Dan Gohman575fad32008-09-03 16:12:24 +00002556 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002557
Dan Gohman575fad32008-09-03 16:12:24 +00002558 CaseBitsVector CasesBits;
2559 unsigned i, count = 0;
2560
2561 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2562 MachineBasicBlock* Dest = I->BB;
2563 for (i = 0; i < count; ++i)
2564 if (Dest == CasesBits[i].BB)
2565 break;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002566
Dan Gohman575fad32008-09-03 16:12:24 +00002567 if (i == count) {
2568 assert((count < 3) && "Too much destinations to test!");
Manman Rencf104462012-08-24 18:14:27 +00002569 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
Dan Gohman575fad32008-09-03 16:12:24 +00002570 count++;
2571 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002572
2573 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2574 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2575
2576 uint64_t lo = (lowValue - lowBound).getZExtValue();
2577 uint64_t hi = (highValue - lowBound).getZExtValue();
Manman Rencf104462012-08-24 18:14:27 +00002578 CasesBits[i].ExtraWeight += I->ExtraWeight;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002579
Dan Gohman575fad32008-09-03 16:12:24 +00002580 for (uint64_t j = lo; j <= hi; j++) {
2581 CasesBits[i].Mask |= 1ULL << j;
2582 CasesBits[i].Bits++;
2583 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002584
Dan Gohman575fad32008-09-03 16:12:24 +00002585 }
2586 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002587
Dan Gohman575fad32008-09-03 16:12:24 +00002588 BitTestInfo BTC;
2589
2590 // Figure out which block is immediately after the current one.
2591 MachineFunction::iterator BBI = CR.CaseBB;
2592 ++BBI;
2593
2594 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2595
David Greene5730f202010-01-05 01:24:57 +00002596 DEBUG(dbgs() << "Cases:\n");
Dan Gohman575fad32008-09-03 16:12:24 +00002597 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
David Greene5730f202010-01-05 01:24:57 +00002598 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002599 << ", Bits: " << CasesBits[i].Bits
2600 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002601
2602 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2603 CurMF->insert(BBI, CaseBB);
2604 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2605 CaseBB,
Manman Rencf104462012-08-24 18:14:27 +00002606 CasesBits[i].BB, CasesBits[i].ExtraWeight));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002607
2608 // Put SV in a virtual register to make it available from the new blocks.
2609 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002610 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002611
2612 BitTestBlock BTB(lowBound, cmpRange, SV,
Evan Chengac730dd2011-01-06 01:02:44 +00002613 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
Dan Gohman575fad32008-09-03 16:12:24 +00002614 CR.CaseBB, Default, BTC);
2615
Dan Gohman7c0303a2010-04-19 22:41:47 +00002616 if (CR.CaseBB == SwitchBB)
2617 visitBitTestHeader(BTB, SwitchBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002618
Dan Gohman575fad32008-09-03 16:12:24 +00002619 BitTestCases.push_back(BTB);
2620
2621 return true;
2622}
2623
Dan Gohman575fad32008-09-03 16:12:24 +00002624/// Clusterify - Transform simple list of Cases into list of CaseRange's
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002625size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2626 const SwitchInst& SI) {
Bob Wilsone4077362013-09-09 19:14:35 +00002627 size_t numCmps = 0;
Dan Gohman575fad32008-09-03 16:12:24 +00002628
Manman Rencf104462012-08-24 18:14:27 +00002629 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Dan Gohman575fad32008-09-03 16:12:24 +00002630 // Start with "simple" cases
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002631 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002632 i != e; ++i) {
2633 const BasicBlock *SuccBB = i.getCaseSuccessor();
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002634 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2635
Bob Wilsone4077362013-09-09 19:14:35 +00002636 uint32_t ExtraWeight =
2637 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2638
2639 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2640 SMBB, ExtraWeight));
Dan Gohman575fad32008-09-03 16:12:24 +00002641 }
Bob Wilsone4077362013-09-09 19:14:35 +00002642 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Stephen Lincfe7f352013-07-08 00:37:03 +00002643
Bob Wilsone4077362013-09-09 19:14:35 +00002644 // Merge case into clusters
2645 if (Cases.size() >= 2)
2646 // Must recompute end() each iteration because it may be
2647 // invalidated by erase if we hold on to it
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002648 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
Bob Wilsone4077362013-09-09 19:14:35 +00002649 J != Cases.end(); ) {
2650 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2651 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2652 MachineBasicBlock* nextBB = J->BB;
2653 MachineBasicBlock* currentBB = I->BB;
Stephen Lincfe7f352013-07-08 00:37:03 +00002654
Bob Wilsone4077362013-09-09 19:14:35 +00002655 // If the two neighboring cases go to the same destination, merge them
2656 // into a single case.
2657 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2658 I->High = J->High;
2659 I->ExtraWeight += J->ExtraWeight;
2660 J = Cases.erase(J);
2661 } else {
2662 I = J++;
2663 }
2664 }
Dan Gohman575fad32008-09-03 16:12:24 +00002665
Bob Wilsone4077362013-09-09 19:14:35 +00002666 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2667 if (I->Low != I->High)
2668 // A range counts double, since it requires two compares.
2669 ++numCmps;
Dan Gohman575fad32008-09-03 16:12:24 +00002670 }
2671
2672 return numCmps;
2673}
2674
Jakob Stoklund Olesen665aa6e2010-09-30 19:44:31 +00002675void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2676 MachineBasicBlock *Last) {
2677 // Update JTCases.
2678 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2679 if (JTCases[i].first.HeaderBB == First)
2680 JTCases[i].first.HeaderBB = Last;
2681
2682 // Update BitTestCases.
2683 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2684 if (BitTestCases[i].Parent == First)
2685 BitTestCases[i].Parent = Last;
2686}
2687
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002688void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00002689 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002690
Dan Gohman575fad32008-09-03 16:12:24 +00002691 // Figure out which block is immediately after the current one.
Craig Topperc0196b12014-04-14 00:51:57 +00002692 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00002693 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2694
2695 // If there is only the default destination, branch to it if it is not the
2696 // next basic block. Otherwise, just fall through.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002697 if (!SI.getNumCases()) {
Dan Gohman575fad32008-09-03 16:12:24 +00002698 // Update machine-CFG edges.
2699
2700 // If this is not a fall-through branch, emit the branch.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002701 SwitchMBB->addSuccessor(Default);
Bill Wendling954cb182010-01-28 21:51:40 +00002702 if (Default != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002703 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002704 MVT::Other, getControlRoot(),
2705 DAG.getBasicBlock(Default)));
Bill Wendling443d0722009-12-21 22:30:11 +00002706
Dan Gohman575fad32008-09-03 16:12:24 +00002707 return;
2708 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002709
Dan Gohman575fad32008-09-03 16:12:24 +00002710 // If there are any non-default case statements, create a vector of Cases
2711 // representing each one, and sort the vector so that we can efficiently
2712 // create a binary search tree from them.
2713 CaseVector Cases;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002714 size_t numCmps = Clusterify(Cases, SI);
David Greene5730f202010-01-05 01:24:57 +00002715 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002716 << ". Total compares: " << numCmps << '\n');
Duncan Sandsd278d352011-10-18 12:44:00 +00002717 (void)numCmps;
Dan Gohman575fad32008-09-03 16:12:24 +00002718
2719 // Get the Value to be switched on and default basic blocks, which will be
2720 // inserted into CaseBlock records, representing basic blocks in the binary
2721 // search tree.
Eli Friedman95031ed2011-09-29 20:21:17 +00002722 const Value *SV = SI.getCondition();
Dan Gohman575fad32008-09-03 16:12:24 +00002723
2724 // Push the initial CaseRec onto the worklist
2725 CaseRecVector WorkList;
Craig Topperc0196b12014-04-14 00:51:57 +00002726 WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002727 CaseRange(Cases.begin(),Cases.end())));
Dan Gohman575fad32008-09-03 16:12:24 +00002728
2729 while (!WorkList.empty()) {
2730 // Grab a record representing a case range to process off the worklist
2731 CaseRec CR = WorkList.back();
2732 WorkList.pop_back();
2733
Dan Gohman7c0303a2010-04-19 22:41:47 +00002734 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002735 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002736
Dan Gohman575fad32008-09-03 16:12:24 +00002737 // If the range has few cases (two or less) emit a series of specific
2738 // tests.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002739 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002740 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002741
Sebastian Popedb31fa2012-09-25 20:35:36 +00002742 // If the switch has more than N blocks, and is at least 40% dense, and the
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002743 // target supports indirect branches, then emit a jump table rather than
Dan Gohman575fad32008-09-03 16:12:24 +00002744 // lowering the switch to a binary tree of conditional branches.
Sebastian Popedb31fa2012-09-25 20:35:36 +00002745 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
Dan Gohman7c0303a2010-04-19 22:41:47 +00002746 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002747 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002748
Dan Gohman575fad32008-09-03 16:12:24 +00002749 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2750 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002751 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002752 }
2753}
2754
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002755void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00002756 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002757
Jakob Stoklund Olesen896428d2010-02-11 00:34:18 +00002758 // Update machine-CFG edges with unique successors.
Nadav Rotem33e034a2012-10-23 21:05:33 +00002759 SmallSet<BasicBlock*, 32> Done;
2760 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2761 BasicBlock *BB = I.getSuccessor(i);
2762 bool Inserted = Done.insert(BB);
2763 if (!Inserted)
2764 continue;
2765
2766 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
Jakub Staszak12a43bd2011-06-16 20:22:37 +00002767 addSuccessorWithWeight(IndirectBrMBB, Succ);
2768 }
Dan Gohmana5e078b2009-10-27 22:10:34 +00002769
Andrew Trickef9de2a2013-05-25 02:42:55 +00002770 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002771 MVT::Other, getControlRoot(),
2772 getValue(I.getAddress())));
Bill Wendling443d0722009-12-21 22:30:11 +00002773}
Dan Gohman575fad32008-09-03 16:12:24 +00002774
Yaron Kerend7ba46b2014-04-19 13:47:43 +00002775void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2776 if (DAG.getTarget().Options.TrapUnreachable)
2777 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2778}
2779
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002780void SelectionDAGBuilder::visitFSub(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002781 // -0.0 - X --> fneg
Chris Lattner229907c2011-07-18 04:54:35 +00002782 Type *Ty = I.getType();
Chris Lattner69229312011-02-15 00:14:00 +00002783 if (isa<Constant>(I.getOperand(0)) &&
2784 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2785 SDValue Op2 = getValue(I.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002786 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
Chris Lattner69229312011-02-15 00:14:00 +00002787 Op2.getValueType(), Op2));
2788 return;
Dan Gohman575fad32008-09-03 16:12:24 +00002789 }
Bill Wendling443d0722009-12-21 22:30:11 +00002790
Dan Gohmana5b96452009-06-04 22:49:04 +00002791 visitBinary(I, ISD::FSUB);
Dan Gohman575fad32008-09-03 16:12:24 +00002792}
2793
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002794void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
Dan Gohman575fad32008-09-03 16:12:24 +00002795 SDValue Op1 = getValue(I.getOperand(0));
2796 SDValue Op2 = getValue(I.getOperand(1));
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00002797
2798 bool nuw = false;
2799 bool nsw = false;
2800 bool exact = false;
2801 if (const OverflowingBinaryOperator *OFBinOp =
2802 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2803 nuw = OFBinOp->hasNoUnsignedWrap();
2804 nsw = OFBinOp->hasNoSignedWrap();
2805 }
2806 if (const PossiblyExactOperator *ExactOp =
2807 dyn_cast<const PossiblyExactOperator>(&I))
2808 exact = ExactOp->isExact();
2809
2810 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2811 Op1, Op2, nuw, nsw, exact);
2812 setValue(&I, BinNodeValue);
Dan Gohman575fad32008-09-03 16:12:24 +00002813}
2814
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002815void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
Dan Gohman575fad32008-09-03 16:12:24 +00002816 SDValue Op1 = getValue(I.getOperand(0));
2817 SDValue Op2 = getValue(I.getOperand(1));
Owen Andersonb2c80da2011-02-25 21:41:48 +00002818
Eric Christopherd9134482014-08-04 21:25:23 +00002819 EVT ShiftTy = TM.getSubtargetImpl()->getTargetLowering()->getShiftAmountTy(
2820 Op2.getValueType());
Owen Andersonb2c80da2011-02-25 21:41:48 +00002821
Chris Lattner2a720d92011-02-13 09:02:52 +00002822 // Coerce the shift amount to the right type if we can.
2823 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
Chris Lattnerd5f0b112011-02-13 09:10:56 +00002824 unsigned ShiftSize = ShiftTy.getSizeInBits();
2825 unsigned Op2Size = Op2.getValueType().getSizeInBits();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002826 SDLoc DL = getCurSDLoc();
Owen Andersonb2c80da2011-02-25 21:41:48 +00002827
Dan Gohman0e8d1992009-04-09 03:51:29 +00002828 // If the operand is smaller than the shift count type, promote it.
Chris Lattner2a720d92011-02-13 09:02:52 +00002829 if (ShiftSize > Op2Size)
2830 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002831
Dan Gohman0e8d1992009-04-09 03:51:29 +00002832 // If the operand is larger than the shift count type but the shift
2833 // count type has enough bits to represent any shift value, truncate
2834 // it now. This is a common case and it exposes the truncate to
2835 // optimization early.
Chris Lattner2a720d92011-02-13 09:02:52 +00002836 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2837 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2838 // Otherwise we'll need to temporarily settle for some other convenient
Chris Lattnere95d1952011-02-13 19:09:16 +00002839 // type. Type legalization will make adjustments once the shiftee is split.
Chris Lattner2a720d92011-02-13 09:02:52 +00002840 else
Chris Lattnere95d1952011-02-13 19:09:16 +00002841 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
Dan Gohman575fad32008-09-03 16:12:24 +00002842 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002843
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00002844 bool nuw = false;
2845 bool nsw = false;
2846 bool exact = false;
2847
2848 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2849
2850 if (const OverflowingBinaryOperator *OFBinOp =
2851 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2852 nuw = OFBinOp->hasNoUnsignedWrap();
2853 nsw = OFBinOp->hasNoSignedWrap();
2854 }
2855 if (const PossiblyExactOperator *ExactOp =
2856 dyn_cast<const PossiblyExactOperator>(&I))
2857 exact = ExactOp->isExact();
2858 }
2859
2860 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2861 nuw, nsw, exact);
2862 setValue(&I, Res);
Dan Gohman575fad32008-09-03 16:12:24 +00002863}
2864
Benjamin Kramer9960a252011-07-08 10:31:30 +00002865void SelectionDAGBuilder::visitSDiv(const User &I) {
Benjamin Kramer9960a252011-07-08 10:31:30 +00002866 SDValue Op1 = getValue(I.getOperand(0));
2867 SDValue Op2 = getValue(I.getOperand(1));
2868
2869 // Turn exact SDivs into multiplications.
2870 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2871 // exact bit.
Benjamin Kramer2bb8b262011-07-08 12:08:24 +00002872 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2873 !isa<ConstantSDNode>(Op1) &&
Benjamin Kramer9960a252011-07-08 10:31:30 +00002874 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
Eric Christopherd9134482014-08-04 21:25:23 +00002875 setValue(&I, TM.getSubtargetImpl()->getTargetLowering()->BuildExactSDIV(
2876 Op1, Op2, getCurSDLoc(), DAG));
Benjamin Kramer9960a252011-07-08 10:31:30 +00002877 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00002878 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
Benjamin Kramer9960a252011-07-08 10:31:30 +00002879 Op1, Op2));
2880}
2881
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002882void SelectionDAGBuilder::visitICmp(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002883 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002884 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002885 predicate = IC->getPredicate();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002886 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002887 predicate = ICmpInst::Predicate(IC->getPredicate());
2888 SDValue Op1 = getValue(I.getOperand(0));
2889 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman293abcc2008-10-17 18:18:45 +00002890 ISD::CondCode Opcode = getICmpCondCode(predicate);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00002891
Eric Christopherd9134482014-08-04 21:25:23 +00002892 EVT DestVT =
2893 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002894 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohman575fad32008-09-03 16:12:24 +00002895}
2896
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002897void SelectionDAGBuilder::visitFCmp(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002898 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002899 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002900 predicate = FC->getPredicate();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002901 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002902 predicate = FCmpInst::Predicate(FC->getPredicate());
2903 SDValue Op1 = getValue(I.getOperand(0));
2904 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman293abcc2008-10-17 18:18:45 +00002905 ISD::CondCode Condition = getFCmpCondCode(predicate);
Nick Lewycky50f02cb2011-12-02 22:16:29 +00002906 if (TM.Options.NoNaNsFPMath)
2907 Condition = getFCmpCodeWithoutNaN(Condition);
Eric Christopherd9134482014-08-04 21:25:23 +00002908 EVT DestVT =
2909 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002910 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
Dan Gohman575fad32008-09-03 16:12:24 +00002911}
2912
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002913void SelectionDAGBuilder::visitSelect(const User &I) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002914 SmallVector<EVT, 4> ValueVTs;
Eric Christopherd9134482014-08-04 21:25:23 +00002915 ComputeValueVTs(*TM.getSubtargetImpl()->getTargetLowering(), I.getType(),
2916 ValueVTs);
Dan Gohman8b44b882008-10-21 20:00:42 +00002917 unsigned NumValues = ValueVTs.size();
Bill Wendling443d0722009-12-21 22:30:11 +00002918 if (NumValues == 0) return;
Dan Gohman8b44b882008-10-21 20:00:42 +00002919
Bill Wendling443d0722009-12-21 22:30:11 +00002920 SmallVector<SDValue, 4> Values(NumValues);
2921 SDValue Cond = getValue(I.getOperand(0));
2922 SDValue TrueVal = getValue(I.getOperand(1));
2923 SDValue FalseVal = getValue(I.getOperand(2));
Duncan Sandsf2641e12011-09-06 19:07:46 +00002924 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2925 ISD::VSELECT : ISD::SELECT;
Dan Gohman8b44b882008-10-21 20:00:42 +00002926
Bill Wendling954cb182010-01-28 21:51:40 +00002927 for (unsigned i = 0; i != NumValues; ++i)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002928 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
Duncan Sandsf2641e12011-09-06 19:07:46 +00002929 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
Chris Lattner53ebf8a2010-03-12 07:15:36 +00002930 Cond,
Bill Wendling443d0722009-12-21 22:30:11 +00002931 SDValue(TrueVal.getNode(),
2932 TrueVal.getResNo() + i),
2933 SDValue(FalseVal.getNode(),
2934 FalseVal.getResNo() + i));
2935
Andrew Trickef9de2a2013-05-25 02:42:55 +00002936 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00002937 DAG.getVTList(ValueVTs), Values));
Bill Wendling443d0722009-12-21 22:30:11 +00002938}
Dan Gohman575fad32008-09-03 16:12:24 +00002939
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002940void SelectionDAGBuilder::visitTrunc(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002941 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2942 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00002943 EVT DestVT =
2944 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002945 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002946}
2947
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002948void SelectionDAGBuilder::visitZExt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002949 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2950 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2951 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00002952 EVT DestVT =
2953 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002954 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002955}
2956
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002957void SelectionDAGBuilder::visitSExt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002958 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2959 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2960 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00002961 EVT DestVT =
2962 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002963 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002964}
2965
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002966void SelectionDAGBuilder::visitFPTrunc(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002967 // FPTrunc is never a no-op cast, no need to check
2968 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00002969 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002970 EVT DestVT = TLI->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002971 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(),
Pete Coopere3d305a2012-01-17 01:54:07 +00002972 DestVT, N,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002973 DAG.getTargetConstant(0, TLI->getPointerTy())));
Dan Gohman575fad32008-09-03 16:12:24 +00002974}
2975
Stephen Lin6d715e82013-07-06 21:44:25 +00002976void SelectionDAGBuilder::visitFPExt(const User &I) {
Hal Finkelbab66782011-10-18 03:51:57 +00002977 // FPExt is never a no-op cast, no need to check
Dan Gohman575fad32008-09-03 16:12:24 +00002978 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00002979 EVT DestVT =
2980 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002981 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002982}
2983
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002984void SelectionDAGBuilder::visitFPToUI(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002985 // FPToUI is never a no-op cast, no need to check
2986 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00002987 EVT DestVT =
2988 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002989 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002990}
2991
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002992void SelectionDAGBuilder::visitFPToSI(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002993 // FPToSI is never a no-op cast, no need to check
2994 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00002995 EVT DestVT =
2996 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002997 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002998}
2999
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003000void SelectionDAGBuilder::visitUIToFP(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003001 // UIToFP is never a no-op cast, no need to check
3002 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00003003 EVT DestVT =
3004 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003005 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003006}
3007
Stephen Lin6d715e82013-07-06 21:44:25 +00003008void SelectionDAGBuilder::visitSIToFP(const User &I) {
Bill Wendling6c87bfc2008-10-19 20:34:04 +00003009 // SIToFP is never a no-op cast, no need to check
Dan Gohman575fad32008-09-03 16:12:24 +00003010 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00003011 EVT DestVT =
3012 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003013 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003014}
3015
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003016void SelectionDAGBuilder::visitPtrToInt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003017 // What to do depends on the size of the integer and the size of the pointer.
3018 // We can either truncate, zero extend, or no-op, accordingly.
3019 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00003020 EVT DestVT =
3021 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003022 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
Dan Gohman575fad32008-09-03 16:12:24 +00003023}
3024
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003025void SelectionDAGBuilder::visitIntToPtr(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003026 // What to do depends on the size of the integer and the size of the pointer.
3027 // We can either truncate, zero extend, or no-op, accordingly.
3028 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00003029 EVT DestVT =
3030 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003031 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
Dan Gohman575fad32008-09-03 16:12:24 +00003032}
3033
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003034void SelectionDAGBuilder::visitBitCast(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003035 SDValue N = getValue(I.getOperand(0));
Eric Christopherd9134482014-08-04 21:25:23 +00003036 EVT DestVT =
3037 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Dan Gohman575fad32008-09-03 16:12:24 +00003038
Bill Wendling443d0722009-12-21 22:30:11 +00003039 // BitCast assures us that source and destination are the same size so this is
Wesley Peck527da1b2010-11-23 03:31:01 +00003040 // either a BITCAST or a no-op.
Bill Wendling954cb182010-01-28 21:51:40 +00003041 if (DestVT != N.getValueType())
Andrew Trickef9de2a2013-05-25 02:42:55 +00003042 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00003043 DestVT, N)); // convert types.
Juergen Ributzka2b97f9b2014-02-13 04:19:26 +00003044 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3045 // might fold any kind of constant expression to an integer constant and that
3046 // is not what we are looking for. Only regcognize a bitcast of a genuine
3047 // constant integer as an opaque constant.
3048 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3049 setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
3050 /*isOpaque*/true));
Bill Wendling954cb182010-01-28 21:51:40 +00003051 else
Bill Wendling443d0722009-12-21 22:30:11 +00003052 setValue(&I, N); // noop cast.
Dan Gohman575fad32008-09-03 16:12:24 +00003053}
3054
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003055void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3056 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3057 const Value *SV = I.getOperand(0);
3058 SDValue N = getValue(SV);
Eric Christopherd9134482014-08-04 21:25:23 +00003059 EVT DestVT =
3060 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003061
3062 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3063 unsigned DestAS = I.getType()->getPointerAddressSpace();
3064
3065 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3066 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3067
3068 setValue(&I, N);
3069}
3070
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003071void SelectionDAGBuilder::visitInsertElement(const User &I) {
Tom Stellardd42c5942013-08-05 22:22:01 +00003072 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +00003073 SDValue InVec = getValue(I.getOperand(0));
3074 SDValue InVal = getValue(I.getOperand(1));
Tom Stellardd42c5942013-08-05 22:22:01 +00003075 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3076 getCurSDLoc(), TLI.getVectorIdxTy());
Eric Christopherd9134482014-08-04 21:25:23 +00003077 setValue(&I,
3078 DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3079 TM.getSubtargetImpl()->getTargetLowering()->getValueType(
3080 I.getType()),
3081 InVec, InVal, InIdx));
Dan Gohman575fad32008-09-03 16:12:24 +00003082}
3083
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003084void SelectionDAGBuilder::visitExtractElement(const User &I) {
Tom Stellardd42c5942013-08-05 22:22:01 +00003085 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +00003086 SDValue InVec = getValue(I.getOperand(0));
Tom Stellardd42c5942013-08-05 22:22:01 +00003087 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3088 getCurSDLoc(), TLI.getVectorIdxTy());
Eric Christopherd9134482014-08-04 21:25:23 +00003089 setValue(&I,
3090 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3091 TM.getSubtargetImpl()->getTargetLowering()->getValueType(
3092 I.getType()),
3093 InVec, InIdx));
Dan Gohman575fad32008-09-03 16:12:24 +00003094}
3095
Craig Topperf726e152012-01-04 09:23:09 +00003096// Utility for visitShuffleVector - Return true if every element in Mask,
Benjamin Kramerbde91762012-06-02 10:20:22 +00003097// beginning from position Pos and ending in Pos+Size, falls within the
Craig Topperf726e152012-01-04 09:23:09 +00003098// specified sequential range [L, L+Pos). or is undef.
3099static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
Craig Topper3ef01cd2012-04-11 03:06:35 +00003100 unsigned Pos, unsigned Size, int Low) {
3101 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
Craig Topperf726e152012-01-04 09:23:09 +00003102 if (Mask[i] >= 0 && Mask[i] != Low)
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003103 return false;
Mon P Wang25f01062008-11-10 04:46:22 +00003104 return true;
3105}
3106
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003107void SelectionDAGBuilder::visitShuffleVector(const User &I) {
Mon P Wangc3113602008-11-21 04:25:21 +00003108 SDValue Src1 = getValue(I.getOperand(0));
3109 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohman575fad32008-09-03 16:12:24 +00003110
Chris Lattnercf129702012-01-26 02:51:13 +00003111 SmallVector<int, 8> Mask;
3112 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3113 unsigned MaskNumElts = Mask.size();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003114
Eric Christopherd9134482014-08-04 21:25:23 +00003115 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003116 EVT VT = TLI->getValueType(I.getType());
Owen Anderson53aa7a92009-08-10 22:56:29 +00003117 EVT SrcVT = Src1.getValueType();
Nate Begeman5f829d82009-04-29 05:20:52 +00003118 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wang25f01062008-11-10 04:46:22 +00003119
Mon P Wang7a824742008-11-16 05:06:27 +00003120 if (SrcNumElts == MaskNumElts) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003121 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003122 &Mask[0]));
Mon P Wang25f01062008-11-10 04:46:22 +00003123 return;
3124 }
3125
3126 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wang7a824742008-11-16 05:06:27 +00003127 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3128 // Mask is longer than the source vectors and is a multiple of the source
3129 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wangc3113602008-11-21 04:25:21 +00003130 // lengths match.
Craig Topperf726e152012-01-04 09:23:09 +00003131 if (SrcNumElts*2 == MaskNumElts) {
3132 // First check for Src1 in low and Src2 in high
3133 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3134 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3135 // The shuffle is concatenating two vectors together.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003136 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
Craig Topperf726e152012-01-04 09:23:09 +00003137 VT, Src1, Src2));
3138 return;
3139 }
3140 // Then check for Src2 in low and Src1 in high
3141 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3142 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3143 // The shuffle is concatenating two vectors together.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003144 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
Craig Topperf726e152012-01-04 09:23:09 +00003145 VT, Src2, Src1));
3146 return;
3147 }
Mon P Wang25f01062008-11-10 04:46:22 +00003148 }
3149
Mon P Wang7a824742008-11-16 05:06:27 +00003150 // Pad both vectors with undefs to make them the same length as the mask.
3151 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003152 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3153 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesen84935752009-02-06 23:05:02 +00003154 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wang25f01062008-11-10 04:46:22 +00003155
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003156 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3157 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wangc3113602008-11-21 04:25:21 +00003158 MOps1[0] = Src1;
3159 MOps2[0] = Src2;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003160
3161 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Craig Topper48d114b2014-04-26 18:35:24 +00003162 getCurSDLoc(), VT, MOps1);
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003163 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Craig Topper48d114b2014-04-26 18:35:24 +00003164 getCurSDLoc(), VT, MOps2);
Mon P Wangc3113602008-11-21 04:25:21 +00003165
Mon P Wang25f01062008-11-10 04:46:22 +00003166 // Readjust mask for new input vector length.
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003167 SmallVector<int, 8> MappedOps;
Nate Begeman5f829d82009-04-29 05:20:52 +00003168 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003169 int Idx = Mask[i];
Craig Topper3ef01cd2012-04-11 03:06:35 +00003170 if (Idx >= (int)SrcNumElts)
3171 Idx -= SrcNumElts - MaskNumElts;
3172 MappedOps.push_back(Idx);
Mon P Wang25f01062008-11-10 04:46:22 +00003173 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003174
Andrew Trickef9de2a2013-05-25 02:42:55 +00003175 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003176 &MappedOps[0]));
Mon P Wang25f01062008-11-10 04:46:22 +00003177 return;
3178 }
3179
Mon P Wang7a824742008-11-16 05:06:27 +00003180 if (SrcNumElts > MaskNumElts) {
Mon P Wang7a824742008-11-16 05:06:27 +00003181 // Analyze the access pattern of the vector to see if we can extract
3182 // two subvectors and do the shuffle. The analysis is done by calculating
3183 // the range of elements the mask access on both vectors.
Craig Topper6148fe62012-04-08 23:15:04 +00003184 int MinRange[2] = { static_cast<int>(SrcNumElts),
3185 static_cast<int>(SrcNumElts)};
Mon P Wang7a824742008-11-16 05:06:27 +00003186 int MaxRange[2] = {-1, -1};
3187
Nate Begeman5f829d82009-04-29 05:20:52 +00003188 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003189 int Idx = Mask[i];
Craig Topper6148fe62012-04-08 23:15:04 +00003190 unsigned Input = 0;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003191 if (Idx < 0)
3192 continue;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003193
Nate Begeman5f829d82009-04-29 05:20:52 +00003194 if (Idx >= (int)SrcNumElts) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003195 Input = 1;
3196 Idx -= SrcNumElts;
Mon P Wang25f01062008-11-10 04:46:22 +00003197 }
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003198 if (Idx > MaxRange[Input])
3199 MaxRange[Input] = Idx;
3200 if (Idx < MinRange[Input])
3201 MinRange[Input] = Idx;
Mon P Wang25f01062008-11-10 04:46:22 +00003202 }
Mon P Wang25f01062008-11-10 04:46:22 +00003203
Mon P Wang7a824742008-11-16 05:06:27 +00003204 // Check if the access is smaller than the vector size and can we find
3205 // a reasonable extract index.
Craig Topper6148fe62012-04-08 23:15:04 +00003206 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3207 // Extract.
Mon P Wang7a824742008-11-16 05:06:27 +00003208 int StartIdx[2]; // StartIdx to extract from
Craig Topper6148fe62012-04-08 23:15:04 +00003209 for (unsigned Input = 0; Input < 2; ++Input) {
3210 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
Mon P Wang7a824742008-11-16 05:06:27 +00003211 RangeUse[Input] = 0; // Unused
3212 StartIdx[Input] = 0;
Craig Topperc8e2d912012-04-08 17:53:33 +00003213 continue;
Mon P Wangc3113602008-11-21 04:25:21 +00003214 }
Craig Topperc8e2d912012-04-08 17:53:33 +00003215
3216 // Find a good start index that is a multiple of the mask length. Then
3217 // see if the rest of the elements are in range.
3218 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3219 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3220 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3221 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wang7a824742008-11-16 05:06:27 +00003222 }
3223
Bill Wendlingdff54ef2009-08-21 18:16:06 +00003224 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Bill Wendling954cb182010-01-28 21:51:40 +00003225 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wang7a824742008-11-16 05:06:27 +00003226 return;
3227 }
Craig Topper6148fe62012-04-08 23:15:04 +00003228 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
Mon P Wang7a824742008-11-16 05:06:27 +00003229 // Extract appropriate subvector and generate a vector shuffle
Craig Topper6148fe62012-04-08 23:15:04 +00003230 for (unsigned Input = 0; Input < 2; ++Input) {
Bill Wendlingc6b47342009-12-21 23:47:40 +00003231 SDValue &Src = Input == 0 ? Src1 : Src2;
Bill Wendlingfff99f02009-12-21 22:42:14 +00003232 if (RangeUse[Input] == 0)
Dale Johannesen84935752009-02-06 23:05:02 +00003233 Src = DAG.getUNDEF(VT);
Bill Wendlingfff99f02009-12-21 22:42:14 +00003234 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00003235 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT,
Tom Stellardd42c5942013-08-05 22:22:01 +00003236 Src, DAG.getConstant(StartIdx[Input],
3237 TLI->getVectorIdxTy()));
Mon P Wang25f01062008-11-10 04:46:22 +00003238 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003239
Mon P Wang7a824742008-11-16 05:06:27 +00003240 // Calculate new mask.
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003241 SmallVector<int, 8> MappedOps;
Nate Begeman5f829d82009-04-29 05:20:52 +00003242 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003243 int Idx = Mask[i];
Craig Topper3ef01cd2012-04-11 03:06:35 +00003244 if (Idx >= 0) {
3245 if (Idx < (int)SrcNumElts)
3246 Idx -= StartIdx[0];
3247 else
3248 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3249 }
3250 MappedOps.push_back(Idx);
Mon P Wang7a824742008-11-16 05:06:27 +00003251 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003252
Andrew Trickef9de2a2013-05-25 02:42:55 +00003253 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003254 &MappedOps[0]));
Mon P Wang7a824742008-11-16 05:06:27 +00003255 return;
Mon P Wang25f01062008-11-10 04:46:22 +00003256 }
3257 }
3258
Mon P Wang7a824742008-11-16 05:06:27 +00003259 // We can't use either concat vectors or extract subvectors so fall back to
3260 // replacing the shuffle with extract and build vector.
3261 // to insert and build vector.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003262 EVT EltVT = VT.getVectorElementType();
Tom Stellardd42c5942013-08-05 22:22:01 +00003263 EVT IdxVT = TLI->getVectorIdxTy();
Mon P Wang25f01062008-11-10 04:46:22 +00003264 SmallVector<SDValue,8> Ops;
Nate Begeman5f829d82009-04-29 05:20:52 +00003265 for (unsigned i = 0; i != MaskNumElts; ++i) {
Craig Topper3ef01cd2012-04-11 03:06:35 +00003266 int Idx = Mask[i];
3267 SDValue Res;
3268
3269 if (Idx < 0) {
3270 Res = DAG.getUNDEF(EltVT);
Mon P Wang25f01062008-11-10 04:46:22 +00003271 } else {
Craig Topper3ef01cd2012-04-11 03:06:35 +00003272 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3273 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
Bill Wendlingfff99f02009-12-21 22:42:14 +00003274
Andrew Trickef9de2a2013-05-25 02:42:55 +00003275 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
Tom Stellardd42c5942013-08-05 22:22:01 +00003276 EltVT, Src, DAG.getConstant(Idx, IdxVT));
Mon P Wang25f01062008-11-10 04:46:22 +00003277 }
Craig Topper3ef01cd2012-04-11 03:06:35 +00003278
3279 Ops.push_back(Res);
Mon P Wang25f01062008-11-10 04:46:22 +00003280 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003281
Craig Topper48d114b2014-04-26 18:35:24 +00003282 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops));
Dan Gohman575fad32008-09-03 16:12:24 +00003283}
3284
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003285void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003286 const Value *Op0 = I.getOperand(0);
3287 const Value *Op1 = I.getOperand(1);
Chris Lattner229907c2011-07-18 04:54:35 +00003288 Type *AggTy = I.getType();
3289 Type *ValTy = Op1->getType();
Dan Gohman575fad32008-09-03 16:12:24 +00003290 bool IntoUndef = isa<UndefValue>(Op0);
3291 bool FromUndef = isa<UndefValue>(Op1);
3292
Jay Foad57aa6362011-07-13 10:26:04 +00003293 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohman575fad32008-09-03 16:12:24 +00003294
Eric Christopherd9134482014-08-04 21:25:23 +00003295 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Owen Anderson53aa7a92009-08-10 22:56:29 +00003296 SmallVector<EVT, 4> AggValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003297 ComputeValueVTs(*TLI, AggTy, AggValueVTs);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003298 SmallVector<EVT, 4> ValValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003299 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00003300
3301 unsigned NumAggValues = AggValueVTs.size();
3302 unsigned NumValValues = ValValueVTs.size();
3303 SmallVector<SDValue, 4> Values(NumAggValues);
3304
3305 SDValue Agg = getValue(Op0);
Dan Gohman575fad32008-09-03 16:12:24 +00003306 unsigned i = 0;
3307 // Copy the beginning value(s) from the original aggregate.
3308 for (; i != LinearIndex; ++i)
Dale Johannesen84935752009-02-06 23:05:02 +00003309 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohman575fad32008-09-03 16:12:24 +00003310 SDValue(Agg.getNode(), Agg.getResNo() + i);
3311 // Copy values from the inserted value(s).
Rafael Espindolae53b7d12011-05-13 15:18:06 +00003312 if (NumValValues) {
3313 SDValue Val = getValue(Op1);
3314 for (; i != LinearIndex + NumValValues; ++i)
3315 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3316 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3317 }
Dan Gohman575fad32008-09-03 16:12:24 +00003318 // Copy remaining value(s) from the original aggregate.
3319 for (; i != NumAggValues; ++i)
Dale Johannesen84935752009-02-06 23:05:02 +00003320 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohman575fad32008-09-03 16:12:24 +00003321 SDValue(Agg.getNode(), Agg.getResNo() + i);
3322
Andrew Trickef9de2a2013-05-25 02:42:55 +00003323 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00003324 DAG.getVTList(AggValueVTs), Values));
Dan Gohman575fad32008-09-03 16:12:24 +00003325}
3326
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003327void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003328 const Value *Op0 = I.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003329 Type *AggTy = Op0->getType();
3330 Type *ValTy = I.getType();
Dan Gohman575fad32008-09-03 16:12:24 +00003331 bool OutOfUndef = isa<UndefValue>(Op0);
3332
Jay Foad57aa6362011-07-13 10:26:04 +00003333 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohman575fad32008-09-03 16:12:24 +00003334
Eric Christopherd9134482014-08-04 21:25:23 +00003335 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Owen Anderson53aa7a92009-08-10 22:56:29 +00003336 SmallVector<EVT, 4> ValValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003337 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00003338
3339 unsigned NumValValues = ValValueVTs.size();
Rafael Espindolae53b7d12011-05-13 15:18:06 +00003340
3341 // Ignore a extractvalue that produces an empty object
3342 if (!NumValValues) {
3343 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3344 return;
3345 }
3346
Dan Gohman575fad32008-09-03 16:12:24 +00003347 SmallVector<SDValue, 4> Values(NumValValues);
3348
3349 SDValue Agg = getValue(Op0);
3350 // Copy out the selected value(s).
3351 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3352 Values[i - LinearIndex] =
Bill Wendling165b45d2008-11-20 07:24:30 +00003353 OutOfUndef ?
Dale Johannesen84935752009-02-06 23:05:02 +00003354 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendling165b45d2008-11-20 07:24:30 +00003355 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohman575fad32008-09-03 16:12:24 +00003356
Andrew Trickef9de2a2013-05-25 02:42:55 +00003357 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00003358 DAG.getVTList(ValValueVTs), Values));
Dan Gohman575fad32008-09-03 16:12:24 +00003359}
3360
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003361void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
Matt Arsenaultb7689122013-10-21 20:03:54 +00003362 Value *Op0 = I.getOperand(0);
Nadav Rotem1d666092012-02-28 14:13:19 +00003363 // Note that the pointer operand may be a vector of pointers. Take the scalar
3364 // element which holds a pointer.
Matt Arsenaultb7689122013-10-21 20:03:54 +00003365 Type *Ty = Op0->getType()->getScalarType();
3366 unsigned AS = Ty->getPointerAddressSpace();
3367 SDValue N = getValue(Op0);
Dan Gohman575fad32008-09-03 16:12:24 +00003368
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003369 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
Dan Gohman575fad32008-09-03 16:12:24 +00003370 OI != E; ++OI) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003371 const Value *Idx = *OI;
Chris Lattner229907c2011-07-18 04:54:35 +00003372 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003373 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
Dan Gohman575fad32008-09-03 16:12:24 +00003374 if (Field) {
3375 // N = N + Offset
Rafael Espindola5f57f462014-02-21 18:34:28 +00003376 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003377 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003378 DAG.getConstant(Offset, N.getValueType()));
Dan Gohman575fad32008-09-03 16:12:24 +00003379 }
Bill Wendlinge79105b2009-12-21 23:10:19 +00003380
Dan Gohman575fad32008-09-03 16:12:24 +00003381 Ty = StTy->getElementType(Field);
3382 } else {
3383 Ty = cast<SequentialType>(Ty)->getElementType();
3384
3385 // If this is a constant subscript, handle it quickly.
Eric Christopherd9134482014-08-04 21:25:23 +00003386 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003387 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Dan Gohmanf1d83042010-06-18 14:22:04 +00003388 if (CI->isZero()) continue;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003389 uint64_t Offs =
Rafael Espindola5f57f462014-02-21 18:34:28 +00003390 DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Chengfe174df2009-02-09 21:01:06 +00003391 SDValue OffsVal;
Tom Stellardfd155822013-08-26 15:05:36 +00003392 EVT PTy = TLI->getPointerTy(AS);
Owen Andersonc30530d2009-08-10 18:56:59 +00003393 unsigned PtrBits = PTy.getSizeInBits();
Bill Wendlinge79105b2009-12-21 23:10:19 +00003394 if (PtrBits < 64)
Tom Stellardfd155822013-08-26 15:05:36 +00003395 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
Owen Anderson9f944592009-08-11 20:47:22 +00003396 DAG.getConstant(Offs, MVT::i64));
Bill Wendlinge79105b2009-12-21 23:10:19 +00003397 else
Tom Stellardfd155822013-08-26 15:05:36 +00003398 OffsVal = DAG.getConstant(Offs, PTy);
Bill Wendlinge79105b2009-12-21 23:10:19 +00003399
Andrew Trickef9de2a2013-05-25 02:42:55 +00003400 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
Evan Cheng020588c2009-02-09 20:54:38 +00003401 OffsVal);
Dan Gohman575fad32008-09-03 16:12:24 +00003402 continue;
3403 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003404
Dan Gohman575fad32008-09-03 16:12:24 +00003405 // N = N + Idx * ElementSize;
Tom Stellardfd155822013-08-26 15:05:36 +00003406 APInt ElementSize = APInt(TLI->getPointerSizeInBits(AS),
Rafael Espindola5f57f462014-02-21 18:34:28 +00003407 DL->getTypeAllocSize(Ty));
Dan Gohman575fad32008-09-03 16:12:24 +00003408 SDValue IdxN = getValue(Idx);
3409
3410 // If the index is smaller or larger than intptr_t, truncate or extend
3411 // it.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003412 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
Dan Gohman575fad32008-09-03 16:12:24 +00003413
3414 // If this is a multiply by a power of two, turn it into a shl
3415 // immediately. This is a very common case.
3416 if (ElementSize != 1) {
Dan Gohman4ef112b2009-10-23 17:57:43 +00003417 if (ElementSize.isPowerOf2()) {
3418 unsigned Amt = ElementSize.logBase2();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003419 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003420 N.getValueType(), IdxN,
Nadav Rotem3924cb02011-12-05 06:29:09 +00003421 DAG.getConstant(Amt, IdxN.getValueType()));
Dan Gohman575fad32008-09-03 16:12:24 +00003422 } else {
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003423 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003424 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003425 N.getValueType(), IdxN, Scale);
Dan Gohman575fad32008-09-03 16:12:24 +00003426 }
3427 }
3428
Andrew Trickef9de2a2013-05-25 02:42:55 +00003429 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003430 N.getValueType(), N, IdxN);
Dan Gohman575fad32008-09-03 16:12:24 +00003431 }
3432 }
Bill Wendlinge79105b2009-12-21 23:10:19 +00003433
Dan Gohman575fad32008-09-03 16:12:24 +00003434 setValue(&I, N);
3435}
3436
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003437void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003438 // If this is a fixed sized alloca in the entry block of the function,
3439 // allocate it statically on the stack.
3440 if (FuncInfo.StaticAllocaMap.count(&I))
3441 return; // getValue will auto-populate this.
3442
Chris Lattner229907c2011-07-18 04:54:35 +00003443 Type *Ty = I.getAllocatedType();
Eric Christopherd9134482014-08-04 21:25:23 +00003444 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003445 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
Dan Gohman575fad32008-09-03 16:12:24 +00003446 unsigned Align =
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003447 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
Dan Gohman575fad32008-09-03 16:12:24 +00003448 I.getAlignment());
3449
3450 SDValue AllocSize = getValue(I.getArraySize());
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003451
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003452 EVT IntPtr = TLI->getPointerTy();
Dan Gohman2140a742010-05-28 01:14:11 +00003453 if (AllocSize.getValueType() != IntPtr)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003454 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
Dan Gohman2140a742010-05-28 01:14:11 +00003455
Andrew Trickef9de2a2013-05-25 02:42:55 +00003456 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
Dan Gohman2140a742010-05-28 01:14:11 +00003457 AllocSize,
3458 DAG.getConstant(TySize, IntPtr));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003459
Dan Gohman575fad32008-09-03 16:12:24 +00003460 // Handle alignment. If the requested alignment is less than or equal to
3461 // the stack alignment, ignore it. If the size is greater than or equal to
3462 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Eric Christopherd9134482014-08-04 21:25:23 +00003463 unsigned StackAlign =
3464 TM.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
Dan Gohman575fad32008-09-03 16:12:24 +00003465 if (Align <= StackAlign)
3466 Align = 0;
3467
3468 // Round the size of the allocation up to the stack alignment size
3469 // by add SA-1 to the size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003470 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003471 AllocSize.getValueType(), AllocSize,
Dan Gohman575fad32008-09-03 16:12:24 +00003472 DAG.getIntPtrConstant(StackAlign-1));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003473
Dan Gohman575fad32008-09-03 16:12:24 +00003474 // Mask out the low bits for alignment purposes.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003475 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003476 AllocSize.getValueType(), AllocSize,
Dan Gohman575fad32008-09-03 16:12:24 +00003477 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3478
3479 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson9f944592009-08-11 20:47:22 +00003480 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Craig Topper48d114b2014-04-26 18:35:24 +00003481 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), VTs, Ops);
Dan Gohman575fad32008-09-03 16:12:24 +00003482 setValue(&I, DSA);
3483 DAG.setRoot(DSA.getValue(1));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003484
Hans Wennborgacb842d2014-03-05 02:43:26 +00003485 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
Dan Gohman575fad32008-09-03 16:12:24 +00003486}
3487
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003488void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
Eli Friedman342e8df2011-08-24 20:50:09 +00003489 if (I.isAtomic())
3490 return visitAtomicLoad(I);
3491
Dan Gohman575fad32008-09-03 16:12:24 +00003492 const Value *SV = I.getOperand(0);
3493 SDValue Ptr = getValue(SV);
3494
Chris Lattner229907c2011-07-18 04:54:35 +00003495 Type *Ty = I.getType();
David Greene39c6d012010-02-15 17:00:31 +00003496
Dan Gohman575fad32008-09-03 16:12:24 +00003497 bool isVolatile = I.isVolatile();
Craig Topperc0196b12014-04-14 00:51:57 +00003498 bool isNonTemporal = I.getMetadata("nontemporal") != nullptr;
3499 bool isInvariant = I.getMetadata("invariant.load") != nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00003500 unsigned Alignment = I.getAlignment();
Hal Finkelcc39b672014-07-24 12:16:19 +00003501
3502 AAMDNodes AAInfo;
3503 I.getAAMetadata(AAInfo);
Rafael Espindola80c540e2012-03-31 18:14:00 +00003504 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
Dan Gohman575fad32008-09-03 16:12:24 +00003505
Owen Anderson53aa7a92009-08-10 22:56:29 +00003506 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00003507 SmallVector<uint64_t, 4> Offsets;
Eric Christopherd9134482014-08-04 21:25:23 +00003508 ComputeValueVTs(*TM.getSubtargetImpl()->getTargetLowering(), Ty, ValueVTs,
3509 &Offsets);
Dan Gohman575fad32008-09-03 16:12:24 +00003510 unsigned NumValues = ValueVTs.size();
3511 if (NumValues == 0)
3512 return;
3513
3514 SDValue Root;
3515 bool ConstantMemory = false;
Richard Sandiford9afe6132013-12-10 10:36:34 +00003516 if (isVolatile || NumValues > MaxParallelChains)
Dan Gohman575fad32008-09-03 16:12:24 +00003517 // Serialize volatile loads with other side effects.
3518 Root = getRoot();
Dan Gohmana94cc6d2010-10-20 00:31:05 +00003519 else if (AA->pointsToConstantMemory(
Hal Finkelcc39b672014-07-24 12:16:19 +00003520 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
Dan Gohman575fad32008-09-03 16:12:24 +00003521 // Do not serialize (non-volatile) loads of constant memory with anything.
3522 Root = DAG.getEntryNode();
3523 ConstantMemory = true;
3524 } else {
3525 // Do not serialize non-volatile loads against each other.
3526 Root = DAG.getRoot();
3527 }
Wesley Peck527da1b2010-11-23 03:31:01 +00003528
Eric Christopherd9134482014-08-04 21:25:23 +00003529 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Richard Sandiford9afe6132013-12-10 10:36:34 +00003530 if (isVolatile)
3531 Root = TLI->prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
3532
Dan Gohman575fad32008-09-03 16:12:24 +00003533 SmallVector<SDValue, 4> Values(NumValues);
Andrew Trick116efac2010-11-12 17:50:46 +00003534 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3535 NumValues));
Owen Anderson53aa7a92009-08-10 22:56:29 +00003536 EVT PtrVT = Ptr.getValueType();
Andrew Trick116efac2010-11-12 17:50:46 +00003537 unsigned ChainI = 0;
3538 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3539 // Serializing loads here may result in excessive register pressure, and
3540 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3541 // could recover a bit by hoisting nodes upward in the chain by recognizing
3542 // they are side-effect free or do not alias. The optimizer should really
3543 // avoid this case by converting large object/array copies to llvm.memcpy
3544 // (MaxParallelChains should always remain as failsafe).
3545 if (ChainI == MaxParallelChains) {
3546 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
Craig Topper48d114b2014-04-26 18:35:24 +00003547 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003548 makeArrayRef(Chains.data(), ChainI));
Andrew Trick116efac2010-11-12 17:50:46 +00003549 Root = Chain;
3550 ChainI = 0;
3551 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00003552 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003553 PtrVT, Ptr,
3554 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003555 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00003556 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
Hal Finkelcc39b672014-07-24 12:16:19 +00003557 isNonTemporal, isInvariant, Alignment, AAInfo,
Rafael Espindola80c540e2012-03-31 18:14:00 +00003558 Ranges);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003559
Dan Gohman575fad32008-09-03 16:12:24 +00003560 Values[i] = L;
Andrew Trick116efac2010-11-12 17:50:46 +00003561 Chains[ChainI] = L.getValue(1);
Dan Gohman575fad32008-09-03 16:12:24 +00003562 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003563
Dan Gohman575fad32008-09-03 16:12:24 +00003564 if (!ConstantMemory) {
Craig Topper48d114b2014-04-26 18:35:24 +00003565 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003566 makeArrayRef(Chains.data(), ChainI));
Dan Gohman575fad32008-09-03 16:12:24 +00003567 if (isVolatile)
3568 DAG.setRoot(Chain);
3569 else
3570 PendingLoads.push_back(Chain);
3571 }
3572
Andrew Trickef9de2a2013-05-25 02:42:55 +00003573 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00003574 DAG.getVTList(ValueVTs), Values));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003575}
Dan Gohman575fad32008-09-03 16:12:24 +00003576
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003577void SelectionDAGBuilder::visitStore(const StoreInst &I) {
Eli Friedman342e8df2011-08-24 20:50:09 +00003578 if (I.isAtomic())
3579 return visitAtomicStore(I);
3580
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003581 const Value *SrcV = I.getOperand(0);
3582 const Value *PtrV = I.getOperand(1);
Dan Gohman575fad32008-09-03 16:12:24 +00003583
Owen Anderson53aa7a92009-08-10 22:56:29 +00003584 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00003585 SmallVector<uint64_t, 4> Offsets;
Eric Christopherd9134482014-08-04 21:25:23 +00003586 ComputeValueVTs(*TM.getSubtargetImpl()->getTargetLowering(), SrcV->getType(),
3587 ValueVTs, &Offsets);
Dan Gohman575fad32008-09-03 16:12:24 +00003588 unsigned NumValues = ValueVTs.size();
3589 if (NumValues == 0)
3590 return;
3591
3592 // Get the lowered operands. Note that we do this after
3593 // checking if NumResults is zero, because with zero results
3594 // the operands won't have values in the map.
3595 SDValue Src = getValue(SrcV);
3596 SDValue Ptr = getValue(PtrV);
3597
3598 SDValue Root = getRoot();
Andrew Trick116efac2010-11-12 17:50:46 +00003599 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3600 NumValues));
Owen Anderson53aa7a92009-08-10 22:56:29 +00003601 EVT PtrVT = Ptr.getValueType();
Dan Gohman575fad32008-09-03 16:12:24 +00003602 bool isVolatile = I.isVolatile();
Craig Topperc0196b12014-04-14 00:51:57 +00003603 bool isNonTemporal = I.getMetadata("nontemporal") != nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00003604 unsigned Alignment = I.getAlignment();
Hal Finkelcc39b672014-07-24 12:16:19 +00003605
3606 AAMDNodes AAInfo;
3607 I.getAAMetadata(AAInfo);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003608
Andrew Trick116efac2010-11-12 17:50:46 +00003609 unsigned ChainI = 0;
3610 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3611 // See visitLoad comments.
3612 if (ChainI == MaxParallelChains) {
Craig Topper48d114b2014-04-26 18:35:24 +00003613 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003614 makeArrayRef(Chains.data(), ChainI));
Andrew Trick116efac2010-11-12 17:50:46 +00003615 Root = Chain;
3616 ChainI = 0;
3617 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00003618 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003619 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003620 SDValue St = DAG.getStore(Root, getCurSDLoc(),
Andrew Trick116efac2010-11-12 17:50:46 +00003621 SDValue(Src.getNode(), Src.getResNo() + i),
3622 Add, MachinePointerInfo(PtrV, Offsets[i]),
Hal Finkelcc39b672014-07-24 12:16:19 +00003623 isVolatile, isNonTemporal, Alignment, AAInfo);
Andrew Trick116efac2010-11-12 17:50:46 +00003624 Chains[ChainI] = St;
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003625 }
3626
Craig Topper48d114b2014-04-26 18:35:24 +00003627 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003628 makeArrayRef(Chains.data(), ChainI));
Devang Patel05561e82010-10-26 22:14:52 +00003629 DAG.setRoot(StoreNode);
Dan Gohman575fad32008-09-03 16:12:24 +00003630}
3631
Eli Friedman30a49e92011-08-03 21:06:02 +00003632static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
Eli Friedman342e8df2011-08-24 20:50:09 +00003633 SynchronizationScope Scope,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003634 bool Before, SDLoc dl,
Eli Friedman30a49e92011-08-03 21:06:02 +00003635 SelectionDAG &DAG,
3636 const TargetLowering &TLI) {
3637 // Fence, if necessary
3638 if (Before) {
Eli Friedman452aae62011-08-26 02:59:24 +00003639 if (Order == AcquireRelease || Order == SequentiallyConsistent)
Eli Friedman30a49e92011-08-03 21:06:02 +00003640 Order = Release;
Tim Northoverd622e122014-05-30 14:41:51 +00003641 else if (Order == Acquire || Order == Monotonic || Order == Unordered)
Eli Friedman30a49e92011-08-03 21:06:02 +00003642 return Chain;
3643 } else {
3644 if (Order == AcquireRelease)
3645 Order = Acquire;
Tim Northoverd622e122014-05-30 14:41:51 +00003646 else if (Order == Release || Order == Monotonic || Order == Unordered)
Eli Friedman30a49e92011-08-03 21:06:02 +00003647 return Chain;
3648 }
3649 SDValue Ops[3];
3650 Ops[0] = Chain;
Eli Friedman342e8df2011-08-24 20:50:09 +00003651 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
3652 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
Craig Topper48d114b2014-04-26 18:35:24 +00003653 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
Eli Friedman30a49e92011-08-03 21:06:02 +00003654}
3655
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003656void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003657 SDLoc dl = getCurSDLoc();
Tim Northovere94a5182014-03-11 10:48:52 +00003658 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3659 AtomicOrdering FailureOrder = I.getFailureOrdering();
Eli Friedman342e8df2011-08-24 20:50:09 +00003660 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman30a49e92011-08-03 21:06:02 +00003661
3662 SDValue InChain = getRoot();
3663
Eric Christopherd9134482014-08-04 21:25:23 +00003664 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003665 if (TLI->getInsertFencesForAtomic())
Tim Northovere94a5182014-03-11 10:48:52 +00003666 InChain = InsertFenceForAtomic(InChain, SuccessOrder, Scope, true, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003667 DAG, *TLI);
Eli Friedman30a49e92011-08-03 21:06:02 +00003668
Tim Northover420a2162014-06-13 14:24:07 +00003669 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3670 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3671 SDValue L = DAG.getAtomicCmpSwap(
3672 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3673 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3674 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3675 0 /* Alignment */,
3676 TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder,
3677 TLI->getInsertFencesForAtomic() ? Monotonic : FailureOrder, Scope);
Eli Friedman30a49e92011-08-03 21:06:02 +00003678
Tim Northover420a2162014-06-13 14:24:07 +00003679 SDValue OutChain = L.getValue(2);
Eli Friedman30a49e92011-08-03 21:06:02 +00003680
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003681 if (TLI->getInsertFencesForAtomic())
Tim Northovere94a5182014-03-11 10:48:52 +00003682 OutChain = InsertFenceForAtomic(OutChain, SuccessOrder, Scope, false, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003683 DAG, *TLI);
Eli Friedman30a49e92011-08-03 21:06:02 +00003684
Eli Friedmanadec5872011-07-29 03:05:32 +00003685 setValue(&I, L);
Eli Friedman30a49e92011-08-03 21:06:02 +00003686 DAG.setRoot(OutChain);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003687}
3688
3689void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003690 SDLoc dl = getCurSDLoc();
Eli Friedmanadec5872011-07-29 03:05:32 +00003691 ISD::NodeType NT;
3692 switch (I.getOperation()) {
David Blaikie46a9f012012-01-20 21:51:11 +00003693 default: llvm_unreachable("Unknown atomicrmw operation");
Eli Friedmanadec5872011-07-29 03:05:32 +00003694 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3695 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3696 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3697 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3698 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3699 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3700 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3701 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3702 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3703 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3704 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3705 }
Eli Friedman30a49e92011-08-03 21:06:02 +00003706 AtomicOrdering Order = I.getOrdering();
Eli Friedman342e8df2011-08-24 20:50:09 +00003707 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman30a49e92011-08-03 21:06:02 +00003708
3709 SDValue InChain = getRoot();
3710
Eric Christopherd9134482014-08-04 21:25:23 +00003711 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003712 if (TLI->getInsertFencesForAtomic())
Eli Friedman342e8df2011-08-24 20:50:09 +00003713 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003714 DAG, *TLI);
Eli Friedman30a49e92011-08-03 21:06:02 +00003715
Eli Friedmanadec5872011-07-29 03:05:32 +00003716 SDValue L =
Eli Friedman30a49e92011-08-03 21:06:02 +00003717 DAG.getAtomic(NT, dl,
Craig Topperd9c27832013-08-15 02:44:19 +00003718 getValue(I.getValOperand()).getSimpleValueType(),
Eli Friedman30a49e92011-08-03 21:06:02 +00003719 InChain,
Eli Friedmanadec5872011-07-29 03:05:32 +00003720 getValue(I.getPointerOperand()),
3721 getValue(I.getValOperand()),
3722 I.getPointerOperand(), 0 /* Alignment */,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003723 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
Eli Friedman342e8df2011-08-24 20:50:09 +00003724 Scope);
Eli Friedman30a49e92011-08-03 21:06:02 +00003725
3726 SDValue OutChain = L.getValue(1);
3727
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003728 if (TLI->getInsertFencesForAtomic())
Eli Friedman342e8df2011-08-24 20:50:09 +00003729 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003730 DAG, *TLI);
Eli Friedman30a49e92011-08-03 21:06:02 +00003731
Eli Friedmanadec5872011-07-29 03:05:32 +00003732 setValue(&I, L);
Eli Friedman30a49e92011-08-03 21:06:02 +00003733 DAG.setRoot(OutChain);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003734}
3735
Eli Friedmanfee02c62011-07-25 23:16:38 +00003736void SelectionDAGBuilder::visitFence(const FenceInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003737 SDLoc dl = getCurSDLoc();
Eric Christopherd9134482014-08-04 21:25:23 +00003738 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Eli Friedman26a48482011-07-27 22:21:52 +00003739 SDValue Ops[3];
3740 Ops[0] = getRoot();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003741 Ops[1] = DAG.getConstant(I.getOrdering(), TLI->getPointerTy());
3742 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI->getPointerTy());
Craig Topper48d114b2014-04-26 18:35:24 +00003743 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
Eli Friedmanfee02c62011-07-25 23:16:38 +00003744}
3745
Eli Friedman342e8df2011-08-24 20:50:09 +00003746void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003747 SDLoc dl = getCurSDLoc();
Eli Friedman342e8df2011-08-24 20:50:09 +00003748 AtomicOrdering Order = I.getOrdering();
3749 SynchronizationScope Scope = I.getSynchScope();
3750
3751 SDValue InChain = getRoot();
3752
Eric Christopherd9134482014-08-04 21:25:23 +00003753 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003754 EVT VT = TLI->getValueType(I.getType());
Eli Friedman342e8df2011-08-24 20:50:09 +00003755
Evan Chenga72b9702013-02-06 02:06:33 +00003756 if (I.getAlignment() < VT.getSizeInBits() / 8)
Eli Friedmanf1518212011-09-13 20:50:54 +00003757 report_fatal_error("Cannot generate unaligned atomic load");
3758
Nick Lewyckyaad475b2014-04-15 07:22:52 +00003759 MachineMemOperand *MMO =
3760 DAG.getMachineFunction().
3761 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3762 MachineMemOperand::MOVolatile |
3763 MachineMemOperand::MOLoad,
3764 VT.getStoreSize(),
3765 I.getAlignment() ? I.getAlignment() :
3766 DAG.getEVTAlignment(VT));
3767
Richard Sandiford9afe6132013-12-10 10:36:34 +00003768 InChain = TLI->prepareVolatileOrAtomicLoad(InChain, dl, DAG);
Eli Friedman342e8df2011-08-24 20:50:09 +00003769 SDValue L =
Nick Lewyckyaad475b2014-04-15 07:22:52 +00003770 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3771 getValue(I.getPointerOperand()), MMO,
3772 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3773 Scope);
Eli Friedman342e8df2011-08-24 20:50:09 +00003774
3775 SDValue OutChain = L.getValue(1);
3776
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003777 if (TLI->getInsertFencesForAtomic())
Eli Friedman342e8df2011-08-24 20:50:09 +00003778 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003779 DAG, *TLI);
Eli Friedman342e8df2011-08-24 20:50:09 +00003780
3781 setValue(&I, L);
3782 DAG.setRoot(OutChain);
3783}
3784
3785void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003786 SDLoc dl = getCurSDLoc();
Eli Friedman342e8df2011-08-24 20:50:09 +00003787
3788 AtomicOrdering Order = I.getOrdering();
3789 SynchronizationScope Scope = I.getSynchScope();
3790
3791 SDValue InChain = getRoot();
3792
Eric Christopherd9134482014-08-04 21:25:23 +00003793 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003794 EVT VT = TLI->getValueType(I.getValueOperand()->getType());
Eli Friedmanf1518212011-09-13 20:50:54 +00003795
Evan Chenga72b9702013-02-06 02:06:33 +00003796 if (I.getAlignment() < VT.getSizeInBits() / 8)
Eli Friedmanf1518212011-09-13 20:50:54 +00003797 report_fatal_error("Cannot generate unaligned atomic store");
3798
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003799 if (TLI->getInsertFencesForAtomic())
Eli Friedman342e8df2011-08-24 20:50:09 +00003800 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003801 DAG, *TLI);
Eli Friedman342e8df2011-08-24 20:50:09 +00003802
3803 SDValue OutChain =
Eli Friedmanf1518212011-09-13 20:50:54 +00003804 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
Eli Friedman342e8df2011-08-24 20:50:09 +00003805 InChain,
3806 getValue(I.getPointerOperand()),
3807 getValue(I.getValueOperand()),
3808 I.getPointerOperand(), I.getAlignment(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003809 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
Eli Friedman342e8df2011-08-24 20:50:09 +00003810 Scope);
3811
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003812 if (TLI->getInsertFencesForAtomic())
Eli Friedman342e8df2011-08-24 20:50:09 +00003813 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003814 DAG, *TLI);
Eli Friedman342e8df2011-08-24 20:50:09 +00003815
3816 DAG.setRoot(OutChain);
3817}
3818
Dan Gohman575fad32008-09-03 16:12:24 +00003819/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3820/// node.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003821void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00003822 unsigned Intrinsic) {
Dan Gohman575fad32008-09-03 16:12:24 +00003823 bool HasChain = !I.doesNotAccessMemory();
3824 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3825
3826 // Build the operand list.
3827 SmallVector<SDValue, 8> Ops;
3828 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3829 if (OnlyLoad) {
3830 // We don't need to serialize loads against other loads.
3831 Ops.push_back(DAG.getRoot());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003832 } else {
Dan Gohman575fad32008-09-03 16:12:24 +00003833 Ops.push_back(getRoot());
3834 }
3835 }
Mon P Wang769134b2008-11-01 20:24:53 +00003836
3837 // Info is set by getTgtMemInstrinsic
3838 TargetLowering::IntrinsicInfo Info;
Eric Christopherd9134482014-08-04 21:25:23 +00003839 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003840 bool IsTgtIntrinsic = TLI->getTgtMemIntrinsic(Info, I, Intrinsic);
Mon P Wang769134b2008-11-01 20:24:53 +00003841
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003842 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Bob Wilson5549d492010-09-21 17:56:22 +00003843 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3844 Info.opc == ISD::INTRINSIC_W_CHAIN)
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003845 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI->getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00003846
3847 // Add all operands of the call to the operand list.
Gabor Greifeba0be72010-06-25 09:38:13 +00003848 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3849 SDValue Op = getValue(I.getArgOperand(i));
Dan Gohman575fad32008-09-03 16:12:24 +00003850 Ops.push_back(Op);
3851 }
3852
Owen Anderson53aa7a92009-08-10 22:56:29 +00003853 SmallVector<EVT, 4> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003854 ComputeValueVTs(*TLI, I.getType(), ValueVTs);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003855
Dan Gohman575fad32008-09-03 16:12:24 +00003856 if (HasChain)
Owen Anderson9f944592009-08-11 20:47:22 +00003857 ValueVTs.push_back(MVT::Other);
Dan Gohman575fad32008-09-03 16:12:24 +00003858
Craig Topperabb4ac72014-04-16 06:10:51 +00003859 SDVTList VTs = DAG.getVTList(ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00003860
3861 // Create the node.
3862 SDValue Result;
Mon P Wang769134b2008-11-01 20:24:53 +00003863 if (IsTgtIntrinsic) {
3864 // This is target intrinsic that touches memory
Andrew Trickef9de2a2013-05-25 02:42:55 +00003865 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
Craig Topper206fcd42014-04-26 19:29:41 +00003866 VTs, Ops, Info.memVT,
Chris Lattnerd2d58ad2010-09-21 04:57:15 +00003867 MachinePointerInfo(Info.ptrVal, Info.offset),
Mon P Wang769134b2008-11-01 20:24:53 +00003868 Info.align, Info.vol,
3869 Info.readMem, Info.writeMem);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003870 } else if (!HasChain) {
Craig Topper48d114b2014-04-26 18:35:24 +00003871 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003872 } else if (!I.getType()->isVoidTy()) {
Craig Topper48d114b2014-04-26 18:35:24 +00003873 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003874 } else {
Craig Topper48d114b2014-04-26 18:35:24 +00003875 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003876 }
3877
Dan Gohman575fad32008-09-03 16:12:24 +00003878 if (HasChain) {
3879 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3880 if (OnlyLoad)
3881 PendingLoads.push_back(Chain);
3882 else
3883 DAG.setRoot(Chain);
3884 }
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003885
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003886 if (!I.getType()->isVoidTy()) {
Chris Lattner229907c2011-07-18 04:54:35 +00003887 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003888 EVT VT = TLI->getValueType(PTy);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003889 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003890 }
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003891
Dan Gohman575fad32008-09-03 16:12:24 +00003892 setValue(&I, Result);
3893 }
3894}
3895
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003896/// GetSignificand - Get the significand and build it into a floating-point
3897/// number with exponent of 1:
3898///
3899/// Op = (Op & 0x007fffff) | 0x3f800000;
3900///
Matt Beaumont-Gay0e760da2013-02-25 18:11:18 +00003901/// where Op is the hexadecimal representation of floating point value.
Bill Wendlinged3bb782008-09-09 20:39:27 +00003902static SDValue
Andrew Trickef9de2a2013-05-25 02:42:55 +00003903GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
Owen Anderson9f944592009-08-11 20:47:22 +00003904 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3905 DAG.getConstant(0x007fffff, MVT::i32));
3906 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3907 DAG.getConstant(0x3f800000, MVT::i32));
Wesley Peck527da1b2010-11-23 03:31:01 +00003908 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
Bill Wendlinged3bb782008-09-09 20:39:27 +00003909}
3910
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003911/// GetExponent - Get the exponent:
3912///
Bill Wendling23959162009-01-20 21:17:57 +00003913/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003914///
Matt Beaumont-Gay0e760da2013-02-25 18:11:18 +00003915/// where Op is the hexadecimal representation of floating point value.
Bill Wendlinged3bb782008-09-09 20:39:27 +00003916static SDValue
Dale Johannesendb7c5f62009-01-31 02:22:37 +00003917GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003918 SDLoc dl) {
Owen Anderson9f944592009-08-11 20:47:22 +00003919 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3920 DAG.getConstant(0x7f800000, MVT::i32));
3921 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands41826032009-01-31 15:50:11 +00003922 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson9f944592009-08-11 20:47:22 +00003923 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3924 DAG.getConstant(127, MVT::i32));
Bill Wendling954cb182010-01-28 21:51:40 +00003925 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendlinged3bb782008-09-09 20:39:27 +00003926}
3927
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003928/// getF32Constant - Get 32-bit floating point constant.
3929static SDValue
3930getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Tim Northover29178a32013-01-22 09:46:31 +00003931 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3932 MVT::f32);
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003933}
3934
Craig Topperd2638c12012-11-24 18:52:06 +00003935/// expandExp - Lower an exp intrinsic. Handles the special sequences for
Bill Wendling48217d82008-09-09 22:13:54 +00003936/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003937static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperd2638c12012-11-24 18:52:06 +00003938 const TargetLowering &TLI) {
3939 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48217d82008-09-09 22:13:54 +00003940 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Bill Wendling48217d82008-09-09 22:13:54 +00003941
3942 // Put the exponent in the right bit position for later addition to the
3943 // final result:
3944 //
3945 // #define LOG2OFe 1.4426950f
3946 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson9f944592009-08-11 20:47:22 +00003947 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003948 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson9f944592009-08-11 20:47:22 +00003949 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendling48217d82008-09-09 22:13:54 +00003950
3951 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson9f944592009-08-11 20:47:22 +00003952 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3953 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendling48217d82008-09-09 22:13:54 +00003954
3955 // IntegerPartOfX <<= 23;
Owen Anderson9f944592009-08-11 20:47:22 +00003956 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands41826032009-01-31 15:50:11 +00003957 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003958
Craig Topper4a981752012-11-24 08:22:37 +00003959 SDValue TwoToFracPartOfX;
Bill Wendling48217d82008-09-09 22:13:54 +00003960 if (LimitFloatPrecision <= 6) {
3961 // For floating-point precision of 6:
3962 //
3963 // TwoToFractionalPartOfX =
3964 // 0.997535578f +
3965 // (0.735607626f + 0.252464424f * x) * x;
3966 //
3967 // error 0.0144103317, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00003968 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003969 getF32Constant(DAG, 0x3e814304));
Owen Anderson9f944592009-08-11 20:47:22 +00003970 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003971 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson9f944592009-08-11 20:47:22 +00003972 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper4a981752012-11-24 08:22:37 +00003973 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3974 getF32Constant(DAG, 0x3f7f5e7e));
Craig Toppered756c52012-11-16 20:01:39 +00003975 } else if (LimitFloatPrecision <= 12) {
Bill Wendling48217d82008-09-09 22:13:54 +00003976 // For floating-point precision of 12:
3977 //
3978 // TwoToFractionalPartOfX =
3979 // 0.999892986f +
3980 // (0.696457318f +
3981 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3982 //
3983 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00003984 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003985 getF32Constant(DAG, 0x3da235e3));
Owen Anderson9f944592009-08-11 20:47:22 +00003986 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003987 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson9f944592009-08-11 20:47:22 +00003988 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3989 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003990 getF32Constant(DAG, 0x3f324b07));
Owen Anderson9f944592009-08-11 20:47:22 +00003991 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper4a981752012-11-24 08:22:37 +00003992 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3993 getF32Constant(DAG, 0x3f7ff8fd));
Craig Toppered756c52012-11-16 20:01:39 +00003994 } else { // LimitFloatPrecision <= 18
Bill Wendling48217d82008-09-09 22:13:54 +00003995 // For floating-point precision of 18:
3996 //
3997 // TwoToFractionalPartOfX =
3998 // 0.999999982f +
3999 // (0.693148872f +
4000 // (0.240227044f +
4001 // (0.554906021e-1f +
4002 // (0.961591928e-2f +
4003 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4004 //
4005 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004006 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004007 getF32Constant(DAG, 0x3924b03e));
Owen Anderson9f944592009-08-11 20:47:22 +00004008 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004009 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson9f944592009-08-11 20:47:22 +00004010 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4011 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004012 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson9f944592009-08-11 20:47:22 +00004013 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4014 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004015 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson9f944592009-08-11 20:47:22 +00004016 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4017 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004018 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson9f944592009-08-11 20:47:22 +00004019 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4020 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004021 getF32Constant(DAG, 0x3f317234));
Owen Anderson9f944592009-08-11 20:47:22 +00004022 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topper4a981752012-11-24 08:22:37 +00004023 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4024 getF32Constant(DAG, 0x3f800000));
Bill Wendling48217d82008-09-09 22:13:54 +00004025 }
Craig Topper4a981752012-11-24 08:22:37 +00004026
4027 // Add the exponent into the result in integer domain.
4028 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
Craig Topperd2638c12012-11-24 18:52:06 +00004029 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4030 DAG.getNode(ISD::ADD, dl, MVT::i32,
4031 t13, IntegerPartOfX));
Bill Wendling48217d82008-09-09 22:13:54 +00004032 }
4033
Craig Topperd2638c12012-11-24 18:52:06 +00004034 // No special expansion.
4035 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004036}
4037
Craig Topperbef254a2012-11-23 18:38:31 +00004038/// expandLog - Lower a log intrinsic. Handles the special sequences for
Bill Wendlinged3bb782008-09-09 20:39:27 +00004039/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004040static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00004041 const TargetLowering &TLI) {
4042 if (Op.getValueType() == MVT::f32 &&
Bill Wendlinged3bb782008-09-09 20:39:27 +00004043 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00004044 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendlinged3bb782008-09-09 20:39:27 +00004045
4046 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004047 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson9f944592009-08-11 20:47:22 +00004048 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004049 getF32Constant(DAG, 0x3f317218));
Bill Wendlinged3bb782008-09-09 20:39:27 +00004050
4051 // Get the significand and build it into a floating-point number with
4052 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004053 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendlinged3bb782008-09-09 20:39:27 +00004054
Craig Topper3669de42012-11-16 19:08:44 +00004055 SDValue LogOfMantissa;
Bill Wendlinged3bb782008-09-09 20:39:27 +00004056 if (LimitFloatPrecision <= 6) {
4057 // For floating-point precision of 6:
4058 //
4059 // LogofMantissa =
4060 // -1.1609546f +
4061 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004062 //
Bill Wendlinged3bb782008-09-09 20:39:27 +00004063 // error 0.0034276066, which is better than 8 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004064 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004065 getF32Constant(DAG, 0xbe74c456));
Owen Anderson9f944592009-08-11 20:47:22 +00004066 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004067 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson9f944592009-08-11 20:47:22 +00004068 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004069 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4070 getF32Constant(DAG, 0x3f949a29));
Craig Toppered756c52012-11-16 20:01:39 +00004071 } else if (LimitFloatPrecision <= 12) {
Bill Wendlinged3bb782008-09-09 20:39:27 +00004072 // For floating-point precision of 12:
4073 //
4074 // LogOfMantissa =
4075 // -1.7417939f +
4076 // (2.8212026f +
4077 // (-1.4699568f +
4078 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4079 //
4080 // error 0.000061011436, which is 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004081 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004082 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson9f944592009-08-11 20:47:22 +00004083 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004084 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson9f944592009-08-11 20:47:22 +00004085 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4086 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004087 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson9f944592009-08-11 20:47:22 +00004088 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4089 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004090 getF32Constant(DAG, 0x40348e95));
Owen Anderson9f944592009-08-11 20:47:22 +00004091 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper3669de42012-11-16 19:08:44 +00004092 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4093 getF32Constant(DAG, 0x3fdef31a));
Craig Toppered756c52012-11-16 20:01:39 +00004094 } else { // LimitFloatPrecision <= 18
Bill Wendlinged3bb782008-09-09 20:39:27 +00004095 // For floating-point precision of 18:
4096 //
4097 // LogOfMantissa =
4098 // -2.1072184f +
4099 // (4.2372794f +
4100 // (-3.7029485f +
4101 // (2.2781945f +
4102 // (-0.87823314f +
4103 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4104 //
4105 // error 0.0000023660568, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004106 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004107 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson9f944592009-08-11 20:47:22 +00004108 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004109 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson9f944592009-08-11 20:47:22 +00004110 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4111 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004112 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson9f944592009-08-11 20:47:22 +00004113 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4114 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004115 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson9f944592009-08-11 20:47:22 +00004116 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4117 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004118 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson9f944592009-08-11 20:47:22 +00004119 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4120 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004121 getF32Constant(DAG, 0x408797cb));
Owen Anderson9f944592009-08-11 20:47:22 +00004122 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topper3669de42012-11-16 19:08:44 +00004123 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4124 getF32Constant(DAG, 0x4006dcab));
Bill Wendlinged3bb782008-09-09 20:39:27 +00004125 }
Craig Topper3669de42012-11-16 19:08:44 +00004126
Craig Topperbef254a2012-11-23 18:38:31 +00004127 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendlinged3bb782008-09-09 20:39:27 +00004128 }
4129
Craig Topperbef254a2012-11-23 18:38:31 +00004130 // No special expansion.
4131 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004132}
4133
Craig Topperbef254a2012-11-23 18:38:31 +00004134/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
Bill Wendling48416782008-09-09 00:28:24 +00004135/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004136static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00004137 const TargetLowering &TLI) {
4138 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48416782008-09-09 00:28:24 +00004139 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00004140 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling48416782008-09-09 00:28:24 +00004141
Bill Wendlinged3bb782008-09-09 20:39:27 +00004142 // Get the exponent.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004143 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00004144
Bill Wendling48416782008-09-09 00:28:24 +00004145 // Get the significand and build it into a floating-point number with
Bill Wendlinged3bb782008-09-09 20:39:27 +00004146 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004147 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004148
Bill Wendling48416782008-09-09 00:28:24 +00004149 // Different possible minimax approximations of significand in
4150 // floating-point for various degrees of accuracy over [1,2].
Craig Topper3669de42012-11-16 19:08:44 +00004151 SDValue Log2ofMantissa;
Bill Wendling48416782008-09-09 00:28:24 +00004152 if (LimitFloatPrecision <= 6) {
4153 // For floating-point precision of 6:
4154 //
4155 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4156 //
4157 // error 0.0049451742, which is more than 7 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004158 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004159 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson9f944592009-08-11 20:47:22 +00004160 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004161 getF32Constant(DAG, 0x40019463));
Owen Anderson9f944592009-08-11 20:47:22 +00004162 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004163 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4164 getF32Constant(DAG, 0x3fd6633d));
Craig Toppered756c52012-11-16 20:01:39 +00004165 } else if (LimitFloatPrecision <= 12) {
Bill Wendling48416782008-09-09 00:28:24 +00004166 // For floating-point precision of 12:
4167 //
4168 // Log2ofMantissa =
4169 // -2.51285454f +
4170 // (4.07009056f +
4171 // (-2.12067489f +
4172 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004173 //
Bill Wendling48416782008-09-09 00:28:24 +00004174 // error 0.0000876136000, which is better than 13 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004175 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004176 getF32Constant(DAG, 0xbda7262e));
Owen Anderson9f944592009-08-11 20:47:22 +00004177 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004178 getF32Constant(DAG, 0x3f25280b));
Owen Anderson9f944592009-08-11 20:47:22 +00004179 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4180 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004181 getF32Constant(DAG, 0x4007b923));
Owen Anderson9f944592009-08-11 20:47:22 +00004182 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4183 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004184 getF32Constant(DAG, 0x40823e2f));
Owen Anderson9f944592009-08-11 20:47:22 +00004185 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper3669de42012-11-16 19:08:44 +00004186 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4187 getF32Constant(DAG, 0x4020d29c));
Craig Toppered756c52012-11-16 20:01:39 +00004188 } else { // LimitFloatPrecision <= 18
Bill Wendling48416782008-09-09 00:28:24 +00004189 // For floating-point precision of 18:
4190 //
4191 // Log2ofMantissa =
4192 // -3.0400495f +
4193 // (6.1129976f +
4194 // (-5.3420409f +
4195 // (3.2865683f +
4196 // (-1.2669343f +
4197 // (0.27515199f -
4198 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4199 //
4200 // error 0.0000018516, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004201 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004202 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson9f944592009-08-11 20:47:22 +00004203 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004204 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson9f944592009-08-11 20:47:22 +00004205 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4206 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004207 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson9f944592009-08-11 20:47:22 +00004208 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4209 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004210 getF32Constant(DAG, 0x40525723));
Owen Anderson9f944592009-08-11 20:47:22 +00004211 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4212 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004213 getF32Constant(DAG, 0x40aaf200));
Owen Anderson9f944592009-08-11 20:47:22 +00004214 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4215 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004216 getF32Constant(DAG, 0x40c39dad));
Owen Anderson9f944592009-08-11 20:47:22 +00004217 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topper3669de42012-11-16 19:08:44 +00004218 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4219 getF32Constant(DAG, 0x4042902c));
Bill Wendling48416782008-09-09 00:28:24 +00004220 }
Craig Topper3669de42012-11-16 19:08:44 +00004221
Craig Topperbef254a2012-11-23 18:38:31 +00004222 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
Dale Johannesen36d532a2008-09-05 23:49:37 +00004223 }
Bill Wendling48416782008-09-09 00:28:24 +00004224
Craig Topperbef254a2012-11-23 18:38:31 +00004225 // No special expansion.
4226 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004227}
4228
Craig Topperbef254a2012-11-23 18:38:31 +00004229/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
Bill Wendling48416782008-09-09 00:28:24 +00004230/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004231static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00004232 const TargetLowering &TLI) {
4233 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48416782008-09-09 00:28:24 +00004234 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00004235 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling48416782008-09-09 00:28:24 +00004236
Bill Wendlinged3bb782008-09-09 20:39:27 +00004237 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004238 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson9f944592009-08-11 20:47:22 +00004239 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004240 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling48416782008-09-09 00:28:24 +00004241
4242 // Get the significand and build it into a floating-point number with
Bill Wendlinged3bb782008-09-09 20:39:27 +00004243 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004244 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling48416782008-09-09 00:28:24 +00004245
Craig Topper3669de42012-11-16 19:08:44 +00004246 SDValue Log10ofMantissa;
Bill Wendling48416782008-09-09 00:28:24 +00004247 if (LimitFloatPrecision <= 6) {
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004248 // For floating-point precision of 6:
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004249 //
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004250 // Log10ofMantissa =
4251 // -0.50419619f +
4252 // (0.60948995f - 0.10380950f * x) * x;
4253 //
4254 // error 0.0014886165, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004255 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004256 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson9f944592009-08-11 20:47:22 +00004257 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004258 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson9f944592009-08-11 20:47:22 +00004259 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004260 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4261 getF32Constant(DAG, 0x3f011300));
Craig Toppered756c52012-11-16 20:01:39 +00004262 } else if (LimitFloatPrecision <= 12) {
Bill Wendling48416782008-09-09 00:28:24 +00004263 // For floating-point precision of 12:
4264 //
4265 // Log10ofMantissa =
4266 // -0.64831180f +
4267 // (0.91751397f +
4268 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4269 //
4270 // error 0.00019228036, which is better than 12 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004271 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004272 getF32Constant(DAG, 0x3d431f31));
Owen Anderson9f944592009-08-11 20:47:22 +00004273 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004274 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson9f944592009-08-11 20:47:22 +00004275 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4276 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004277 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson9f944592009-08-11 20:47:22 +00004278 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper3669de42012-11-16 19:08:44 +00004279 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4280 getF32Constant(DAG, 0x3f25f7c3));
Craig Toppered756c52012-11-16 20:01:39 +00004281 } else { // LimitFloatPrecision <= 18
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004282 // For floating-point precision of 18:
4283 //
4284 // Log10ofMantissa =
4285 // -0.84299375f +
4286 // (1.5327582f +
4287 // (-1.0688956f +
4288 // (0.49102474f +
4289 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4290 //
4291 // error 0.0000037995730, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004292 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004293 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson9f944592009-08-11 20:47:22 +00004294 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004295 getF32Constant(DAG, 0x3e00685a));
Owen Anderson9f944592009-08-11 20:47:22 +00004296 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4297 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004298 getF32Constant(DAG, 0x3efb6798));
Owen Anderson9f944592009-08-11 20:47:22 +00004299 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4300 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004301 getF32Constant(DAG, 0x3f88d192));
Owen Anderson9f944592009-08-11 20:47:22 +00004302 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4303 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004304 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson9f944592009-08-11 20:47:22 +00004305 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
Craig Topper3669de42012-11-16 19:08:44 +00004306 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4307 getF32Constant(DAG, 0x3f57ce70));
Bill Wendling48416782008-09-09 00:28:24 +00004308 }
Craig Topper3669de42012-11-16 19:08:44 +00004309
Craig Topperbef254a2012-11-23 18:38:31 +00004310 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
Dale Johannesend4dac0e2008-09-05 21:27:19 +00004311 }
Bill Wendling48416782008-09-09 00:28:24 +00004312
Craig Topperbef254a2012-11-23 18:38:31 +00004313 // No special expansion.
4314 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004315}
4316
Craig Topperd2638c12012-11-24 18:52:06 +00004317/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
Bill Wendlingab6676a2008-09-09 22:39:21 +00004318/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004319static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperd2638c12012-11-24 18:52:06 +00004320 const TargetLowering &TLI) {
4321 if (Op.getValueType() == MVT::f32 &&
Bill Wendlingab6676a2008-09-09 22:39:21 +00004322 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Owen Anderson9f944592009-08-11 20:47:22 +00004323 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlingab6676a2008-09-09 22:39:21 +00004324
4325 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson9f944592009-08-11 20:47:22 +00004326 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4327 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlingab6676a2008-09-09 22:39:21 +00004328
4329 // IntegerPartOfX <<= 23;
Owen Anderson9f944592009-08-11 20:47:22 +00004330 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands41826032009-01-31 15:50:11 +00004331 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingab6676a2008-09-09 22:39:21 +00004332
Craig Topper4a981752012-11-24 08:22:37 +00004333 SDValue TwoToFractionalPartOfX;
Bill Wendlingab6676a2008-09-09 22:39:21 +00004334 if (LimitFloatPrecision <= 6) {
4335 // For floating-point precision of 6:
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004336 //
Bill Wendlingab6676a2008-09-09 22:39:21 +00004337 // TwoToFractionalPartOfX =
4338 // 0.997535578f +
4339 // (0.735607626f + 0.252464424f * x) * x;
4340 //
4341 // error 0.0144103317, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004342 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004343 getF32Constant(DAG, 0x3e814304));
Owen Anderson9f944592009-08-11 20:47:22 +00004344 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004345 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson9f944592009-08-11 20:47:22 +00004346 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper4a981752012-11-24 08:22:37 +00004347 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4348 getF32Constant(DAG, 0x3f7f5e7e));
Craig Toppered756c52012-11-16 20:01:39 +00004349 } else if (LimitFloatPrecision <= 12) {
Bill Wendlingab6676a2008-09-09 22:39:21 +00004350 // For floating-point precision of 12:
4351 //
4352 // TwoToFractionalPartOfX =
4353 // 0.999892986f +
4354 // (0.696457318f +
4355 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4356 //
4357 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004358 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004359 getF32Constant(DAG, 0x3da235e3));
Owen Anderson9f944592009-08-11 20:47:22 +00004360 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004361 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson9f944592009-08-11 20:47:22 +00004362 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4363 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004364 getF32Constant(DAG, 0x3f324b07));
Owen Anderson9f944592009-08-11 20:47:22 +00004365 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper4a981752012-11-24 08:22:37 +00004366 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4367 getF32Constant(DAG, 0x3f7ff8fd));
Craig Toppered756c52012-11-16 20:01:39 +00004368 } else { // LimitFloatPrecision <= 18
Bill Wendlingab6676a2008-09-09 22:39:21 +00004369 // For floating-point precision of 18:
4370 //
4371 // TwoToFractionalPartOfX =
4372 // 0.999999982f +
4373 // (0.693148872f +
4374 // (0.240227044f +
4375 // (0.554906021e-1f +
4376 // (0.961591928e-2f +
4377 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4378 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004379 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004380 getF32Constant(DAG, 0x3924b03e));
Owen Anderson9f944592009-08-11 20:47:22 +00004381 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004382 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson9f944592009-08-11 20:47:22 +00004383 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4384 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004385 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson9f944592009-08-11 20:47:22 +00004386 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4387 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004388 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson9f944592009-08-11 20:47:22 +00004389 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4390 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004391 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson9f944592009-08-11 20:47:22 +00004392 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4393 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004394 getF32Constant(DAG, 0x3f317234));
Owen Anderson9f944592009-08-11 20:47:22 +00004395 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topper4a981752012-11-24 08:22:37 +00004396 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4397 getF32Constant(DAG, 0x3f800000));
Bill Wendlingab6676a2008-09-09 22:39:21 +00004398 }
Craig Topper4a981752012-11-24 08:22:37 +00004399
4400 // Add the exponent into the result in integer domain.
4401 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4402 TwoToFractionalPartOfX);
Craig Topperd2638c12012-11-24 18:52:06 +00004403 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4404 DAG.getNode(ISD::ADD, dl, MVT::i32,
4405 t13, IntegerPartOfX));
Dale Johannesenf2a52bb2008-09-05 01:48:15 +00004406 }
Bill Wendlingab6676a2008-09-09 22:39:21 +00004407
Craig Topperd2638c12012-11-24 18:52:06 +00004408 // No special expansion.
4409 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
Dale Johannesenf2a52bb2008-09-05 01:48:15 +00004410}
4411
Bill Wendling648930b2008-09-10 00:20:20 +00004412/// visitPow - Lower a pow intrinsic. Handles the special sequences for
4413/// limited-precision mode with x == 10.0f.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004414static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
Craig Topper79bd2052012-11-25 08:08:58 +00004415 SelectionDAG &DAG, const TargetLowering &TLI) {
Bill Wendling648930b2008-09-10 00:20:20 +00004416 bool IsExp10 = false;
Benjamin Kramer671a5962013-12-11 16:36:09 +00004417 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
Bill Wendling648930b2008-09-10 00:20:20 +00004418 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Craig Topper79bd2052012-11-25 08:08:58 +00004419 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4420 APFloat Ten(10.0f);
4421 IsExp10 = LHSC->isExactlyValue(Ten);
Bill Wendling648930b2008-09-10 00:20:20 +00004422 }
4423 }
4424
Craig Topper268b6222012-11-25 00:48:58 +00004425 if (IsExp10) {
Bill Wendling648930b2008-09-10 00:20:20 +00004426 // Put the exponent in the right bit position for later addition to the
4427 // final result:
4428 //
4429 // #define LOG2OF10 3.3219281f
4430 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Craig Topper79bd2052012-11-25 08:08:58 +00004431 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004432 getF32Constant(DAG, 0x40549a78));
Owen Anderson9f944592009-08-11 20:47:22 +00004433 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendling648930b2008-09-10 00:20:20 +00004434
4435 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson9f944592009-08-11 20:47:22 +00004436 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4437 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendling648930b2008-09-10 00:20:20 +00004438
4439 // IntegerPartOfX <<= 23;
Owen Anderson9f944592009-08-11 20:47:22 +00004440 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands41826032009-01-31 15:50:11 +00004441 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendling648930b2008-09-10 00:20:20 +00004442
Craig Topper85719442012-11-25 00:15:07 +00004443 SDValue TwoToFractionalPartOfX;
Bill Wendling648930b2008-09-10 00:20:20 +00004444 if (LimitFloatPrecision <= 6) {
4445 // For floating-point precision of 6:
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004446 //
Bill Wendling648930b2008-09-10 00:20:20 +00004447 // twoToFractionalPartOfX =
4448 // 0.997535578f +
4449 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004450 //
Bill Wendling648930b2008-09-10 00:20:20 +00004451 // error 0.0144103317, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004452 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004453 getF32Constant(DAG, 0x3e814304));
Owen Anderson9f944592009-08-11 20:47:22 +00004454 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004455 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson9f944592009-08-11 20:47:22 +00004456 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper85719442012-11-25 00:15:07 +00004457 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4458 getF32Constant(DAG, 0x3f7f5e7e));
Craig Toppered756c52012-11-16 20:01:39 +00004459 } else if (LimitFloatPrecision <= 12) {
Bill Wendling648930b2008-09-10 00:20:20 +00004460 // For floating-point precision of 12:
4461 //
4462 // TwoToFractionalPartOfX =
4463 // 0.999892986f +
4464 // (0.696457318f +
4465 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4466 //
4467 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004468 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004469 getF32Constant(DAG, 0x3da235e3));
Owen Anderson9f944592009-08-11 20:47:22 +00004470 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004471 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson9f944592009-08-11 20:47:22 +00004472 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4473 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004474 getF32Constant(DAG, 0x3f324b07));
Owen Anderson9f944592009-08-11 20:47:22 +00004475 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper85719442012-11-25 00:15:07 +00004476 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4477 getF32Constant(DAG, 0x3f7ff8fd));
Craig Toppered756c52012-11-16 20:01:39 +00004478 } else { // LimitFloatPrecision <= 18
Bill Wendling648930b2008-09-10 00:20:20 +00004479 // For floating-point precision of 18:
4480 //
4481 // TwoToFractionalPartOfX =
4482 // 0.999999982f +
4483 // (0.693148872f +
4484 // (0.240227044f +
4485 // (0.554906021e-1f +
4486 // (0.961591928e-2f +
4487 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4488 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004489 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004490 getF32Constant(DAG, 0x3924b03e));
Owen Anderson9f944592009-08-11 20:47:22 +00004491 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004492 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson9f944592009-08-11 20:47:22 +00004493 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4494 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004495 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson9f944592009-08-11 20:47:22 +00004496 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4497 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004498 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson9f944592009-08-11 20:47:22 +00004499 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4500 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004501 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson9f944592009-08-11 20:47:22 +00004502 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4503 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004504 getF32Constant(DAG, 0x3f317234));
Owen Anderson9f944592009-08-11 20:47:22 +00004505 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topper85719442012-11-25 00:15:07 +00004506 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4507 getF32Constant(DAG, 0x3f800000));
Bill Wendling648930b2008-09-10 00:20:20 +00004508 }
Craig Topper85719442012-11-25 00:15:07 +00004509
4510 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
Craig Topper79bd2052012-11-25 08:08:58 +00004511 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4512 DAG.getNode(ISD::ADD, dl, MVT::i32,
4513 t13, IntegerPartOfX));
Bill Wendling648930b2008-09-10 00:20:20 +00004514 }
4515
Craig Topper79bd2052012-11-25 08:08:58 +00004516 // No special expansion.
4517 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
Bill Wendling648930b2008-09-10 00:20:20 +00004518}
4519
Chris Lattner39f18e52010-01-01 03:32:16 +00004520
4521/// ExpandPowI - Expand a llvm.powi intrinsic.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004522static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
Chris Lattner39f18e52010-01-01 03:32:16 +00004523 SelectionDAG &DAG) {
4524 // If RHS is a constant, we can expand this out to a multiplication tree,
4525 // otherwise we end up lowering to a call to __powidf2 (for example). When
4526 // optimizing for size, we only want to do this if the expansion would produce
4527 // a small number of multiplies, otherwise we do the full expansion.
4528 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4529 // Get the exponent as a positive value.
4530 unsigned Val = RHSC->getSExtValue();
4531 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004532
Chris Lattner39f18e52010-01-01 03:32:16 +00004533 // powi(x, 0) -> 1.0
4534 if (Val == 0)
4535 return DAG.getConstantFP(1.0, LHS.getValueType());
4536
Dan Gohman913c9982010-04-15 04:33:49 +00004537 const Function *F = DAG.getMachineFunction().getFunction();
Bill Wendling698e84f2012-12-30 10:32:01 +00004538 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
4539 Attribute::OptimizeForSize) ||
Chris Lattner39f18e52010-01-01 03:32:16 +00004540 // If optimizing for size, don't insert too many multiplies. This
4541 // inserts up to 5 multiplies.
4542 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4543 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004544 // sequence. There are more optimal ways to do this (for example,
Chris Lattner39f18e52010-01-01 03:32:16 +00004545 // powi(x,15) generates one more multiply than it should), but this has
4546 // the benefit of being both really simple and much better than a libcall.
4547 SDValue Res; // Logically starts equal to 1.0
4548 SDValue CurSquare = LHS;
4549 while (Val) {
Mikhail Glushenkov5c35d2f2010-01-01 04:41:36 +00004550 if (Val & 1) {
Chris Lattner39f18e52010-01-01 03:32:16 +00004551 if (Res.getNode())
4552 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4553 else
4554 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkov5c35d2f2010-01-01 04:41:36 +00004555 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004556
Chris Lattner39f18e52010-01-01 03:32:16 +00004557 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4558 CurSquare, CurSquare);
4559 Val >>= 1;
4560 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004561
Chris Lattner39f18e52010-01-01 03:32:16 +00004562 // If the original was negative, invert the result, producing 1/(x*x*x).
4563 if (RHSC->getSExtValue() < 0)
4564 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4565 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4566 return Res;
4567 }
4568 }
4569
4570 // Otherwise, expand to a libcall.
4571 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4572}
4573
Devang Patel8e60ff12011-05-16 21:24:05 +00004574// getTruncatedArgReg - Find underlying register used for an truncated
4575// argument.
4576static unsigned getTruncatedArgReg(const SDValue &N) {
4577 if (N.getOpcode() != ISD::TRUNCATE)
4578 return 0;
4579
4580 const SDValue &Ext = N.getOperand(0);
Stephen Lin6d715e82013-07-06 21:44:25 +00004581 if (Ext.getOpcode() == ISD::AssertZext ||
4582 Ext.getOpcode() == ISD::AssertSext) {
Devang Patel8e60ff12011-05-16 21:24:05 +00004583 const SDValue &CFR = Ext.getOperand(0);
4584 if (CFR.getOpcode() == ISD::CopyFromReg)
4585 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
Craig Topper692d5842012-04-11 04:55:51 +00004586 if (CFR.getOpcode() == ISD::TRUNCATE)
4587 return getTruncatedArgReg(CFR);
Devang Patel8e60ff12011-05-16 21:24:05 +00004588 }
4589 return 0;
4590}
4591
Evan Cheng6e822452010-04-28 23:08:54 +00004592/// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4593/// argument, create the corresponding DBG_VALUE machine instruction for it now.
4594/// At the end of instruction selection, they will be inserted to the entry BB.
Evan Cheng5fb45a22010-04-29 01:40:30 +00004595bool
Devang Patel3f53d6e2010-08-25 20:39:26 +00004596SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
Adrian Prantl32da8892014-04-25 20:49:25 +00004597 int64_t Offset, bool IsIndirect,
Dan Gohman63f31112010-05-01 00:33:16 +00004598 const SDValue &N) {
Devang Patel86ec8b32010-08-31 22:22:42 +00004599 const Argument *Arg = dyn_cast<Argument>(V);
4600 if (!Arg)
Evan Cheng5fb45a22010-04-29 01:40:30 +00004601 return false;
Evan Cheng6e822452010-04-28 23:08:54 +00004602
Devang Patel03955532010-04-29 20:40:36 +00004603 MachineFunction &MF = DAG.getMachineFunction();
Eric Christopherfc6de422014-08-05 02:39:49 +00004604 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
Devang Patel94f2a252010-11-02 17:01:30 +00004605
Devang Patela46953d2010-04-29 18:50:36 +00004606 // Ignore inlined function arguments here.
4607 DIVariable DV(Variable);
Devang Patel03955532010-04-29 20:40:36 +00004608 if (DV.isInlinedFnArgument(MF.getFunction()))
Devang Patela46953d2010-04-29 18:50:36 +00004609 return false;
4610
David Blaikie0252265b2013-06-16 20:34:15 +00004611 Optional<MachineOperand> Op;
Devang Patel9d904e12011-09-08 22:59:09 +00004612 // Some arguments' frame index is recorded during argument lowering.
David Blaikie0252265b2013-06-16 20:34:15 +00004613 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4614 Op = MachineOperand::CreateFI(FI);
Devang Patel86ec8b32010-08-31 22:22:42 +00004615
David Blaikie0252265b2013-06-16 20:34:15 +00004616 if (!Op && N.getNode()) {
4617 unsigned Reg;
Devang Patel8e60ff12011-05-16 21:24:05 +00004618 if (N.getOpcode() == ISD::CopyFromReg)
4619 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4620 else
4621 Reg = getTruncatedArgReg(N);
4622 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
Evan Cheng6e822452010-04-28 23:08:54 +00004623 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4624 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4625 if (PR)
4626 Reg = PR;
4627 }
David Blaikie0252265b2013-06-16 20:34:15 +00004628 if (Reg)
4629 Op = MachineOperand::CreateReg(Reg, false);
Evan Cheng6e822452010-04-28 23:08:54 +00004630 }
4631
David Blaikie0252265b2013-06-16 20:34:15 +00004632 if (!Op) {
Devang Patel94f2a252010-11-02 17:01:30 +00004633 // Check if ValueMap has reg number.
Evan Cheng923679f2010-04-29 06:33:38 +00004634 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
Devang Patelbc741402010-11-02 17:19:03 +00004635 if (VMI != FuncInfo.ValueMap.end())
David Blaikie0252265b2013-06-16 20:34:15 +00004636 Op = MachineOperand::CreateReg(VMI->second, false);
Evan Cheng923679f2010-04-29 06:33:38 +00004637 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004638
David Blaikie0252265b2013-06-16 20:34:15 +00004639 if (!Op && N.getNode())
Devang Patel94f2a252010-11-02 17:01:30 +00004640 // Check if frame index is available.
4641 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
Wesley Peck527da1b2010-11-23 03:31:01 +00004642 if (FrameIndexSDNode *FINode =
David Blaikie0252265b2013-06-16 20:34:15 +00004643 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4644 Op = MachineOperand::CreateFI(FINode->getIndex());
Devang Patelbc741402010-11-02 17:19:03 +00004645
David Blaikie0252265b2013-06-16 20:34:15 +00004646 if (!Op)
Devang Patelbc741402010-11-02 17:19:03 +00004647 return false;
Devang Patel94f2a252010-11-02 17:01:30 +00004648
David Blaikie0252265b2013-06-16 20:34:15 +00004649 if (Op->isReg())
Adrian Prantl418d1d12013-07-09 20:28:37 +00004650 FuncInfo.ArgDbgValues.push_back(BuildMI(MF, getCurDebugLoc(),
4651 TII->get(TargetOpcode::DBG_VALUE),
Adrian Prantlfacc9f42013-07-10 01:53:30 +00004652 IsIndirect,
Adrian Prantl418d1d12013-07-09 20:28:37 +00004653 Op->getReg(), Offset, Variable));
4654 else
4655 FuncInfo.ArgDbgValues.push_back(
David Blaikie0252265b2013-06-16 20:34:15 +00004656 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4657 .addOperand(*Op).addImm(Offset).addMetadata(Variable));
Adrian Prantl418d1d12013-07-09 20:28:37 +00004658
Evan Cheng5fb45a22010-04-29 01:40:30 +00004659 return true;
Evan Cheng6e822452010-04-28 23:08:54 +00004660}
Chris Lattner39f18e52010-01-01 03:32:16 +00004661
Douglas Gregor6739a892010-05-11 06:17:44 +00004662// VisualStudio defines setjmp as _setjmp
Michael J. Spencerded5f662010-09-24 19:48:47 +00004663#if defined(_MSC_VER) && defined(setjmp) && \
4664 !defined(setjmp_undefined_for_msvc)
4665# pragma push_macro("setjmp")
4666# undef setjmp
4667# define setjmp_undefined_for_msvc
Douglas Gregor6739a892010-05-11 06:17:44 +00004668#endif
4669
Dan Gohman575fad32008-09-03 16:12:24 +00004670/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4671/// we want to emit this as a call to a named external function, return the name
4672/// otherwise lower it and return null.
4673const char *
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004674SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
Eric Christopherd9134482014-08-04 21:25:23 +00004675 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004676 SDLoc sdl = getCurSDLoc();
Dale Johannesendb7c5f62009-01-31 02:22:37 +00004677 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb99b2692009-12-22 00:40:51 +00004678 SDValue Res;
4679
Dan Gohman575fad32008-09-03 16:12:24 +00004680 switch (Intrinsic) {
4681 default:
4682 // By default, turn this into a target intrinsic node.
4683 visitTargetIntrinsic(I, Intrinsic);
Craig Topperc0196b12014-04-14 00:51:57 +00004684 return nullptr;
4685 case Intrinsic::vastart: visitVAStart(I); return nullptr;
4686 case Intrinsic::vaend: visitVAEnd(I); return nullptr;
4687 case Intrinsic::vacopy: visitVACopy(I); return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004688 case Intrinsic::returnaddress:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004689 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI->getPointerTy(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004690 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004691 return nullptr;
Bill Wendlingc966a732008-09-26 22:10:44 +00004692 case Intrinsic::frameaddress:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004693 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI->getPointerTy(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004694 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004695 return nullptr;
Renato Golinc7aea402014-05-06 16:51:25 +00004696 case Intrinsic::read_register: {
4697 Value *Reg = I.getArgOperand(0);
4698 SDValue RegName = DAG.getMDNode(cast<MDNode>(Reg));
Eric Christopherd9134482014-08-04 21:25:23 +00004699 EVT VT =
4700 TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType());
Renato Golinc7aea402014-05-06 16:51:25 +00004701 setValue(&I, DAG.getNode(ISD::READ_REGISTER, sdl, VT, RegName));
4702 return nullptr;
4703 }
4704 case Intrinsic::write_register: {
4705 Value *Reg = I.getArgOperand(0);
4706 Value *RegValue = I.getArgOperand(1);
4707 SDValue Chain = getValue(RegValue).getOperand(0);
4708 SDValue RegName = DAG.getMDNode(cast<MDNode>(Reg));
4709 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4710 RegName, getValue(RegValue)));
4711 return nullptr;
4712 }
Dan Gohman575fad32008-09-03 16:12:24 +00004713 case Intrinsic::setjmp:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004714 return &"_setjmp"[!TLI->usesUnderscoreSetJmp()];
Dan Gohman575fad32008-09-03 16:12:24 +00004715 case Intrinsic::longjmp:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004716 return &"_longjmp"[!TLI->usesUnderscoreLongJmp()];
Chris Lattnerdd708342008-11-21 16:42:48 +00004717 case Intrinsic::memcpy: {
Mon P Wangc576ee92010-04-04 03:10:48 +00004718 // Assert for address < 256 since we support only user defined address
4719 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004720 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004721 < 256 &&
Gabor Greifeba0be72010-06-25 09:38:13 +00004722 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004723 < 256 &&
4724 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004725 SDValue Op1 = getValue(I.getArgOperand(0));
4726 SDValue Op2 = getValue(I.getArgOperand(1));
4727 SDValue Op3 = getValue(I.getArgOperand(2));
4728 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004729 if (!Align)
4730 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004731 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004732 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
Chris Lattner2510de22010-09-21 05:40:29 +00004733 MachinePointerInfo(I.getArgOperand(0)),
4734 MachinePointerInfo(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00004735 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004736 }
Chris Lattnerdd708342008-11-21 16:42:48 +00004737 case Intrinsic::memset: {
Mon P Wangc576ee92010-04-04 03:10:48 +00004738 // Assert for address < 256 since we support only user defined address
4739 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004740 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004741 < 256 &&
4742 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004743 SDValue Op1 = getValue(I.getArgOperand(0));
4744 SDValue Op2 = getValue(I.getArgOperand(1));
4745 SDValue Op3 = getValue(I.getArgOperand(2));
4746 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004747 if (!Align)
4748 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004749 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004750 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
Chris Lattner2510de22010-09-21 05:40:29 +00004751 MachinePointerInfo(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004752 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004753 }
Chris Lattnerdd708342008-11-21 16:42:48 +00004754 case Intrinsic::memmove: {
Mon P Wangc576ee92010-04-04 03:10:48 +00004755 // Assert for address < 256 since we support only user defined address
4756 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004757 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004758 < 256 &&
Gabor Greifeba0be72010-06-25 09:38:13 +00004759 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004760 < 256 &&
4761 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004762 SDValue Op1 = getValue(I.getArgOperand(0));
4763 SDValue Op2 = getValue(I.getArgOperand(1));
4764 SDValue Op3 = getValue(I.getArgOperand(2));
4765 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004766 if (!Align)
4767 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004768 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004769 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
Chris Lattner2510de22010-09-21 05:40:29 +00004770 MachinePointerInfo(I.getArgOperand(0)),
4771 MachinePointerInfo(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00004772 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004773 }
Bill Wendling65c0fd42009-02-13 02:16:35 +00004774 case Intrinsic::dbg_declare: {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004775 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Devang Pateldf45c7f2009-10-09 22:42:28 +00004776 MDNode *Variable = DI.getVariable();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004777 const Value *Address = DI.getAddress();
Manman Ren983a16c2013-06-28 05:43:10 +00004778 DIVariable DIVar(Variable);
4779 assert((!DIVar || DIVar.isVariable()) &&
4780 "Variable in DbgDeclareInst should be either null or a DIVariable.");
4781 if (!Address || !DIVar) {
Eric Christopherbe7a1012012-03-15 21:33:41 +00004782 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00004783 return nullptr;
Eric Christopherbe7a1012012-03-15 21:33:41 +00004784 }
Dale Johannesene0983522010-04-26 20:06:49 +00004785
Devang Patel3bffd522010-09-02 21:29:42 +00004786 // Check if address has undef value.
4787 if (isa<UndefValue>(Address) ||
4788 (Address->use_empty() && !isa<Argument>(Address))) {
Eric Christopher5c452052012-02-23 03:39:39 +00004789 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00004790 return nullptr;
Devang Patel3bffd522010-09-02 21:29:42 +00004791 }
4792
Dale Johannesene0983522010-04-26 20:06:49 +00004793 SDValue &N = NodeMap[Address];
Devang Patel86ec8b32010-08-31 22:22:42 +00004794 if (!N.getNode() && isa<Argument>(Address))
4795 // Check unused arguments map.
4796 N = UnusedArgNodeMap[Address];
Dale Johannesene0983522010-04-26 20:06:49 +00004797 SDDbgValue *SDV;
4798 if (N.getNode()) {
Devang Patel98d3edf2010-09-02 21:02:27 +00004799 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4800 Address = BCI->getOperand(0);
Eric Christopherda970542012-02-24 01:59:08 +00004801 // Parameters are handled specially.
4802 bool isParameter =
4803 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4804 isa<Argument>(Address));
4805
Devang Patel98d3edf2010-09-02 21:02:27 +00004806 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4807
Dale Johannesene0983522010-04-26 20:06:49 +00004808 if (isParameter && !AI) {
4809 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4810 if (FINode)
4811 // Byval parameter. We have a frame index at this point.
Adrian Prantl32da8892014-04-25 20:49:25 +00004812 SDV = DAG.getFrameIndexDbgValue(Variable, FINode->getIndex(),
4813 0, dl, SDNodeOrder);
Devang Patelc24048a2010-12-06 22:39:26 +00004814 else {
Devang Patel8e60ff12011-05-16 21:24:05 +00004815 // Address is an argument, so try to emit its dbg value using
4816 // virtual register info from the FuncInfo.ValueMap.
Adrian Prantl32da8892014-04-25 20:49:25 +00004817 EmitFuncArgumentDbgValue(Address, Variable, 0, false, N);
Craig Topperc0196b12014-04-14 00:51:57 +00004818 return nullptr;
Devang Patelc24048a2010-12-06 22:39:26 +00004819 }
Dale Johannesene0983522010-04-26 20:06:49 +00004820 } else if (AI)
4821 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
Adrian Prantl32da8892014-04-25 20:49:25 +00004822 true, 0, dl, SDNodeOrder);
Devang Patelc24048a2010-12-06 22:39:26 +00004823 else {
Dale Johannesene0983522010-04-26 20:06:49 +00004824 // Can't do anything with other non-AI cases yet.
Eric Christopher5c452052012-02-23 03:39:39 +00004825 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Eric Christopherda970542012-02-24 01:59:08 +00004826 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4827 DEBUG(Address->dump());
Craig Topperc0196b12014-04-14 00:51:57 +00004828 return nullptr;
Devang Patelc24048a2010-12-06 22:39:26 +00004829 }
Dale Johannesene0983522010-04-26 20:06:49 +00004830 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4831 } else {
Gabor Greif47a3b8c2010-10-01 10:32:19 +00004832 // If Address is an argument then try to emit its dbg value using
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00004833 // virtual register info from the FuncInfo.ValueMap.
Adrian Prantl32da8892014-04-25 20:49:25 +00004834 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, false, N)) {
Devang Patelda25de82010-09-15 14:48:53 +00004835 // If variable is pinned by a alloca in dominating bb then
4836 // use StaticAllocaMap.
4837 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
Devang Patel46b96c42010-09-15 18:13:55 +00004838 if (AI->getParent() != DI.getParent()) {
4839 DenseMap<const AllocaInst*, int>::iterator SI =
4840 FuncInfo.StaticAllocaMap.find(AI);
4841 if (SI != FuncInfo.StaticAllocaMap.end()) {
Adrian Prantl32da8892014-04-25 20:49:25 +00004842 SDV = DAG.getFrameIndexDbgValue(Variable, SI->second,
4843 0, dl, SDNodeOrder);
Craig Topperc0196b12014-04-14 00:51:57 +00004844 DAG.AddDbgValue(SDV, nullptr, false);
4845 return nullptr;
Devang Patel46b96c42010-09-15 18:13:55 +00004846 }
Devang Patelda25de82010-09-15 14:48:53 +00004847 }
4848 }
Eric Christopher18c6be72012-02-23 03:39:43 +00004849 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patelea134f52010-08-26 22:53:27 +00004850 }
Dale Johannesene0983522010-04-26 20:06:49 +00004851 }
Craig Topperc0196b12014-04-14 00:51:57 +00004852 return nullptr;
Bill Wendling65c0fd42009-02-13 02:16:35 +00004853 }
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004854 case Intrinsic::dbg_value: {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004855 const DbgValueInst &DI = cast<DbgValueInst>(I);
Manman Ren983a16c2013-06-28 05:43:10 +00004856 DIVariable DIVar(DI.getVariable());
4857 assert((!DIVar || DIVar.isVariable()) &&
4858 "Variable in DbgValueInst should be either null or a DIVariable.");
4859 if (!DIVar)
Craig Topperc0196b12014-04-14 00:51:57 +00004860 return nullptr;
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004861
4862 MDNode *Variable = DI.getVariable();
Devang Patelf2bce7c2010-03-15 19:15:44 +00004863 uint64_t Offset = DI.getOffset();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004864 const Value *V = DI.getValue();
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004865 if (!V)
Craig Topperc0196b12014-04-14 00:51:57 +00004866 return nullptr;
Devang Patelf2bce7c2010-03-15 19:15:44 +00004867
Dale Johannesene0983522010-04-26 20:06:49 +00004868 SDDbgValue *SDV;
Devang Patelaab841c2011-08-03 23:13:55 +00004869 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
Adrian Prantl32da8892014-04-25 20:49:25 +00004870 SDV = DAG.getConstantDbgValue(Variable, V, Offset, dl, SDNodeOrder);
Craig Topperc0196b12014-04-14 00:51:57 +00004871 DAG.AddDbgValue(SDV, nullptr, false);
Devang Patelf2bce7c2010-03-15 19:15:44 +00004872 } else {
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00004873 // Do not use getValue() in here; we don't want to generate code at
4874 // this point if it hasn't been done yet.
Devang Patelb0c76392010-06-01 19:59:01 +00004875 SDValue N = NodeMap[V];
4876 if (!N.getNode() && isa<Argument>(V))
4877 // Check unused arguments map.
4878 N = UnusedArgNodeMap[V];
Dale Johannesene0983522010-04-26 20:06:49 +00004879 if (N.getNode()) {
Adrian Prantl32da8892014-04-25 20:49:25 +00004880 // A dbg.value for an alloca is always indirect.
4881 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
4882 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, IsIndirect, N)) {
Evan Cheng5fb45a22010-04-29 01:40:30 +00004883 SDV = DAG.getDbgValue(Variable, N.getNode(),
Adrian Prantl32da8892014-04-25 20:49:25 +00004884 N.getResNo(), IsIndirect,
4885 Offset, dl, SDNodeOrder);
Evan Cheng5fb45a22010-04-29 01:40:30 +00004886 DAG.AddDbgValue(SDV, N.getNode(), false);
4887 }
Devang Patelb7ae3cc2011-02-18 22:43:42 +00004888 } else if (!V->use_empty() ) {
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00004889 // Do not call getValue(V) yet, as we don't want to generate code.
4890 // Remember it for later.
4891 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4892 DanglingDebugInfoMap[V] = DDI;
Devang Patelf2855b12010-08-27 22:25:51 +00004893 } else {
Devang Patelf2bce7c2010-03-15 19:15:44 +00004894 // We may expand this to cover more cases. One case where we have no
Devang Patelc24048a2010-12-06 22:39:26 +00004895 // data available is an unreferenced parameter.
Eric Christopher18c6be72012-02-23 03:39:43 +00004896 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesene0983522010-04-26 20:06:49 +00004897 }
Devang Patelf2bce7c2010-03-15 19:15:44 +00004898 }
4899
4900 // Build a debug info table entry.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004901 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004902 V = BCI->getOperand(0);
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004903 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004904 // Don't handle byval struct arguments or VLAs, for example.
Eric Christopherc1e2dcd2012-03-26 06:10:32 +00004905 if (!AI) {
Eric Christopher24a62982012-03-28 07:34:36 +00004906 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4907 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00004908 return nullptr;
Eric Christopherc1e2dcd2012-03-26 06:10:32 +00004909 }
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004910 DenseMap<const AllocaInst*, int>::iterator SI =
4911 FuncInfo.StaticAllocaMap.find(AI);
4912 if (SI == FuncInfo.StaticAllocaMap.end())
Craig Topperc0196b12014-04-14 00:51:57 +00004913 return nullptr; // VLAs.
Craig Topperc0196b12014-04-14 00:51:57 +00004914 return nullptr;
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004915 }
Dan Gohman575fad32008-09-03 16:12:24 +00004916
Duncan Sands8e6ccb62009-10-14 16:11:37 +00004917 case Intrinsic::eh_typeid_for: {
Chris Lattnerfb964e52010-04-05 06:19:28 +00004918 // Find the type id for the given typeinfo.
Gabor Greifeba0be72010-06-25 09:38:13 +00004919 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
Chris Lattnerfb964e52010-04-05 06:19:28 +00004920 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4921 Res = DAG.getConstant(TypeID, MVT::i32);
Bill Wendlingb99b2692009-12-22 00:40:51 +00004922 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00004923 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004924 }
4925
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004926 case Intrinsic::eh_return_i32:
4927 case Intrinsic::eh_return_i64:
Chris Lattnerfb964e52010-04-05 06:19:28 +00004928 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004929 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
Chris Lattnerfb964e52010-04-05 06:19:28 +00004930 MVT::Other,
4931 getControlRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004932 getValue(I.getArgOperand(0)),
4933 getValue(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00004934 return nullptr;
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004935 case Intrinsic::eh_unwind_init:
Chris Lattnerfb964e52010-04-05 06:19:28 +00004936 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
Craig Topperc0196b12014-04-14 00:51:57 +00004937 return nullptr;
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004938 case Intrinsic::eh_dwarf_cfa: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004939 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004940 TLI->getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004941 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
Tom Stellard838e2342013-08-26 15:06:10 +00004942 CfaArg.getValueType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004943 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
Tom Stellard838e2342013-08-26 15:06:10 +00004944 CfaArg.getValueType()),
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004945 CfaArg);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004946 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00004947 TLI->getPointerTy(),
4948 DAG.getConstant(0, TLI->getPointerTy()));
Tom Stellard838e2342013-08-26 15:06:10 +00004949 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
Bill Wendling954cb182010-01-28 21:51:40 +00004950 FA, Offset));
Craig Topperc0196b12014-04-14 00:51:57 +00004951 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004952 }
Jim Grosbach54c05302010-01-28 01:45:32 +00004953 case Intrinsic::eh_sjlj_callsite: {
Chris Lattnerfb964e52010-04-05 06:19:28 +00004954 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Gabor Greifeba0be72010-06-25 09:38:13 +00004955 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
Jim Grosbach54c05302010-01-28 01:45:32 +00004956 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
Chris Lattnerfb964e52010-04-05 06:19:28 +00004957 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
Jim Grosbach54c05302010-01-28 01:45:32 +00004958
Chris Lattnerfb964e52010-04-05 06:19:28 +00004959 MMI.setCurrentCallSite(CI->getZExtValue());
Craig Topperc0196b12014-04-14 00:51:57 +00004960 return nullptr;
Jim Grosbach54c05302010-01-28 01:45:32 +00004961 }
Bill Wendling66b110f2011-09-28 03:36:43 +00004962 case Intrinsic::eh_sjlj_functioncontext: {
4963 // Get and store the index of the function context.
4964 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
Bill Wendlingbaf39412011-09-28 03:52:41 +00004965 AllocaInst *FnCtx =
4966 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
Bill Wendling66b110f2011-09-28 03:36:43 +00004967 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4968 MFI->setFunctionContextIndex(FI);
Craig Topperc0196b12014-04-14 00:51:57 +00004969 return nullptr;
Bill Wendling66b110f2011-09-28 03:36:43 +00004970 }
Jim Grosbachc98892f2010-05-26 20:22:18 +00004971 case Intrinsic::eh_sjlj_setjmp: {
Bill Wendling7ecfbd92011-10-07 21:25:38 +00004972 SDValue Ops[2];
4973 Ops[0] = getRoot();
4974 Ops[1] = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004975 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
Craig Topper48d114b2014-04-26 18:35:24 +00004976 DAG.getVTList(MVT::i32, MVT::Other), Ops);
Bill Wendling7ecfbd92011-10-07 21:25:38 +00004977 setValue(&I, Op.getValue(0));
4978 DAG.setRoot(Op.getValue(1));
Craig Topperc0196b12014-04-14 00:51:57 +00004979 return nullptr;
Jim Grosbachc98892f2010-05-26 20:22:18 +00004980 }
Jim Grosbachbd9485d2010-05-22 01:06:18 +00004981 case Intrinsic::eh_sjlj_longjmp: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004982 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
Jim Grosbachbbdc5d22010-10-19 23:27:08 +00004983 getRoot(), getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004984 return nullptr;
Jim Grosbachbbdc5d22010-10-19 23:27:08 +00004985 }
Jim Grosbach54c05302010-01-28 01:45:32 +00004986
Dale Johannesendd224d22010-09-30 23:57:10 +00004987 case Intrinsic::x86_mmx_pslli_w:
4988 case Intrinsic::x86_mmx_pslli_d:
4989 case Intrinsic::x86_mmx_pslli_q:
4990 case Intrinsic::x86_mmx_psrli_w:
4991 case Intrinsic::x86_mmx_psrli_d:
4992 case Intrinsic::x86_mmx_psrli_q:
4993 case Intrinsic::x86_mmx_psrai_w:
4994 case Intrinsic::x86_mmx_psrai_d: {
4995 SDValue ShAmt = getValue(I.getArgOperand(1));
4996 if (isa<ConstantSDNode>(ShAmt)) {
4997 visitTargetIntrinsic(I, Intrinsic);
Craig Topperc0196b12014-04-14 00:51:57 +00004998 return nullptr;
Dale Johannesendd224d22010-09-30 23:57:10 +00004999 }
5000 unsigned NewIntrinsic = 0;
5001 EVT ShAmtVT = MVT::v2i32;
5002 switch (Intrinsic) {
5003 case Intrinsic::x86_mmx_pslli_w:
5004 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5005 break;
5006 case Intrinsic::x86_mmx_pslli_d:
5007 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5008 break;
5009 case Intrinsic::x86_mmx_pslli_q:
5010 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5011 break;
5012 case Intrinsic::x86_mmx_psrli_w:
5013 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5014 break;
5015 case Intrinsic::x86_mmx_psrli_d:
5016 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5017 break;
5018 case Intrinsic::x86_mmx_psrli_q:
5019 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5020 break;
5021 case Intrinsic::x86_mmx_psrai_w:
5022 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5023 break;
5024 case Intrinsic::x86_mmx_psrai_d:
5025 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5026 break;
5027 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5028 }
5029
5030 // The vector shift intrinsics with scalars uses 32b shift amounts but
5031 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5032 // to be zero.
5033 // We must do this early because v2i32 is not a legal type.
Dale Johannesendd224d22010-09-30 23:57:10 +00005034 SDValue ShOps[2];
5035 ShOps[0] = ShAmt;
5036 ShOps[1] = DAG.getConstant(0, MVT::i32);
Craig Topper48d114b2014-04-26 18:35:24 +00005037 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005038 EVT DestVT = TLI->getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005039 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5040 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
Dale Johannesendd224d22010-09-30 23:57:10 +00005041 DAG.getConstant(NewIntrinsic, MVT::i32),
5042 getValue(I.getArgOperand(0)), ShAmt);
5043 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005044 return nullptr;
Dale Johannesendd224d22010-09-30 23:57:10 +00005045 }
Pete Cooper682c76b2012-02-24 03:51:49 +00005046 case Intrinsic::x86_avx_vinsertf128_pd_256:
5047 case Intrinsic::x86_avx_vinsertf128_ps_256:
Craig Topperd024cef2012-04-07 22:32:29 +00005048 case Intrinsic::x86_avx_vinsertf128_si_256:
5049 case Intrinsic::x86_avx2_vinserti128: {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005050 EVT DestVT = TLI->getValueType(I.getType());
5051 EVT ElVT = TLI->getValueType(I.getArgOperand(1)->getType());
Pete Cooper682c76b2012-02-24 03:51:49 +00005052 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
5053 ElVT.getVectorNumElements();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005054 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
Pete Cooper682c76b2012-02-24 03:51:49 +00005055 getValue(I.getArgOperand(0)),
5056 getValue(I.getArgOperand(1)),
Tom Stellardd42c5942013-08-05 22:22:01 +00005057 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
Craig Topper2db23532012-09-05 05:48:09 +00005058 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005059 return nullptr;
Craig Topper2db23532012-09-05 05:48:09 +00005060 }
5061 case Intrinsic::x86_avx_vextractf128_pd_256:
5062 case Intrinsic::x86_avx_vextractf128_ps_256:
5063 case Intrinsic::x86_avx_vextractf128_si_256:
5064 case Intrinsic::x86_avx2_vextracti128: {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005065 EVT DestVT = TLI->getValueType(I.getType());
Craig Topper2db23532012-09-05 05:48:09 +00005066 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
5067 DestVT.getVectorNumElements();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005068 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
Craig Topper2db23532012-09-05 05:48:09 +00005069 getValue(I.getArgOperand(0)),
Tom Stellardd42c5942013-08-05 22:22:01 +00005070 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
Pete Cooper682c76b2012-02-24 03:51:49 +00005071 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005072 return nullptr;
Pete Cooper682c76b2012-02-24 03:51:49 +00005073 }
Mon P Wang58fb9132008-11-10 20:54:11 +00005074 case Intrinsic::convertff:
5075 case Intrinsic::convertfsi:
5076 case Intrinsic::convertfui:
5077 case Intrinsic::convertsif:
5078 case Intrinsic::convertuif:
5079 case Intrinsic::convertss:
5080 case Intrinsic::convertsu:
5081 case Intrinsic::convertus:
5082 case Intrinsic::convertuu: {
5083 ISD::CvtCode Code = ISD::CVT_INVALID;
5084 switch (Intrinsic) {
Craig Topperbc680062012-04-11 04:34:11 +00005085 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
Mon P Wang58fb9132008-11-10 20:54:11 +00005086 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
5087 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
5088 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
5089 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
5090 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
5091 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
5092 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
5093 case Intrinsic::convertus: Code = ISD::CVT_US; break;
5094 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
5095 }
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005096 EVT DestVT = TLI->getValueType(I.getType());
Gabor Greifeba0be72010-06-25 09:38:13 +00005097 const Value *Op1 = I.getArgOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005098 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
Bill Wendlingb99b2692009-12-22 00:40:51 +00005099 DAG.getValueType(DestVT),
5100 DAG.getValueType(getValue(Op1).getValueType()),
Gabor Greifeba0be72010-06-25 09:38:13 +00005101 getValue(I.getArgOperand(1)),
5102 getValue(I.getArgOperand(2)),
Bill Wendlingb99b2692009-12-22 00:40:51 +00005103 Code);
5104 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005105 return nullptr;
Mon P Wang58fb9132008-11-10 20:54:11 +00005106 }
Dan Gohman575fad32008-09-03 16:12:24 +00005107 case Intrinsic::powi:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005108 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
Gabor Greifeba0be72010-06-25 09:38:13 +00005109 getValue(I.getArgOperand(1)), DAG));
Craig Topperc0196b12014-04-14 00:51:57 +00005110 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005111 case Intrinsic::log:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005112 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005113 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005114 case Intrinsic::log2:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005115 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005116 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005117 case Intrinsic::log10:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005118 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005119 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005120 case Intrinsic::exp:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005121 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005122 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005123 case Intrinsic::exp2:
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005124 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005125 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005126 case Intrinsic::pow:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005127 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005128 getValue(I.getArgOperand(1)), DAG, *TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005129 return nullptr;
Craig Topperae894262012-11-16 07:48:23 +00005130 case Intrinsic::sqrt:
Peter Collingbourne913869b2012-05-28 21:48:37 +00005131 case Intrinsic::fabs:
Craig Topperae894262012-11-16 07:48:23 +00005132 case Intrinsic::sin:
5133 case Intrinsic::cos:
Dan Gohman0b3d7822012-07-26 17:43:27 +00005134 case Intrinsic::floor:
Craig Topper61d04572012-11-15 06:51:10 +00005135 case Intrinsic::ceil:
Craig Topper61d04572012-11-15 06:51:10 +00005136 case Intrinsic::trunc:
Craig Topper61d04572012-11-15 06:51:10 +00005137 case Intrinsic::rint:
Hal Finkel171817e2013-08-07 22:49:12 +00005138 case Intrinsic::nearbyint:
5139 case Intrinsic::round: {
Craig Topperae894262012-11-16 07:48:23 +00005140 unsigned Opcode;
5141 switch (Intrinsic) {
5142 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5143 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5144 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5145 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5146 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5147 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5148 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5149 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5150 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5151 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
Hal Finkel171817e2013-08-07 22:49:12 +00005152 case Intrinsic::round: Opcode = ISD::FROUND; break;
Craig Topperae894262012-11-16 07:48:23 +00005153 }
5154
Andrew Trickef9de2a2013-05-25 02:42:55 +00005155 setValue(&I, DAG.getNode(Opcode, sdl,
Craig Topper61d04572012-11-15 06:51:10 +00005156 getValue(I.getArgOperand(0)).getValueType(),
5157 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00005158 return nullptr;
Craig Topperae894262012-11-16 07:48:23 +00005159 }
Hal Finkel0c5c01aa2013-08-19 23:35:46 +00005160 case Intrinsic::copysign:
5161 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5162 getValue(I.getArgOperand(0)).getValueType(),
5163 getValue(I.getArgOperand(0)),
5164 getValue(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00005165 return nullptr;
Cameron Zwarichf03fa182011-07-08 21:39:21 +00005166 case Intrinsic::fma:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005167 setValue(&I, DAG.getNode(ISD::FMA, sdl,
Cameron Zwarichf03fa182011-07-08 21:39:21 +00005168 getValue(I.getArgOperand(0)).getValueType(),
5169 getValue(I.getArgOperand(0)),
5170 getValue(I.getArgOperand(1)),
5171 getValue(I.getArgOperand(2))));
Craig Topperc0196b12014-04-14 00:51:57 +00005172 return nullptr;
Lang Hamesa59100c2012-06-05 19:07:46 +00005173 case Intrinsic::fmuladd: {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005174 EVT VT = TLI->getValueType(I.getType());
Lang Hamesb8650f12012-06-22 01:09:09 +00005175 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00005176 TLI->isFMAFasterThanFMulAndFAdd(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005177 setValue(&I, DAG.getNode(ISD::FMA, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005178 getValue(I.getArgOperand(0)).getValueType(),
5179 getValue(I.getArgOperand(0)),
5180 getValue(I.getArgOperand(1)),
5181 getValue(I.getArgOperand(2))));
5182 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005183 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005184 getValue(I.getArgOperand(0)).getValueType(),
5185 getValue(I.getArgOperand(0)),
5186 getValue(I.getArgOperand(1)));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005187 SDValue Add = DAG.getNode(ISD::FADD, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005188 getValue(I.getArgOperand(0)).getValueType(),
5189 Mul,
5190 getValue(I.getArgOperand(2)));
5191 setValue(&I, Add);
5192 }
Craig Topperc0196b12014-04-14 00:51:57 +00005193 return nullptr;
Lang Hamesa59100c2012-06-05 19:07:46 +00005194 }
Anton Korobeynikov39ed49d2010-03-14 18:42:15 +00005195 case Intrinsic::convert_to_fp16:
Tim Northoverf7a02c12014-07-21 09:13:56 +00005196 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5197 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5198 getValue(I.getArgOperand(0)),
5199 DAG.getTargetConstant(0, MVT::i32))));
Craig Topperc0196b12014-04-14 00:51:57 +00005200 return nullptr;
Anton Korobeynikov39ed49d2010-03-14 18:42:15 +00005201 case Intrinsic::convert_from_fp16:
Tim Northoverfd7e4242014-07-17 10:51:23 +00005202 setValue(&I,
Tim Northoverf7a02c12014-07-21 09:13:56 +00005203 DAG.getNode(ISD::FP_EXTEND, sdl, TLI->getValueType(I.getType()),
5204 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5205 getValue(I.getArgOperand(0)))));
Craig Topperc0196b12014-04-14 00:51:57 +00005206 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005207 case Intrinsic::pcmarker: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005208 SDValue Tmp = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005209 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
Craig Topperc0196b12014-04-14 00:51:57 +00005210 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005211 }
5212 case Intrinsic::readcyclecounter: {
5213 SDValue Op = getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005214 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
Craig Topper48d114b2014-04-26 18:35:24 +00005215 DAG.getVTList(MVT::i64, MVT::Other), Op);
Bill Wendlingb99b2692009-12-22 00:40:51 +00005216 setValue(&I, Res);
5217 DAG.setRoot(Res.getValue(1));
Craig Topperc0196b12014-04-14 00:51:57 +00005218 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005219 }
Dan Gohman575fad32008-09-03 16:12:24 +00005220 case Intrinsic::bswap:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005221 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
Gabor Greifeba0be72010-06-25 09:38:13 +00005222 getValue(I.getArgOperand(0)).getValueType(),
5223 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00005224 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005225 case Intrinsic::cttz: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005226 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005227 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005228 EVT Ty = Arg.getValueType();
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005229 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005230 sdl, Ty, Arg));
Craig Topperc0196b12014-04-14 00:51:57 +00005231 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005232 }
5233 case Intrinsic::ctlz: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005234 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005235 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005236 EVT Ty = Arg.getValueType();
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005237 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005238 sdl, Ty, Arg));
Craig Topperc0196b12014-04-14 00:51:57 +00005239 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005240 }
5241 case Intrinsic::ctpop: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005242 SDValue Arg = getValue(I.getArgOperand(0));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005243 EVT Ty = Arg.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005244 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
Craig Topperc0196b12014-04-14 00:51:57 +00005245 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005246 }
5247 case Intrinsic::stacksave: {
5248 SDValue Op = getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005249 Res = DAG.getNode(ISD::STACKSAVE, sdl,
Craig Topper48d114b2014-04-26 18:35:24 +00005250 DAG.getVTList(TLI->getPointerTy(), MVT::Other), Op);
Bill Wendlingb99b2692009-12-22 00:40:51 +00005251 setValue(&I, Res);
5252 DAG.setRoot(Res.getValue(1));
Craig Topperc0196b12014-04-14 00:51:57 +00005253 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005254 }
5255 case Intrinsic::stackrestore: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005256 Res = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005257 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
Craig Topperc0196b12014-04-14 00:51:57 +00005258 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005259 }
Bill Wendling13020d22008-11-18 11:01:33 +00005260 case Intrinsic::stackprotector: {
Bill Wendlingd970ea32008-11-06 02:29:10 +00005261 // Emit code into the DAG to store the stack guard onto the stack.
5262 MachineFunction &MF = DAG.getMachineFunction();
5263 MachineFrameInfo *MFI = MF.getFrameInfo();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005264 EVT PtrTy = TLI->getPointerTy();
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005265 SDValue Src, Chain = getRoot();
Bill Wendlingd970ea32008-11-06 02:29:10 +00005266
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005267 if (TLI->useLoadStackGuardNode()) {
5268 // Emit a LOAD_STACK_GUARD node.
5269 MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
5270 sdl, PtrTy, Chain);
5271 LoadInst *LI = cast<LoadInst>(I.getArgOperand(0));
5272 MachinePointerInfo MPInfo(LI->getPointerOperand());
5273 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
5274 unsigned Flags = MachineMemOperand::MOLoad |
5275 MachineMemOperand::MOInvariant;
5276 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
5277 PtrTy.getSizeInBits() / 8,
5278 DAG.getEVTAlignment(PtrTy));
5279 Node->setMemRefs(MemRefs, MemRefs + 1);
5280
5281 // Copy the guard value to a virtual register so that it can be
5282 // retrieved in the epilogue.
5283 Src = SDValue(Node, 0);
5284 const TargetRegisterClass *RC =
5285 TLI->getRegClassFor(Src.getSimpleValueType());
5286 unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
5287
5288 SPDescriptor.setGuardReg(Reg);
5289 Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
5290 } else {
5291 Src = getValue(I.getArgOperand(0)); // The guard's value.
5292 }
5293
Gabor Greifeba0be72010-06-25 09:38:13 +00005294 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
Bill Wendlingd970ea32008-11-06 02:29:10 +00005295
Bill Wendlingeb4268d2008-11-07 01:23:58 +00005296 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingd970ea32008-11-06 02:29:10 +00005297 MFI->setStackProtectorIndex(FI);
5298
5299 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5300
5301 // Store the stack protector onto the stack.
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005302 Res = DAG.getStore(Chain, sdl, Src, FIN,
Chris Lattnera4f19972010-09-21 18:58:22 +00005303 MachinePointerInfo::getFixedStack(FI),
5304 true, false, 0);
Bill Wendlingb99b2692009-12-22 00:40:51 +00005305 setValue(&I, Res);
5306 DAG.setRoot(Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005307 return nullptr;
Bill Wendlingd970ea32008-11-06 02:29:10 +00005308 }
Eric Christopher7a50b282009-10-27 00:52:25 +00005309 case Intrinsic::objectsize: {
5310 // If we don't know by now, we're never going to know.
Gabor Greifeba0be72010-06-25 09:38:13 +00005311 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
Eric Christopher7a50b282009-10-27 00:52:25 +00005312
5313 assert(CI && "Non-constant type in __builtin_object_size?");
5314
Gabor Greifeba0be72010-06-25 09:38:13 +00005315 SDValue Arg = getValue(I.getCalledValue());
Eric Christopher1fd4c572009-10-28 21:32:16 +00005316 EVT Ty = Arg.getValueType();
5317
Dan Gohmanf1d83042010-06-18 14:22:04 +00005318 if (CI->isZero())
Bill Wendlingb99b2692009-12-22 00:40:51 +00005319 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7a50b282009-10-27 00:52:25 +00005320 else
Bill Wendlingb99b2692009-12-22 00:40:51 +00005321 Res = DAG.getConstant(0, Ty);
5322
5323 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005324 return nullptr;
Eric Christopher7a50b282009-10-27 00:52:25 +00005325 }
Justin Holewinskifff1f5f2013-05-21 14:37:16 +00005326 case Intrinsic::annotation:
5327 case Intrinsic::ptr_annotation:
5328 // Drop the intrinsic, but forward the value
5329 setValue(&I, getValue(I.getOperand(0)));
Craig Topperc0196b12014-04-14 00:51:57 +00005330 return nullptr;
Hal Finkel93046912014-07-25 21:13:35 +00005331 case Intrinsic::assume:
Dan Gohman575fad32008-09-03 16:12:24 +00005332 case Intrinsic::var_annotation:
Hal Finkel93046912014-07-25 21:13:35 +00005333 // Discard annotate attributes and assumptions
Craig Topperc0196b12014-04-14 00:51:57 +00005334 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005335
5336 case Intrinsic::init_trampoline: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005337 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
Dan Gohman575fad32008-09-03 16:12:24 +00005338
5339 SDValue Ops[6];
5340 Ops[0] = getRoot();
Gabor Greifeba0be72010-06-25 09:38:13 +00005341 Ops[1] = getValue(I.getArgOperand(0));
5342 Ops[2] = getValue(I.getArgOperand(1));
5343 Ops[3] = getValue(I.getArgOperand(2));
5344 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
Dan Gohman575fad32008-09-03 16:12:24 +00005345 Ops[5] = DAG.getSrcValue(F);
5346
Craig Topper48d114b2014-04-26 18:35:24 +00005347 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
Dan Gohman575fad32008-09-03 16:12:24 +00005348
Duncan Sandsa0984362011-09-06 13:37:06 +00005349 DAG.setRoot(Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005350 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00005351 }
5352 case Intrinsic::adjust_trampoline: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005353 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005354 TLI->getPointerTy(),
Duncan Sandsa0984362011-09-06 13:37:06 +00005355 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00005356 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005357 }
Dan Gohman575fad32008-09-03 16:12:24 +00005358 case Intrinsic::gcroot:
5359 if (GFI) {
Bill Wendlingb6b50c62012-05-01 22:50:45 +00005360 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
Gabor Greifeba0be72010-06-25 09:38:13 +00005361 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00005362
Dan Gohman575fad32008-09-03 16:12:24 +00005363 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5364 GFI->addStackRoot(FI->getIndex(), TypeMap);
5365 }
Craig Topperc0196b12014-04-14 00:51:57 +00005366 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005367 case Intrinsic::gcread:
5368 case Intrinsic::gcwrite:
Torok Edwinfbcc6632009-07-14 16:55:14 +00005369 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Bill Wendlingb99b2692009-12-22 00:40:51 +00005370 case Intrinsic::flt_rounds:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005371 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
Craig Topperc0196b12014-04-14 00:51:57 +00005372 return nullptr;
Jakub Staszak3f158fd2011-07-06 18:22:43 +00005373
5374 case Intrinsic::expect: {
5375 // Just replace __builtin_expect(exp, c) with EXP.
5376 setValue(&I, getValue(I.getArgOperand(0)));
Craig Topperc0196b12014-04-14 00:51:57 +00005377 return nullptr;
Jakub Staszak3f158fd2011-07-06 18:22:43 +00005378 }
5379
Shuxin Yangcdde0592012-10-19 20:11:16 +00005380 case Intrinsic::debugtrap:
Evan Cheng74d92c12011-04-08 21:37:21 +00005381 case Intrinsic::trap: {
Nick Lewycky50f02cb2011-12-02 22:16:29 +00005382 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
Evan Cheng74d92c12011-04-08 21:37:21 +00005383 if (TrapFuncName.empty()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00005384 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
Shuxin Yangcdde0592012-10-19 20:11:16 +00005385 ISD::TRAP : ISD::DEBUGTRAP;
Andrew Trickef9de2a2013-05-25 02:42:55 +00005386 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
Craig Topperc0196b12014-04-14 00:51:57 +00005387 return nullptr;
Evan Cheng74d92c12011-04-08 21:37:21 +00005388 }
5389 TargetLowering::ArgListTy Args;
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00005390
5391 TargetLowering::CallLoweringInfo CLI(DAG);
5392 CLI.setDebugLoc(sdl).setChain(getRoot())
5393 .setCallee(CallingConv::C, I.getType(),
5394 DAG.getExternalSymbol(TrapFuncName.data(), TLI->getPointerTy()),
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00005395 std::move(Args), 0);
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00005396
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005397 std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
Evan Cheng74d92c12011-04-08 21:37:21 +00005398 DAG.setRoot(Result.second);
Craig Topperc0196b12014-04-14 00:51:57 +00005399 return nullptr;
Evan Cheng74d92c12011-04-08 21:37:21 +00005400 }
Shuxin Yangcdde0592012-10-19 20:11:16 +00005401
Bill Wendling5eee7442008-11-21 02:38:44 +00005402 case Intrinsic::uadd_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005403 case Intrinsic::sadd_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005404 case Intrinsic::usub_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005405 case Intrinsic::ssub_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005406 case Intrinsic::umul_with_overflow:
Craig Topperbc680062012-04-11 04:34:11 +00005407 case Intrinsic::smul_with_overflow: {
5408 ISD::NodeType Op;
5409 switch (Intrinsic) {
5410 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5411 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5412 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5413 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5414 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5415 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5416 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5417 }
5418 SDValue Op1 = getValue(I.getArgOperand(0));
5419 SDValue Op2 = getValue(I.getArgOperand(1));
Bill Wendling74296c62008-11-21 02:03:52 +00005420
Craig Topperbc680062012-04-11 04:34:11 +00005421 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005422 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
Craig Topperc0196b12014-04-14 00:51:57 +00005423 return nullptr;
Craig Topperbc680062012-04-11 04:34:11 +00005424 }
Dan Gohman575fad32008-09-03 16:12:24 +00005425 case Intrinsic::prefetch: {
Bruno Cardoso Lopesdc9ff3a2011-06-14 04:58:37 +00005426 SDValue Ops[5];
Dale Johannesene660f4d2010-10-26 23:11:10 +00005427 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
Dan Gohman575fad32008-09-03 16:12:24 +00005428 Ops[0] = getRoot();
Gabor Greifeba0be72010-06-25 09:38:13 +00005429 Ops[1] = getValue(I.getArgOperand(0));
5430 Ops[2] = getValue(I.getArgOperand(1));
5431 Ops[3] = getValue(I.getArgOperand(2));
Bruno Cardoso Lopesdc9ff3a2011-06-14 04:58:37 +00005432 Ops[4] = getValue(I.getArgOperand(3));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005433 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
Craig Topper206fcd42014-04-26 19:29:41 +00005434 DAG.getVTList(MVT::Other), Ops,
Dale Johannesene660f4d2010-10-26 23:11:10 +00005435 EVT::getIntegerVT(*Context, 8),
5436 MachinePointerInfo(I.getArgOperand(0)),
5437 0, /* align */
5438 false, /* volatile */
5439 rw==0, /* read */
5440 rw==1)); /* write */
Craig Topperc0196b12014-04-14 00:51:57 +00005441 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005442 }
Duncan Sandsdca0c282009-11-10 09:08:09 +00005443 case Intrinsic::lifetime_start:
Nadav Rotem7c277da2012-09-06 09:17:37 +00005444 case Intrinsic::lifetime_end: {
Nadav Rotem7c277da2012-09-06 09:17:37 +00005445 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
Nadav Rotemd753a952012-09-10 08:43:23 +00005446 // Stack coloring is not enabled in O0, discard region information.
5447 if (TM.getOptLevel() == CodeGenOpt::None)
Craig Topperc0196b12014-04-14 00:51:57 +00005448 return nullptr;
Nadav Rotem7c277da2012-09-06 09:17:37 +00005449
Nadav Rotemd753a952012-09-10 08:43:23 +00005450 SmallVector<Value *, 4> Allocas;
Rafael Espindola5f57f462014-02-21 18:34:28 +00005451 GetUnderlyingObjects(I.getArgOperand(1), Allocas, DL);
Nadav Rotemd753a952012-09-10 08:43:23 +00005452
Craig Toppere1c1d362013-07-03 05:11:49 +00005453 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5454 E = Allocas.end(); Object != E; ++Object) {
Nadav Rotemd753a952012-09-10 08:43:23 +00005455 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5456
5457 // Could not find an Alloca.
5458 if (!LifetimeObject)
5459 continue;
5460
5461 int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
5462
5463 SDValue Ops[2];
5464 Ops[0] = getRoot();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005465 Ops[1] = DAG.getFrameIndex(FI, TLI->getPointerTy(), true);
Nadav Rotemd753a952012-09-10 08:43:23 +00005466 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5467
Craig Topper48d114b2014-04-26 18:35:24 +00005468 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
Nadav Rotemd753a952012-09-10 08:43:23 +00005469 DAG.setRoot(Res);
5470 }
Craig Topperc0196b12014-04-14 00:51:57 +00005471 return nullptr;
Nadav Rotem7c277da2012-09-06 09:17:37 +00005472 }
5473 case Intrinsic::invariant_start:
Duncan Sandsdca0c282009-11-10 09:08:09 +00005474 // Discard region information.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005475 setValue(&I, DAG.getUNDEF(TLI->getPointerTy()));
Craig Topperc0196b12014-04-14 00:51:57 +00005476 return nullptr;
Duncan Sandsdca0c282009-11-10 09:08:09 +00005477 case Intrinsic::invariant_end:
Duncan Sandsdca0c282009-11-10 09:08:09 +00005478 // Discard region information.
Craig Topperc0196b12014-04-14 00:51:57 +00005479 return nullptr;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00005480 case Intrinsic::stackprotectorcheck: {
5481 // Do not actually emit anything for this basic block. Instead we initialize
5482 // the stack protector descriptor and export the guard variable so we can
5483 // access it in FinishBasicBlock.
5484 const BasicBlock *BB = I.getParent();
5485 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5486 ExportFromCurrentBlock(SPDescriptor.getGuard());
5487
5488 // Flush our exports since we are going to process a terminator.
5489 (void)getControlRoot();
Craig Topperc0196b12014-04-14 00:51:57 +00005490 return nullptr;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00005491 }
Renato Golinc0a3c1d2014-03-26 12:52:28 +00005492 case Intrinsic::clear_cache:
5493 return TLI->getClearCacheBuiltinName();
Nuno Lopesec9653b2012-06-28 22:30:12 +00005494 case Intrinsic::donothing:
5495 // ignore
Craig Topperc0196b12014-04-14 00:51:57 +00005496 return nullptr;
Andrew Trick74f4c742013-10-31 17:18:24 +00005497 case Intrinsic::experimental_stackmap: {
5498 visitStackmap(I);
Craig Topperc0196b12014-04-14 00:51:57 +00005499 return nullptr;
Andrew Trick74f4c742013-10-31 17:18:24 +00005500 }
5501 case Intrinsic::experimental_patchpoint_void:
5502 case Intrinsic::experimental_patchpoint_i64: {
5503 visitPatchpoint(I);
Craig Topperc0196b12014-04-14 00:51:57 +00005504 return nullptr;
Andrew Trick74f4c742013-10-31 17:18:24 +00005505 }
Dan Gohman575fad32008-09-03 16:12:24 +00005506 }
5507}
5508
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005509void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00005510 bool isTailCall,
5511 MachineBasicBlock *LandingPad) {
Eric Christopherd9134482014-08-04 21:25:23 +00005512 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Chris Lattner229907c2011-07-18 04:54:35 +00005513 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5514 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5515 Type *RetTy = FTy->getReturnType();
Chris Lattnerfb964e52010-04-05 06:19:28 +00005516 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Craig Topperc0196b12014-04-14 00:51:57 +00005517 MCSymbol *BeginLabel = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005518
5519 TargetLowering::ArgListTy Args;
5520 TargetLowering::ArgListEntry Entry;
5521 Args.reserve(CS.arg_size());
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005522
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005523 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriks9f344062009-11-11 19:59:24 +00005524 i != e; ++i) {
Rafael Espindolae53b7d12011-05-13 15:18:06 +00005525 const Value *V = *i;
5526
5527 // Skip empty types
5528 if (V->getType()->isEmptyTy())
5529 continue;
5530
5531 SDValue ArgNode = getValue(V);
5532 Entry.Node = ArgNode; Entry.Ty = V->getType();
Dan Gohman575fad32008-09-03 16:12:24 +00005533
Andrew Trick74f4c742013-10-31 17:18:24 +00005534 // Skip the first return-type Attribute to get to params.
5535 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
Dan Gohman575fad32008-09-03 16:12:24 +00005536 Args.push_back(Entry);
5537 }
5538
Chris Lattnerfb964e52010-04-05 06:19:28 +00005539 if (LandingPad) {
Dan Gohman575fad32008-09-03 16:12:24 +00005540 // Insert a label before the invoke call to mark the try range. This can be
5541 // used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005542 BeginLabel = MMI.getContext().CreateTempSymbol();
Jim Grosbach693e36a2009-08-11 00:09:57 +00005543
Jim Grosbach54c05302010-01-28 01:45:32 +00005544 // For SjLj, keep track of which landing pads go with which invokes
5545 // so as to maintain the ordering of pads in the LSDA.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005546 unsigned CallSiteIndex = MMI.getCurrentCallSite();
Jim Grosbach54c05302010-01-28 01:45:32 +00005547 if (CallSiteIndex) {
Chris Lattnerfb964e52010-04-05 06:19:28 +00005548 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
Bill Wendling267f3232011-10-05 22:24:35 +00005549 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
Bill Wendling3d11aa72011-10-04 22:00:35 +00005550
Jim Grosbach54c05302010-01-28 01:45:32 +00005551 // Now that the call site is handled, stop tracking it.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005552 MMI.setCurrentCallSite(0);
Jim Grosbach54c05302010-01-28 01:45:32 +00005553 }
5554
Dan Gohman575fad32008-09-03 16:12:24 +00005555 // Both PendingLoads and PendingExports must be flushed here;
5556 // this call might not return.
5557 (void)getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005558 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
Dan Gohman575fad32008-09-03 16:12:24 +00005559 }
5560
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005561 // Check if target-independent constraints permit a tail call here.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005562 // Target-dependent constraints are checked within TLI->LowerCallTo.
Juergen Ributzka480872b2014-07-16 00:01:22 +00005563 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005564 isTailCall = false;
5565
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00005566 TargetLowering::CallLoweringInfo CLI(DAG);
5567 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00005568 .setCallee(RetTy, FTy, Callee, std::move(Args), CS).setTailCall(isTailCall);
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00005569
Bill Wendlinga3cd3502013-06-19 21:36:55 +00005570 std::pair<SDValue,SDValue> Result = TLI->LowerCallTo(CLI);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005571 assert((isTailCall || Result.second.getNode()) &&
5572 "Non-null chain expected with non-tail call!");
5573 assert((Result.second.getNode() || !Result.first.getNode()) &&
5574 "Null value expected with tail call!");
Tim Northoverd82ed2e2014-06-18 11:52:44 +00005575 if (Result.first.getNode())
Dan Gohman575fad32008-09-03 16:12:24 +00005576 setValue(CS.getInstruction(), Result.first);
Bill Wendlinga4d7df72009-12-22 00:50:32 +00005577
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005578 if (!Result.second.getNode()) {
Andrew Trick74f4c742013-10-31 17:18:24 +00005579 // As a special case, a null chain means that a tail call has been emitted
5580 // and the DAG root is already updated.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005581 HasTailCall = true;
Tim Northoverdab4db52013-07-06 12:58:45 +00005582
5583 // Since there's no actual continuation from this block, nothing can be
5584 // relying on us setting vregs for them.
5585 PendingExports.clear();
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005586 } else {
5587 DAG.setRoot(Result.second);
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005588 }
Dan Gohman575fad32008-09-03 16:12:24 +00005589
Chris Lattnerfb964e52010-04-05 06:19:28 +00005590 if (LandingPad) {
Dan Gohman575fad32008-09-03 16:12:24 +00005591 // Insert a label at the end of the invoke call to mark the try range. This
5592 // can be used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005593 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005594 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
Dan Gohman575fad32008-09-03 16:12:24 +00005595
5596 // Inform MachineModuleInfo of range.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005597 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
Dan Gohman575fad32008-09-03 16:12:24 +00005598 }
5599}
5600
Chris Lattner1a32ede2009-12-24 00:37:38 +00005601/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5602/// value is equal or not-equal to zero.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005603static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00005604 for (const User *U : V->users()) {
5605 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005606 if (IC->isEquality())
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005607 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005608 if (C->isNullValue())
5609 continue;
5610 // Unknown instruction.
5611 return false;
5612 }
5613 return true;
5614}
5615
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005616static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
Chris Lattner229907c2011-07-18 04:54:35 +00005617 Type *LoadTy,
Chris Lattner1a32ede2009-12-24 00:37:38 +00005618 SelectionDAGBuilder &Builder) {
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005619
Chris Lattner1a32ede2009-12-24 00:37:38 +00005620 // Check to see if this load can be trivially constant folded, e.g. if the
5621 // input is from a string literal.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005622 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
Chris Lattner1a32ede2009-12-24 00:37:38 +00005623 // Cast pointer to the type we really want to load.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005624 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
Chris Lattner1a32ede2009-12-24 00:37:38 +00005625 PointerType::getUnqual(LoadTy));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005626
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005627 if (const Constant *LoadCst =
5628 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
Rafael Espindola5f57f462014-02-21 18:34:28 +00005629 Builder.DL))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005630 return Builder.getValue(LoadCst);
5631 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005632
Chris Lattner1a32ede2009-12-24 00:37:38 +00005633 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5634 // still constant memory, the input chain can be the entry node.
5635 SDValue Root;
5636 bool ConstantMemory = false;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005637
Chris Lattner1a32ede2009-12-24 00:37:38 +00005638 // Do not serialize (non-volatile) loads of constant memory with anything.
5639 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5640 Root = Builder.DAG.getEntryNode();
5641 ConstantMemory = true;
5642 } else {
5643 // Do not serialize non-volatile loads against each other.
5644 Root = Builder.DAG.getRoot();
5645 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005646
Chris Lattner1a32ede2009-12-24 00:37:38 +00005647 SDValue Ptr = Builder.getValue(PtrVal);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005648 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
Chris Lattner1ffcf522010-09-21 16:36:31 +00005649 Ptr, MachinePointerInfo(PtrVal),
David Greene39c6d012010-02-15 17:00:31 +00005650 false /*volatile*/,
Stephen Lincfe7f352013-07-08 00:37:03 +00005651 false /*nontemporal*/,
Pete Cooper82cd9e82011-11-08 18:42:53 +00005652 false /*isinvariant*/, 1 /* align=1 */);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005653
Chris Lattner1a32ede2009-12-24 00:37:38 +00005654 if (!ConstantMemory)
5655 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5656 return LoadVal;
5657}
5658
Richard Sandiforde3827752013-08-16 10:55:47 +00005659/// processIntegerCallValue - Record the value for an instruction that
5660/// produces an integer result, converting the type where necessary.
5661void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5662 SDValue Value,
5663 bool IsSigned) {
Eric Christopherd9134482014-08-04 21:25:23 +00005664 EVT VT = TM.getSubtargetImpl()->getTargetLowering()->getValueType(I.getType(),
5665 true);
Richard Sandiforde3827752013-08-16 10:55:47 +00005666 if (IsSigned)
5667 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5668 else
5669 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5670 setValue(&I, Value);
5671}
Chris Lattner1a32ede2009-12-24 00:37:38 +00005672
5673/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5674/// If so, return true and lower it, otherwise return false and it will be
5675/// lowered like a normal call.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005676bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
Chris Lattner1a32ede2009-12-24 00:37:38 +00005677 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
Gabor Greiff69acfe2010-06-30 12:55:46 +00005678 if (I.getNumArgOperands() != 3)
Chris Lattner1a32ede2009-12-24 00:37:38 +00005679 return false;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005680
Gabor Greifeba0be72010-06-25 09:38:13 +00005681 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
Duncan Sands19d0b472010-02-16 11:11:14 +00005682 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
Gabor Greifeba0be72010-06-25 09:38:13 +00005683 !I.getArgOperand(2)->getType()->isIntegerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00005684 !I.getType()->isIntegerTy())
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005685 return false;
5686
Richard Sandiforde3827752013-08-16 10:55:47 +00005687 const Value *Size = I.getArgOperand(2);
5688 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5689 if (CSize && CSize->getZExtValue() == 0) {
Eric Christopherd9134482014-08-04 21:25:23 +00005690 EVT CallVT = TM.getSubtargetImpl()->getTargetLowering()->getValueType(
5691 I.getType(), true);
Richard Sandiford564681c2013-08-12 10:28:10 +00005692 setValue(&I, DAG.getConstant(0, CallVT));
5693 return true;
5694 }
5695
Richard Sandiford564681c2013-08-12 10:28:10 +00005696 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5697 std::pair<SDValue, SDValue> Res =
5698 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
Richard Sandiforde3827752013-08-16 10:55:47 +00005699 getValue(LHS), getValue(RHS), getValue(Size),
5700 MachinePointerInfo(LHS),
5701 MachinePointerInfo(RHS));
Richard Sandiford564681c2013-08-12 10:28:10 +00005702 if (Res.first.getNode()) {
Richard Sandiforde3827752013-08-16 10:55:47 +00005703 processIntegerCallValue(I, Res.first, true);
5704 PendingLoads.push_back(Res.second);
Richard Sandiford564681c2013-08-12 10:28:10 +00005705 return true;
5706 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005707
Chris Lattner1a32ede2009-12-24 00:37:38 +00005708 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5709 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Richard Sandiforde3827752013-08-16 10:55:47 +00005710 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005711 bool ActuallyDoIt = true;
5712 MVT LoadVT;
Chris Lattner229907c2011-07-18 04:54:35 +00005713 Type *LoadTy;
Richard Sandiforde3827752013-08-16 10:55:47 +00005714 switch (CSize->getZExtValue()) {
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005715 default:
5716 LoadVT = MVT::Other;
Craig Topperc0196b12014-04-14 00:51:57 +00005717 LoadTy = nullptr;
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005718 ActuallyDoIt = false;
5719 break;
5720 case 2:
5721 LoadVT = MVT::i16;
Richard Sandiforde3827752013-08-16 10:55:47 +00005722 LoadTy = Type::getInt16Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005723 break;
5724 case 4:
5725 LoadVT = MVT::i32;
Richard Sandiforde3827752013-08-16 10:55:47 +00005726 LoadTy = Type::getInt32Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005727 break;
5728 case 8:
5729 LoadVT = MVT::i64;
Richard Sandiforde3827752013-08-16 10:55:47 +00005730 LoadTy = Type::getInt64Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005731 break;
5732 /*
5733 case 16:
5734 LoadVT = MVT::v4i32;
Richard Sandiforde3827752013-08-16 10:55:47 +00005735 LoadTy = Type::getInt32Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005736 LoadTy = VectorType::get(LoadTy, 4);
5737 break;
5738 */
5739 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005740
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005741 // This turns into unaligned loads. We only do this if the target natively
5742 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5743 // we'll only produce a small number of byte loads.
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005744
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005745 // Require that we can find a legal MVT, and only do this if the target
5746 // supports unaligned loads of that type. Expanding into byte loads would
5747 // bloat the code.
Eric Christopherd9134482014-08-04 21:25:23 +00005748 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Richard Sandiforde3827752013-08-16 10:55:47 +00005749 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
Matt Arsenault1b55dd92014-02-05 23:16:05 +00005750 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5751 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005752 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5753 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
Matt Arsenault6f2a5262014-07-27 17:46:40 +00005754 // TODO: Check alignment of src and dest ptrs.
Matt Arsenault1b55dd92014-02-05 23:16:05 +00005755 if (!TLI->isTypeLegal(LoadVT) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00005756 !TLI->allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5757 !TLI->allowsMisalignedMemoryAccesses(LoadVT, DstAS))
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005758 ActuallyDoIt = false;
5759 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005760
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005761 if (ActuallyDoIt) {
5762 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5763 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005764
Andrew Trickef9de2a2013-05-25 02:42:55 +00005765 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005766 ISD::SETNE);
Richard Sandiforde3827752013-08-16 10:55:47 +00005767 processIntegerCallValue(I, Res, false);
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005768 return true;
5769 }
Chris Lattner1a32ede2009-12-24 00:37:38 +00005770 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005771
5772
Chris Lattner1a32ede2009-12-24 00:37:38 +00005773 return false;
5774}
5775
Richard Sandiford6f6d5512013-08-20 09:38:48 +00005776/// visitMemChrCall -- See if we can lower a memchr call into an optimized
5777/// form. If so, return true and lower it, otherwise return false and it
5778/// will be lowered like a normal call.
5779bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5780 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5781 if (I.getNumArgOperands() != 3)
5782 return false;
5783
5784 const Value *Src = I.getArgOperand(0);
5785 const Value *Char = I.getArgOperand(1);
5786 const Value *Length = I.getArgOperand(2);
5787 if (!Src->getType()->isPointerTy() ||
5788 !Char->getType()->isIntegerTy() ||
5789 !Length->getType()->isIntegerTy() ||
5790 !I.getType()->isPointerTy())
5791 return false;
5792
5793 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5794 std::pair<SDValue, SDValue> Res =
5795 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5796 getValue(Src), getValue(Char), getValue(Length),
5797 MachinePointerInfo(Src));
5798 if (Res.first.getNode()) {
5799 setValue(&I, Res.first);
5800 PendingLoads.push_back(Res.second);
5801 return true;
5802 }
5803
5804 return false;
5805}
5806
Richard Sandifordbb83a502013-08-16 11:29:37 +00005807/// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5808/// optimized form. If so, return true and lower it, otherwise return false
5809/// and it will be lowered like a normal call.
5810bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5811 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5812 if (I.getNumArgOperands() != 2)
5813 return false;
5814
5815 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5816 if (!Arg0->getType()->isPointerTy() ||
5817 !Arg1->getType()->isPointerTy() ||
5818 !I.getType()->isPointerTy())
5819 return false;
5820
5821 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5822 std::pair<SDValue, SDValue> Res =
5823 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5824 getValue(Arg0), getValue(Arg1),
5825 MachinePointerInfo(Arg0),
5826 MachinePointerInfo(Arg1), isStpcpy);
5827 if (Res.first.getNode()) {
5828 setValue(&I, Res.first);
5829 DAG.setRoot(Res.second);
5830 return true;
5831 }
5832
5833 return false;
5834}
5835
Richard Sandifordca232712013-08-16 11:21:54 +00005836/// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5837/// If so, return true and lower it, otherwise return false and it will be
5838/// lowered like a normal call.
5839bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5840 // Verify that the prototype makes sense. int strcmp(void*,void*)
5841 if (I.getNumArgOperands() != 2)
5842 return false;
5843
5844 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5845 if (!Arg0->getType()->isPointerTy() ||
5846 !Arg1->getType()->isPointerTy() ||
5847 !I.getType()->isIntegerTy())
5848 return false;
5849
5850 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5851 std::pair<SDValue, SDValue> Res =
5852 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5853 getValue(Arg0), getValue(Arg1),
5854 MachinePointerInfo(Arg0),
5855 MachinePointerInfo(Arg1));
5856 if (Res.first.getNode()) {
5857 processIntegerCallValue(I, Res.first, true);
5858 PendingLoads.push_back(Res.second);
5859 return true;
5860 }
5861
5862 return false;
5863}
5864
Richard Sandiford0dec06a2013-08-16 11:41:43 +00005865/// visitStrLenCall -- See if we can lower a strlen call into an optimized
5866/// form. If so, return true and lower it, otherwise return false and it
5867/// will be lowered like a normal call.
5868bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5869 // Verify that the prototype makes sense. size_t strlen(char *)
5870 if (I.getNumArgOperands() != 1)
5871 return false;
5872
5873 const Value *Arg0 = I.getArgOperand(0);
5874 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5875 return false;
5876
5877 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5878 std::pair<SDValue, SDValue> Res =
5879 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5880 getValue(Arg0), MachinePointerInfo(Arg0));
5881 if (Res.first.getNode()) {
5882 processIntegerCallValue(I, Res.first, false);
5883 PendingLoads.push_back(Res.second);
5884 return true;
5885 }
5886
5887 return false;
5888}
5889
5890/// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5891/// form. If so, return true and lower it, otherwise return false and it
5892/// will be lowered like a normal call.
5893bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5894 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5895 if (I.getNumArgOperands() != 2)
5896 return false;
5897
5898 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5899 if (!Arg0->getType()->isPointerTy() ||
5900 !Arg1->getType()->isIntegerTy() ||
5901 !I.getType()->isIntegerTy())
5902 return false;
5903
5904 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5905 std::pair<SDValue, SDValue> Res =
5906 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5907 getValue(Arg0), getValue(Arg1),
5908 MachinePointerInfo(Arg0));
5909 if (Res.first.getNode()) {
5910 processIntegerCallValue(I, Res.first, false);
5911 PendingLoads.push_back(Res.second);
5912 return true;
5913 }
5914
5915 return false;
5916}
5917
Bob Wilson874886c2012-08-03 23:29:17 +00005918/// visitUnaryFloatCall - If a call instruction is a unary floating-point
5919/// operation (as expected), translate it to an SDNode with the specified opcode
5920/// and return true.
5921bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5922 unsigned Opcode) {
5923 // Sanity check that it really is a unary floating-point call.
5924 if (I.getNumArgOperands() != 1 ||
5925 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5926 I.getType() != I.getArgOperand(0)->getType() ||
5927 !I.onlyReadsMemory())
5928 return false;
5929
5930 SDValue Tmp = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005931 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
Bob Wilson874886c2012-08-03 23:29:17 +00005932 return true;
5933}
Chris Lattner1a32ede2009-12-24 00:37:38 +00005934
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005935void SelectionDAGBuilder::visitCall(const CallInst &I) {
Chris Lattner2c0315a2010-07-05 05:36:21 +00005936 // Handle inline assembly differently.
5937 if (isa<InlineAsm>(I.getCalledValue())) {
5938 visitInlineAsm(&I);
5939 return;
5940 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00005941
Michael J. Spencer0e36e032010-10-21 20:49:23 +00005942 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Michael J. Spencer8b98bf22012-02-22 19:06:13 +00005943 ComputeUsesVAFloatArgument(I, &MMI);
Michael J. Spencer0e36e032010-10-21 20:49:23 +00005944
Craig Topperc0196b12014-04-14 00:51:57 +00005945 const char *RenameFn = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005946 if (Function *F = I.getCalledFunction()) {
5947 if (F->isDeclaration()) {
Chris Lattner2c0315a2010-07-05 05:36:21 +00005948 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
Dale Johannesenb842d522009-02-05 01:49:45 +00005949 if (unsigned IID = II->getIntrinsicID(F)) {
5950 RenameFn = visitIntrinsicCall(I, IID);
5951 if (!RenameFn)
5952 return;
5953 }
5954 }
Dan Gohman575fad32008-09-03 16:12:24 +00005955 if (unsigned IID = F->getIntrinsicID()) {
5956 RenameFn = visitIntrinsicCall(I, IID);
5957 if (!RenameFn)
5958 return;
5959 }
5960 }
5961
5962 // Check for well-known libc/libm calls. If the function is internal, it
5963 // can't be a library call.
Bob Wilson871701c2012-08-03 21:26:24 +00005964 LibFunc::Func Func;
5965 if (!F->hasLocalLinkage() && F->hasName() &&
5966 LibInfo->getLibFunc(F->getName(), Func) &&
5967 LibInfo->hasOptimizedCodeGen(Func)) {
5968 switch (Func) {
5969 default: break;
5970 case LibFunc::copysign:
5971 case LibFunc::copysignf:
5972 case LibFunc::copysignl:
Gabor Greiff69acfe2010-06-30 12:55:46 +00005973 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
Gabor Greifeba0be72010-06-25 09:38:13 +00005974 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5975 I.getType() == I.getArgOperand(0)->getType() &&
Bob Wilson874886c2012-08-03 23:29:17 +00005976 I.getType() == I.getArgOperand(1)->getType() &&
5977 I.onlyReadsMemory()) {
Gabor Greifeba0be72010-06-25 09:38:13 +00005978 SDValue LHS = getValue(I.getArgOperand(0));
5979 SDValue RHS = getValue(I.getArgOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005980 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
Bill Wendling0602f392009-12-23 01:28:19 +00005981 LHS.getValueType(), LHS, RHS));
Dan Gohman575fad32008-09-03 16:12:24 +00005982 return;
5983 }
Bob Wilson871701c2012-08-03 21:26:24 +00005984 break;
5985 case LibFunc::fabs:
5986 case LibFunc::fabsf:
5987 case LibFunc::fabsl:
Bob Wilson874886c2012-08-03 23:29:17 +00005988 if (visitUnaryFloatCall(I, ISD::FABS))
Dan Gohman575fad32008-09-03 16:12:24 +00005989 return;
Bob Wilson871701c2012-08-03 21:26:24 +00005990 break;
5991 case LibFunc::sin:
5992 case LibFunc::sinf:
5993 case LibFunc::sinl:
Bob Wilson874886c2012-08-03 23:29:17 +00005994 if (visitUnaryFloatCall(I, ISD::FSIN))
Dan Gohman575fad32008-09-03 16:12:24 +00005995 return;
Bob Wilson871701c2012-08-03 21:26:24 +00005996 break;
5997 case LibFunc::cos:
5998 case LibFunc::cosf:
5999 case LibFunc::cosl:
Bob Wilson874886c2012-08-03 23:29:17 +00006000 if (visitUnaryFloatCall(I, ISD::FCOS))
Dan Gohman575fad32008-09-03 16:12:24 +00006001 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006002 break;
6003 case LibFunc::sqrt:
6004 case LibFunc::sqrtf:
6005 case LibFunc::sqrtl:
Preston Gurd048f99d2013-05-27 15:44:35 +00006006 case LibFunc::sqrt_finite:
6007 case LibFunc::sqrtf_finite:
6008 case LibFunc::sqrtl_finite:
Bob Wilson874886c2012-08-03 23:29:17 +00006009 if (visitUnaryFloatCall(I, ISD::FSQRT))
Dale Johannesenc7213422009-09-25 17:23:22 +00006010 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006011 break;
6012 case LibFunc::floor:
6013 case LibFunc::floorf:
6014 case LibFunc::floorl:
Bob Wilson874886c2012-08-03 23:29:17 +00006015 if (visitUnaryFloatCall(I, ISD::FFLOOR))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006016 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006017 break;
6018 case LibFunc::nearbyint:
6019 case LibFunc::nearbyintf:
6020 case LibFunc::nearbyintl:
Bob Wilson874886c2012-08-03 23:29:17 +00006021 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006022 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006023 break;
6024 case LibFunc::ceil:
6025 case LibFunc::ceilf:
6026 case LibFunc::ceill:
Bob Wilson874886c2012-08-03 23:29:17 +00006027 if (visitUnaryFloatCall(I, ISD::FCEIL))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006028 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006029 break;
6030 case LibFunc::rint:
6031 case LibFunc::rintf:
6032 case LibFunc::rintl:
Bob Wilson874886c2012-08-03 23:29:17 +00006033 if (visitUnaryFloatCall(I, ISD::FRINT))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006034 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006035 break;
Hal Finkel171817e2013-08-07 22:49:12 +00006036 case LibFunc::round:
6037 case LibFunc::roundf:
6038 case LibFunc::roundl:
6039 if (visitUnaryFloatCall(I, ISD::FROUND))
6040 return;
6041 break;
Bob Wilson871701c2012-08-03 21:26:24 +00006042 case LibFunc::trunc:
6043 case LibFunc::truncf:
6044 case LibFunc::truncl:
Bob Wilson874886c2012-08-03 23:29:17 +00006045 if (visitUnaryFloatCall(I, ISD::FTRUNC))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006046 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006047 break;
6048 case LibFunc::log2:
6049 case LibFunc::log2f:
6050 case LibFunc::log2l:
Bob Wilson874886c2012-08-03 23:29:17 +00006051 if (visitUnaryFloatCall(I, ISD::FLOG2))
Owen Andersone7f329f2011-12-15 00:54:12 +00006052 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006053 break;
6054 case LibFunc::exp2:
6055 case LibFunc::exp2f:
6056 case LibFunc::exp2l:
Bob Wilson874886c2012-08-03 23:29:17 +00006057 if (visitUnaryFloatCall(I, ISD::FEXP2))
Owen Andersone7f329f2011-12-15 00:54:12 +00006058 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006059 break;
6060 case LibFunc::memcmp:
Chris Lattner1a32ede2009-12-24 00:37:38 +00006061 if (visitMemCmpCall(I))
6062 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006063 break;
Richard Sandiford6f6d5512013-08-20 09:38:48 +00006064 case LibFunc::memchr:
6065 if (visitMemChrCall(I))
6066 return;
6067 break;
Richard Sandifordbb83a502013-08-16 11:29:37 +00006068 case LibFunc::strcpy:
6069 if (visitStrCpyCall(I, false))
6070 return;
6071 break;
6072 case LibFunc::stpcpy:
6073 if (visitStrCpyCall(I, true))
6074 return;
6075 break;
Richard Sandifordca232712013-08-16 11:21:54 +00006076 case LibFunc::strcmp:
6077 if (visitStrCmpCall(I))
6078 return;
6079 break;
Richard Sandiford0dec06a2013-08-16 11:41:43 +00006080 case LibFunc::strlen:
6081 if (visitStrLenCall(I))
6082 return;
6083 break;
6084 case LibFunc::strnlen:
6085 if (visitStrNLenCall(I))
6086 return;
6087 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006088 }
6089 }
Dan Gohman575fad32008-09-03 16:12:24 +00006090 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006091
Dan Gohman575fad32008-09-03 16:12:24 +00006092 SDValue Callee;
6093 if (!RenameFn)
Gabor Greifeba0be72010-06-25 09:38:13 +00006094 Callee = getValue(I.getCalledValue());
Dan Gohman575fad32008-09-03 16:12:24 +00006095 else
Eric Christopherd9134482014-08-04 21:25:23 +00006096 Callee = DAG.getExternalSymbol(
6097 RenameFn, TM.getSubtargetImpl()->getTargetLowering()->getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00006098
Bill Wendling0602f392009-12-23 01:28:19 +00006099 // Check if we can potentially perform a tail call. More detailed checking is
6100 // be done within LowerCallTo, after more information about the call is known.
Evan Chengc35b5a12010-01-26 23:13:04 +00006101 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohman575fad32008-09-03 16:12:24 +00006102}
6103
Benjamin Kramer355ce072011-03-26 16:35:10 +00006104namespace {
Dan Gohman4db93c92010-05-29 17:53:24 +00006105
Dan Gohman575fad32008-09-03 16:12:24 +00006106/// AsmOperandInfo - This contains information for each constraint that we are
6107/// lowering.
Benjamin Kramer355ce072011-03-26 16:35:10 +00006108class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
Cedric Venetd1e179d2009-02-14 16:06:42 +00006109public:
Dan Gohman575fad32008-09-03 16:12:24 +00006110 /// CallOperand - If this is the result output operand or a clobber
6111 /// this is null, otherwise it is the incoming operand to the CallInst.
6112 /// This gets modified as the asm is processed.
6113 SDValue CallOperand;
6114
6115 /// AssignedRegs - If this is a register or register class operand, this
6116 /// contains the set of register corresponding to the operand.
6117 RegsForValue AssignedRegs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006118
John Thompson1094c802010-09-13 18:15:37 +00006119 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
Craig Topperc0196b12014-04-14 00:51:57 +00006120 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
Dan Gohman575fad32008-09-03 16:12:24 +00006121 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006122
Owen Anderson53aa7a92009-08-10 22:56:29 +00006123 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner3b1833c2008-10-17 17:05:25 +00006124 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson9f944592009-08-11 20:47:22 +00006125 /// MVT::Other.
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00006126 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson55f1c092009-08-13 21:58:54 +00006127 const TargetLowering &TLI,
Rafael Espindola5f57f462014-02-21 18:34:28 +00006128 const DataLayout *DL) const {
Craig Topperc0196b12014-04-14 00:51:57 +00006129 if (!CallOperandVal) return MVT::Other;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006130
Chris Lattner3b1833c2008-10-17 17:05:25 +00006131 if (isa<BasicBlock>(CallOperandVal))
6132 return TLI.getPointerTy();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006133
Chris Lattner229907c2011-07-18 04:54:35 +00006134 llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006135
Eric Christopher44804282011-05-09 20:04:43 +00006136 // FIXME: code duplicated from TargetLowering::ParseConstraints().
Chris Lattner3b1833c2008-10-17 17:05:25 +00006137 // If this is an indirect operand, the operand is a pointer to the
6138 // accessed type.
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006139 if (isIndirect) {
Chris Lattner229907c2011-07-18 04:54:35 +00006140 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006141 if (!PtrTy)
Chris Lattner2104b8d2010-04-07 22:58:41 +00006142 report_fatal_error("Indirect operand for inline asm not a pointer!");
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006143 OpTy = PtrTy->getElementType();
6144 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006145
Eric Christopher44804282011-05-09 20:04:43 +00006146 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattner229907c2011-07-18 04:54:35 +00006147 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christopher44804282011-05-09 20:04:43 +00006148 if (STy->getNumElements() == 1)
6149 OpTy = STy->getElementType(0);
6150
Chris Lattner3b1833c2008-10-17 17:05:25 +00006151 // If OpTy is not a single value, it may be a struct/union that we
6152 // can tile with integers.
6153 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Rafael Espindola5f57f462014-02-21 18:34:28 +00006154 unsigned BitSize = DL->getTypeSizeInBits(OpTy);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006155 switch (BitSize) {
6156 default: break;
6157 case 1:
6158 case 8:
6159 case 16:
6160 case 32:
6161 case 64:
Chris Lattneraadf7412008-10-17 19:59:51 +00006162 case 128:
Owen Anderson55f1c092009-08-13 21:58:54 +00006163 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006164 break;
6165 }
6166 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006167
Chris Lattner3b1833c2008-10-17 17:05:25 +00006168 return TLI.getValueType(OpTy, true);
6169 }
Dan Gohman575fad32008-09-03 16:12:24 +00006170};
Dan Gohman4db93c92010-05-29 17:53:24 +00006171
John Thompsone8360b72010-10-29 17:29:13 +00006172typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6173
Benjamin Kramer355ce072011-03-26 16:35:10 +00006174} // end anonymous namespace
Dan Gohman575fad32008-09-03 16:12:24 +00006175
Dan Gohman575fad32008-09-03 16:12:24 +00006176/// GetRegistersForValue - Assign registers (virtual or physical) for the
6177/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson1c00b692009-12-17 05:07:36 +00006178/// register allocator to handle the assignment process. However, if the asm
6179/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohman575fad32008-09-03 16:12:24 +00006180/// allocation. This produces generally horrible, but correct, code.
6181///
6182/// OpInfo describes the operand.
Dan Gohman575fad32008-09-03 16:12:24 +00006183///
Benjamin Kramer355ce072011-03-26 16:35:10 +00006184static void GetRegistersForValue(SelectionDAG &DAG,
6185 const TargetLowering &TLI,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006186 SDLoc DL,
Benjamin Kramer6fe3e3d2012-02-24 14:01:17 +00006187 SDISelAsmOperandInfo &OpInfo) {
Benjamin Kramer355ce072011-03-26 16:35:10 +00006188 LLVMContext &Context = *DAG.getContext();
Owen Anderson117c9e82009-08-12 00:36:31 +00006189
Dan Gohman575fad32008-09-03 16:12:24 +00006190 MachineFunction &MF = DAG.getMachineFunction();
6191 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006192
Dan Gohman575fad32008-09-03 16:12:24 +00006193 // If this is a constraint for a single physreg, or a constraint for a
6194 // register class, find it.
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006195 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohman575fad32008-09-03 16:12:24 +00006196 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6197 OpInfo.ConstraintVT);
6198
6199 unsigned NumRegs = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00006200 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner4396e0d2008-10-21 00:45:36 +00006201 // If this is a FP input in an integer register (or visa versa) insert a bit
6202 // cast of the input value. More generally, handle any case where the input
6203 // value disagrees with the register class we plan to stick this in.
6204 if (OpInfo.Type == InlineAsm::isInput &&
6205 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006206 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner4396e0d2008-10-21 00:45:36 +00006207 // types are identical size, use a bitcast to convert (e.g. two differing
6208 // vector types).
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006209 MVT RegVT = *PhysReg.second->vt_begin();
Kevin Qin275ce912014-03-21 02:14:50 +00006210 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
Benjamin Kramer355ce072011-03-26 16:35:10 +00006211 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesened255b32009-01-30 01:34:22 +00006212 RegVT, OpInfo.CallOperand);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006213 OpInfo.ConstraintVT = RegVT;
6214 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6215 // If the input is a FP value and we want it in FP registers, do a
6216 // bitcast to the corresponding integer type. This turns an f64 value
6217 // into i64, which can be passed with two i32 values on a 32-bit
6218 // machine.
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006219 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Benjamin Kramer355ce072011-03-26 16:35:10 +00006220 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesened255b32009-01-30 01:34:22 +00006221 RegVT, OpInfo.CallOperand);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006222 OpInfo.ConstraintVT = RegVT;
6223 }
6224 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006225
Owen Anderson117c9e82009-08-12 00:36:31 +00006226 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006227 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006228
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006229 MVT RegVT;
Owen Anderson53aa7a92009-08-10 22:56:29 +00006230 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohman575fad32008-09-03 16:12:24 +00006231
6232 // If this is a constraint for a specific physical register, like {r17},
6233 // assign it now.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006234 if (unsigned AssignedReg = PhysReg.first) {
6235 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson9f944592009-08-11 20:47:22 +00006236 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnerc35847e2009-03-24 15:27:37 +00006237 ValueVT = *RC->vt_begin();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006238
Dan Gohman575fad32008-09-03 16:12:24 +00006239 // Get the actual register value type. This is important, because the user
6240 // may have asked for (e.g.) the AX register in i32 type. We need to
6241 // remember that AX is actually i16 to get the right extension.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006242 RegVT = *RC->vt_begin();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006243
Dan Gohman575fad32008-09-03 16:12:24 +00006244 // This is a explicit reference to a physical register.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006245 Regs.push_back(AssignedReg);
Dan Gohman575fad32008-09-03 16:12:24 +00006246
6247 // If this is an expanded reference, add the rest of the regs to Regs.
6248 if (NumRegs != 1) {
Chris Lattnerc35847e2009-03-24 15:27:37 +00006249 TargetRegisterClass::iterator I = RC->begin();
6250 for (; *I != AssignedReg; ++I)
6251 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006252
Dan Gohman575fad32008-09-03 16:12:24 +00006253 // Already added the first reg.
6254 --NumRegs; ++I;
6255 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnerc35847e2009-03-24 15:27:37 +00006256 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohman575fad32008-09-03 16:12:24 +00006257 Regs.push_back(*I);
6258 }
6259 }
Bill Wendlingac087582009-12-22 01:25:10 +00006260
Dan Gohmand16aa542010-05-29 17:03:36 +00006261 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Dan Gohman575fad32008-09-03 16:12:24 +00006262 return;
6263 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006264
Dan Gohman575fad32008-09-03 16:12:24 +00006265 // Otherwise, if this was a reference to an LLVM register class, create vregs
6266 // for this reference.
Chris Lattner42eceb32009-03-24 15:25:07 +00006267 if (const TargetRegisterClass *RC = PhysReg.second) {
6268 RegVT = *RC->vt_begin();
Owen Anderson9f944592009-08-11 20:47:22 +00006269 if (OpInfo.ConstraintVT == MVT::Other)
Evan Cheng968c3b02009-03-23 08:01:15 +00006270 ValueVT = RegVT;
Dan Gohman575fad32008-09-03 16:12:24 +00006271
Evan Cheng968c3b02009-03-23 08:01:15 +00006272 // Create the appropriate number of virtual registers.
6273 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6274 for (; NumRegs; --NumRegs)
Chris Lattner42eceb32009-03-24 15:25:07 +00006275 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006276
Dan Gohmand16aa542010-05-29 17:03:36 +00006277 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Evan Cheng968c3b02009-03-23 08:01:15 +00006278 return;
Dan Gohman575fad32008-09-03 16:12:24 +00006279 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00006280
Dan Gohman575fad32008-09-03 16:12:24 +00006281 // Otherwise, we couldn't allocate enough registers for this.
6282}
6283
Dan Gohman575fad32008-09-03 16:12:24 +00006284/// visitInlineAsm - Handle a call to an InlineAsm object.
6285///
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006286void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6287 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Dan Gohman575fad32008-09-03 16:12:24 +00006288
6289 /// ConstraintOperands - Information about all of the constraints.
John Thompsone8360b72010-10-29 17:29:13 +00006290 SDISelAsmOperandInfoVector ConstraintOperands;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006291
Eric Christopherd9134482014-08-04 21:25:23 +00006292 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Evan Chengd26fc5e2011-05-06 20:52:23 +00006293 TargetLowering::AsmOperandInfoVector
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006294 TargetConstraints = TLI->ParseConstraints(CS);
Evan Chengd26fc5e2011-05-06 20:52:23 +00006295
John Thompson1094c802010-09-13 18:15:37 +00006296 bool hasMemory = false;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006297
Dan Gohman575fad32008-09-03 16:12:24 +00006298 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6299 unsigned ResNo = 0; // ResNo - The result number of the next output.
John Thompson1094c802010-09-13 18:15:37 +00006300 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6301 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
Dan Gohman575fad32008-09-03 16:12:24 +00006302 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006303
Patrik Hagglundf9934612012-12-19 15:19:11 +00006304 MVT OpVT = MVT::Other;
Dan Gohman575fad32008-09-03 16:12:24 +00006305
6306 // Compute the value type for each operand.
6307 switch (OpInfo.Type) {
6308 case InlineAsm::isOutput:
6309 // Indirect outputs just consume an argument.
6310 if (OpInfo.isIndirect) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006311 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohman575fad32008-09-03 16:12:24 +00006312 break;
6313 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006314
Dan Gohman575fad32008-09-03 16:12:24 +00006315 // The return value of the call is this value. As such, there is no
6316 // corresponding argument.
Nick Lewyckyf40df1d2011-09-30 22:19:53 +00006317 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Chris Lattner229907c2011-07-18 04:54:35 +00006318 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006319 OpVT = TLI->getSimpleValueType(STy->getElementType(ResNo));
Dan Gohman575fad32008-09-03 16:12:24 +00006320 } else {
6321 assert(ResNo == 0 && "Asm only has one result!");
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006322 OpVT = TLI->getSimpleValueType(CS.getType());
Dan Gohman575fad32008-09-03 16:12:24 +00006323 }
6324 ++ResNo;
6325 break;
6326 case InlineAsm::isInput:
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006327 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohman575fad32008-09-03 16:12:24 +00006328 break;
6329 case InlineAsm::isClobber:
6330 // Nothing to do.
6331 break;
6332 }
6333
6334 // If this is an input or an indirect output, process the call argument.
6335 // BasicBlocks are labels, currently appearing only in asm's.
6336 if (OpInfo.CallOperandVal) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006337 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohman575fad32008-09-03 16:12:24 +00006338 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006339 } else {
Dan Gohman575fad32008-09-03 16:12:24 +00006340 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohman575fad32008-09-03 16:12:24 +00006341 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006342
Rafael Espindola5f57f462014-02-21 18:34:28 +00006343 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), *TLI, DL).
Patrik Hagglundf9934612012-12-19 15:19:11 +00006344 getSimpleVT();
Dan Gohman575fad32008-09-03 16:12:24 +00006345 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006346
Dan Gohman575fad32008-09-03 16:12:24 +00006347 OpInfo.ConstraintVT = OpVT;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006348
John Thompson1094c802010-09-13 18:15:37 +00006349 // Indirect operand accesses access memory.
6350 if (OpInfo.isIndirect)
6351 hasMemory = true;
6352 else {
6353 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
Evan Chengd26fc5e2011-05-06 20:52:23 +00006354 TargetLowering::ConstraintType
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006355 CType = TLI->getConstraintType(OpInfo.Codes[j]);
John Thompson1094c802010-09-13 18:15:37 +00006356 if (CType == TargetLowering::C_Memory) {
6357 hasMemory = true;
6358 break;
6359 }
6360 }
6361 }
Chris Lattner160e8ab2008-10-18 18:49:30 +00006362 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006363
John Thompson1094c802010-09-13 18:15:37 +00006364 SDValue Chain, Flag;
6365
6366 // We won't need to flush pending loads if this asm doesn't touch
6367 // memory and is nonvolatile.
6368 if (hasMemory || IA->hasSideEffects())
6369 Chain = getRoot();
6370 else
6371 Chain = DAG.getRoot();
6372
Chris Lattner160e8ab2008-10-18 18:49:30 +00006373 // Second pass over the constraints: compute which constraint option to use
6374 // and assign registers to constraints that want a specific physreg.
John Thompson1094c802010-09-13 18:15:37 +00006375 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Chris Lattner160e8ab2008-10-18 18:49:30 +00006376 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006377
John Thompson8118ef82010-09-24 22:24:05 +00006378 // If this is an output operand with a matching input operand, look up the
6379 // matching input. If their types mismatch, e.g. one is an integer, the
6380 // other is floating point, or their sizes are different, flag it as an
6381 // error.
6382 if (OpInfo.hasMatchingInput()) {
6383 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006384
John Thompson8118ef82010-09-24 22:24:05 +00006385 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Bill Wendlingd1634052012-07-19 00:04:14 +00006386 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006387 TLI->getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6388 OpInfo.ConstraintVT);
Bill Wendlingd1634052012-07-19 00:04:14 +00006389 std::pair<unsigned, const TargetRegisterClass*> InputRC =
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006390 TLI->getRegForInlineAsmConstraint(Input.ConstraintCode,
6391 Input.ConstraintVT);
John Thompson8118ef82010-09-24 22:24:05 +00006392 if ((OpInfo.ConstraintVT.isInteger() !=
6393 Input.ConstraintVT.isInteger()) ||
Eric Christopher92464be2011-07-14 20:13:52 +00006394 (MatchRC.second != InputRC.second)) {
John Thompson8118ef82010-09-24 22:24:05 +00006395 report_fatal_error("Unsupported asm: input constraint"
6396 " with a matching output constraint of"
6397 " incompatible type!");
6398 }
6399 Input.ConstraintVT = OpInfo.ConstraintVT;
6400 }
6401 }
6402
Dan Gohman575fad32008-09-03 16:12:24 +00006403 // Compute the constraint code and ConstraintType to use.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006404 TLI->ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Dan Gohman575fad32008-09-03 16:12:24 +00006405
Eric Christopher0cb6fd92013-01-11 18:12:39 +00006406 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6407 OpInfo.Type == InlineAsm::isClobber)
6408 continue;
6409
Dan Gohman575fad32008-09-03 16:12:24 +00006410 // If this is a memory input, and if the operand is not indirect, do what we
6411 // need to to provide an address for the memory input.
6412 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6413 !OpInfo.isIndirect) {
Evan Chengd26fc5e2011-05-06 20:52:23 +00006414 assert((OpInfo.isMultipleAlternative ||
6415 (OpInfo.Type == InlineAsm::isInput)) &&
Dan Gohman575fad32008-09-03 16:12:24 +00006416 "Can only indirectify direct input operands!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006417
Dan Gohman575fad32008-09-03 16:12:24 +00006418 // Memory operands really want the address of the value. If we don't have
6419 // an indirect input, put it in the constpool if we can, otherwise spill
6420 // it to a stack slot.
Eric Christopherfbff0e42011-06-03 17:21:23 +00006421 // TODO: This isn't quite right. We need to handle these according to
6422 // the addressing mode that the constraint wants. Also, this may take
6423 // an additional register for the computation and we don't want that
6424 // either.
Eric Christopher0713a9d2011-06-08 23:55:35 +00006425
Dan Gohman575fad32008-09-03 16:12:24 +00006426 // If the operand is a float, integer, or vector constant, spill to a
6427 // constant pool entry to get its address.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006428 const Value *OpVal = OpInfo.CallOperandVal;
Dan Gohman575fad32008-09-03 16:12:24 +00006429 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
Chris Lattner0256be92012-01-27 03:08:05 +00006430 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
Dan Gohman575fad32008-09-03 16:12:24 +00006431 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006432 TLI->getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00006433 } else {
6434 // Otherwise, create a stack slot and emit a store to it before the
6435 // asm.
Chris Lattner229907c2011-07-18 04:54:35 +00006436 Type *Ty = OpVal->getType();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006437 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
6438 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(Ty);
Dan Gohman575fad32008-09-03 16:12:24 +00006439 MachineFunction &MF = DAG.getMachineFunction();
David Greene1fbe0542009-11-12 20:49:22 +00006440 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006441 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI->getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006442 Chain = DAG.getStore(Chain, getCurSDLoc(),
Chris Lattner1ffcf522010-09-21 16:36:31 +00006443 OpInfo.CallOperand, StackSlot,
6444 MachinePointerInfo::getFixedStack(SSFI),
David Greene39c6d012010-02-15 17:00:31 +00006445 false, false, 0);
Dan Gohman575fad32008-09-03 16:12:24 +00006446 OpInfo.CallOperand = StackSlot;
6447 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006448
Dan Gohman575fad32008-09-03 16:12:24 +00006449 // There is no longer a Value* corresponding to this operand.
Craig Topperc0196b12014-04-14 00:51:57 +00006450 OpInfo.CallOperandVal = nullptr;
Bill Wendlingac087582009-12-22 01:25:10 +00006451
Dan Gohman575fad32008-09-03 16:12:24 +00006452 // It is now an indirect operand.
6453 OpInfo.isIndirect = true;
6454 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006455
Dan Gohman575fad32008-09-03 16:12:24 +00006456 // If this constraint is for a specific register, allocate it before
6457 // anything else.
6458 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006459 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
Dan Gohman575fad32008-09-03 16:12:24 +00006460 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006461
Dan Gohman575fad32008-09-03 16:12:24 +00006462 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattneref890172008-10-17 16:21:11 +00006463 // to register class operands.
Dan Gohman575fad32008-09-03 16:12:24 +00006464 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6465 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006466
Dan Gohman575fad32008-09-03 16:12:24 +00006467 // C_Register operands have already been allocated, Other/Memory don't need
6468 // to be.
6469 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006470 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006471 }
6472
Dan Gohman575fad32008-09-03 16:12:24 +00006473 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6474 std::vector<SDValue> AsmNodeOperands;
6475 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6476 AsmNodeOperands.push_back(
Dan Gohmanfeeced42010-01-04 21:00:54 +00006477 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006478 TLI->getPointerTy()));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006479
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006480 // If we have a !srcloc metadata node associated with it, we want to attach
6481 // this to the ultimately generated inline asm machineinstr. To do this, we
6482 // pass in the third operand as this (potentially null) inline asm MDNode.
6483 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6484 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006485
Chad Rosier9e1274f2012-10-30 19:11:54 +00006486 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6487 // bits as operand 3.
Evan Cheng6eb516d2011-01-07 23:50:32 +00006488 unsigned ExtraInfo = 0;
6489 if (IA->hasSideEffects())
6490 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6491 if (IA->isAlignStack())
6492 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
Chad Rosiercbd2a192012-09-05 22:17:43 +00006493 // Set the asm dialect.
Chad Rosiere53314f2012-09-05 22:40:13 +00006494 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
Chad Rosier9e1274f2012-10-30 19:11:54 +00006495
6496 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6497 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6498 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6499
6500 // Compute the constraint code and ConstraintType to use.
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006501 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chad Rosier9e1274f2012-10-30 19:11:54 +00006502
Chad Rosier86f60502012-10-30 20:01:12 +00006503 // Ideally, we would only check against memory constraints. However, the
6504 // meaning of an other constraint can be target-specific and we can't easily
6505 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6506 // for other constriants as well.
Chad Rosier9e1274f2012-10-30 19:11:54 +00006507 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6508 OpInfo.ConstraintType == TargetLowering::C_Other) {
6509 if (OpInfo.Type == InlineAsm::isInput)
6510 ExtraInfo |= InlineAsm::Extra_MayLoad;
6511 else if (OpInfo.Type == InlineAsm::isOutput)
6512 ExtraInfo |= InlineAsm::Extra_MayStore;
Eric Christopher0cb6fd92013-01-11 18:12:39 +00006513 else if (OpInfo.Type == InlineAsm::isClobber)
6514 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
Chad Rosier9e1274f2012-10-30 19:11:54 +00006515 }
6516 }
6517
Evan Cheng6eb516d2011-01-07 23:50:32 +00006518 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006519 TLI->getPointerTy()));
Dale Johannesen4d887f7c2010-07-02 20:16:09 +00006520
Dan Gohman575fad32008-09-03 16:12:24 +00006521 // Loop over all of the inputs, copying the operand values into the
6522 // appropriate registers and processing the output regs.
6523 RegsForValue RetValRegs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006524
Dan Gohman575fad32008-09-03 16:12:24 +00006525 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6526 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006527
Dan Gohman575fad32008-09-03 16:12:24 +00006528 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6529 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6530
6531 switch (OpInfo.Type) {
6532 case InlineAsm::isOutput: {
6533 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6534 OpInfo.ConstraintType != TargetLowering::C_Register) {
6535 // Memory output, or 'other' output (e.g. 'X' constraint).
6536 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6537
6538 // Add information to the INLINEASM node to know about this output.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006539 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6540 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006541 TLI->getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006542 AsmNodeOperands.push_back(OpInfo.CallOperand);
6543 break;
6544 }
6545
6546 // Otherwise, this is a register or register class output.
6547
6548 // Copy the output from the appropriate register. Find a register that
6549 // we can use.
Chris Lattner6b77a072012-01-03 23:51:01 +00006550 if (OpInfo.AssignedRegs.Regs.empty()) {
6551 LLVMContext &Ctx = *DAG.getContext();
Stephen Lincfe7f352013-07-08 00:37:03 +00006552 Ctx.emitError(CS.getInstruction(),
Chris Lattner6b77a072012-01-03 23:51:01 +00006553 "couldn't allocate output register for constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006554 Twine(OpInfo.ConstraintCode) + "'");
6555 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006556 }
Dan Gohman575fad32008-09-03 16:12:24 +00006557
6558 // If this is an indirect operand, store through the pointer after the
6559 // asm.
6560 if (OpInfo.isIndirect) {
6561 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6562 OpInfo.CallOperandVal));
6563 } else {
6564 // This is the result value of the call.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00006565 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohman575fad32008-09-03 16:12:24 +00006566 // Concatenate this output onto the outputs list.
6567 RetValRegs.append(OpInfo.AssignedRegs);
6568 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006569
Dan Gohman575fad32008-09-03 16:12:24 +00006570 // Add information to the INLINEASM node to know that this register is
6571 // set.
Eric Christopher029af152013-07-30 22:50:44 +00006572 OpInfo.AssignedRegs
6573 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6574 ? InlineAsm::Kind_RegDefEarlyClobber
6575 : InlineAsm::Kind_RegDef,
6576 false, 0, DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006577 break;
6578 }
6579 case InlineAsm::isInput: {
6580 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006581
Chris Lattner860df6e2008-10-17 16:47:46 +00006582 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohman575fad32008-09-03 16:12:24 +00006583 // If this is required to match an output register we have already set,
6584 // just use its register.
Chris Lattneref890172008-10-17 16:21:11 +00006585 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006586
Dan Gohman575fad32008-09-03 16:12:24 +00006587 // Scan until we find the definition we already emitted of this operand.
6588 // When we find it, create a RegsForValue operand.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006589 unsigned CurOp = InlineAsm::Op_FirstOperand;
Dan Gohman575fad32008-09-03 16:12:24 +00006590 for (; OperandNo; --OperandNo) {
6591 // Advance to the next operand.
Evan Cheng2e559232009-03-20 18:03:34 +00006592 unsigned OpFlag =
Dan Gohmaneffb8942008-09-12 16:56:44 +00006593 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006594 assert((InlineAsm::isRegDefKind(OpFlag) ||
6595 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6596 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
Evan Cheng2e559232009-03-20 18:03:34 +00006597 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohman575fad32008-09-03 16:12:24 +00006598 }
6599
Evan Cheng2e559232009-03-20 18:03:34 +00006600 unsigned OpFlag =
Dan Gohmaneffb8942008-09-12 16:56:44 +00006601 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006602 if (InlineAsm::isRegDefKind(OpFlag) ||
6603 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
Evan Cheng2e559232009-03-20 18:03:34 +00006604 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Chris Lattner3c65a832010-04-08 00:09:16 +00006605 if (OpInfo.isIndirect) {
6606 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
Dan Gohman7c0303a2010-04-19 22:41:47 +00006607 LLVMContext &Ctx = *DAG.getContext();
Eric Christophere6656ac2013-07-31 01:26:24 +00006608 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6609 " don't know how to handle tied "
6610 "indirect register inputs");
6611 return;
Chris Lattner3c65a832010-04-08 00:09:16 +00006612 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006613
Dan Gohman575fad32008-09-03 16:12:24 +00006614 RegsForValue MatchedRegs;
Dan Gohman575fad32008-09-03 16:12:24 +00006615 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00006616 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
Evan Cheng968c3b02009-03-23 08:01:15 +00006617 MatchedRegs.RegVTs.push_back(RegVT);
6618 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng2e559232009-03-20 18:03:34 +00006619 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Chad Rosier108d5a62013-04-24 22:53:10 +00006620 i != e; ++i) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006621 if (const TargetRegisterClass *RC = TLI->getRegClassFor(RegVT))
Chad Rosier108d5a62013-04-24 22:53:10 +00006622 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6623 else {
6624 LLVMContext &Ctx = *DAG.getContext();
Eric Christophere6656ac2013-07-31 01:26:24 +00006625 Ctx.emitError(CS.getInstruction(),
6626 "inline asm error: This value"
Chad Rosier108d5a62013-04-24 22:53:10 +00006627 " type register class is not natively supported!");
Eric Christophere6656ac2013-07-31 01:26:24 +00006628 return;
Chad Rosier108d5a62013-04-24 22:53:10 +00006629 }
6630 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006631 // Use the produced MatchedRegs object to
Andrew Trickef9de2a2013-05-25 02:42:55 +00006632 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
Bill Wendling5def8912012-09-26 06:16:18 +00006633 Chain, &Flag, CS.getInstruction());
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006634 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
Evan Cheng968c3b02009-03-23 08:01:15 +00006635 true, OpInfo.getMatchedOperand(),
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006636 DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006637 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006638 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006639
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006640 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6641 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6642 "Unexpected number of operands");
6643 // Add information to the INLINEASM node to know about this input.
6644 // See InlineAsm.h isUseOperandTiedToDef.
6645 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6646 OpInfo.getMatchedOperand());
6647 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006648 TLI->getPointerTy()));
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006649 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6650 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006651 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006652
Dale Johannesencaca5482010-07-13 20:17:05 +00006653 // Treat indirect 'X' constraint as memory.
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006654 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6655 OpInfo.isIndirect)
Dale Johannesencaca5482010-07-13 20:17:05 +00006656 OpInfo.ConstraintType = TargetLowering::C_Memory;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006657
Dale Johannesencaca5482010-07-13 20:17:05 +00006658 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Dan Gohman575fad32008-09-03 16:12:24 +00006659 std::vector<SDValue> Ops;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006660 TLI->LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6661 Ops, DAG);
Chris Lattner6b77a072012-01-03 23:51:01 +00006662 if (Ops.empty()) {
6663 LLVMContext &Ctx = *DAG.getContext();
6664 Ctx.emitError(CS.getInstruction(),
6665 "invalid operand for inline asm constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006666 Twine(OpInfo.ConstraintCode) + "'");
6667 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006668 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006669
Dan Gohman575fad32008-09-03 16:12:24 +00006670 // Add information to the INLINEASM node to know about this input.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006671 unsigned ResOpType =
6672 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006673 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006674 TLI->getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006675 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6676 break;
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006677 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006678
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006679 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Dan Gohman575fad32008-09-03 16:12:24 +00006680 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006681 assert(InOperandVal.getValueType() == TLI->getPointerTy() &&
Dan Gohman575fad32008-09-03 16:12:24 +00006682 "Memory operands expect pointer values");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006683
Dan Gohman575fad32008-09-03 16:12:24 +00006684 // Add information to the INLINEASM node to know about this input.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006685 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
Dale Johannesenc36660d2008-09-24 01:07:17 +00006686 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006687 TLI->getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006688 AsmNodeOperands.push_back(InOperandVal);
6689 break;
6690 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006691
Dan Gohman575fad32008-09-03 16:12:24 +00006692 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6693 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6694 "Unknown constraint type!");
Eric Christopherdd8638f2012-07-02 21:16:43 +00006695
6696 // TODO: Support this.
6697 if (OpInfo.isIndirect) {
6698 LLVMContext &Ctx = *DAG.getContext();
6699 Ctx.emitError(CS.getInstruction(),
6700 "Don't know how to handle indirect register inputs yet "
Eric Christophere6656ac2013-07-31 01:26:24 +00006701 "for constraint '" +
6702 Twine(OpInfo.ConstraintCode) + "'");
6703 return;
Eric Christopherdd8638f2012-07-02 21:16:43 +00006704 }
Dan Gohman575fad32008-09-03 16:12:24 +00006705
6706 // Copy the input into the appropriate registers.
Chris Lattner6b77a072012-01-03 23:51:01 +00006707 if (OpInfo.AssignedRegs.Regs.empty()) {
6708 LLVMContext &Ctx = *DAG.getContext();
Stephen Lincfe7f352013-07-08 00:37:03 +00006709 Ctx.emitError(CS.getInstruction(),
Chris Lattner6b77a072012-01-03 23:51:01 +00006710 "couldn't allocate input reg for constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006711 Twine(OpInfo.ConstraintCode) + "'");
6712 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006713 }
Dan Gohman575fad32008-09-03 16:12:24 +00006714
Andrew Trickef9de2a2013-05-25 02:42:55 +00006715 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
Bill Wendling5def8912012-09-26 06:16:18 +00006716 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006717
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006718 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006719 DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006720 break;
6721 }
6722 case InlineAsm::isClobber: {
6723 // Add the clobbered value to the operand list, so that the register
6724 // allocator is aware that the physreg got clobbered.
6725 if (!OpInfo.AssignedRegs.Regs.empty())
Jakob Stoklund Olesen537a3022011-06-27 04:08:33 +00006726 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006727 false, 0, DAG,
Bill Wendlingac087582009-12-22 01:25:10 +00006728 AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006729 break;
6730 }
6731 }
6732 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006733
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006734 // Finish up input operands. Set the input chain and add the flag last.
Dale Johannesen4d887f7c2010-07-02 20:16:09 +00006735 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
Dan Gohman575fad32008-09-03 16:12:24 +00006736 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006737
Andrew Trickef9de2a2013-05-25 02:42:55 +00006738 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00006739 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006740 Flag = Chain.getValue(1);
6741
6742 // If this asm returns a register value, copy the result from that register
6743 // and set it as the value of the call.
6744 if (!RetValRegs.Regs.empty()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006745 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
Bill Wendling81406f62012-09-26 04:04:19 +00006746 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006747
Chris Lattner160e8ab2008-10-18 18:49:30 +00006748 // FIXME: Why don't we do this for inline asms with MRVs?
6749 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006750 EVT ResultType = TLI->getValueType(CS.getType());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006751
Chris Lattner160e8ab2008-10-18 18:49:30 +00006752 // If any of the results of the inline asm is a vector, it may have the
6753 // wrong width/num elts. This can happen for register classes that can
6754 // contain multiple different value types. The preg or vreg allocated may
6755 // not have the same VT as was expected. Convert it to the right type
6756 // with bit_convert.
6757 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006758 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00006759 ResultType, Val);
Dan Gohman6de25562008-10-18 01:03:45 +00006760
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006761 } else if (ResultType != Val.getValueType() &&
Chris Lattner160e8ab2008-10-18 18:49:30 +00006762 ResultType.isInteger() && Val.getValueType().isInteger()) {
6763 // If a result value was tied to an input value, the computed result may
6764 // have a wider width than the expected result. Extract the relevant
6765 // portion.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006766 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
Dan Gohman6de25562008-10-18 01:03:45 +00006767 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006768
Chris Lattner160e8ab2008-10-18 18:49:30 +00006769 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner052092b2008-10-17 17:52:49 +00006770 }
Dan Gohman6de25562008-10-18 01:03:45 +00006771
Dan Gohman575fad32008-09-03 16:12:24 +00006772 setValue(CS.getInstruction(), Val);
Dale Johannesen83593f42009-04-14 00:56:56 +00006773 // Don't need to use this as a chain in this case.
6774 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6775 return;
Dan Gohman575fad32008-09-03 16:12:24 +00006776 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006777
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006778 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006779
Dan Gohman575fad32008-09-03 16:12:24 +00006780 // Process indirect outputs, first output all of the flagged copies out of
6781 // physregs.
6782 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6783 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006784 const Value *Ptr = IndirectStoresToEmit[i].second;
Andrew Trickef9de2a2013-05-25 02:42:55 +00006785 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
Bill Wendling81406f62012-09-26 04:04:19 +00006786 Chain, &Flag, IA);
Dan Gohman575fad32008-09-03 16:12:24 +00006787 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6788 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006789
Dan Gohman575fad32008-09-03 16:12:24 +00006790 // Emit the non-flagged stores from the physregs.
6791 SmallVector<SDValue, 8> OutChains;
Bill Wendlingac087582009-12-22 01:25:10 +00006792 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006793 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
Bill Wendlingac087582009-12-22 01:25:10 +00006794 StoresToEmit[i].first,
6795 getValue(StoresToEmit[i].second),
Chris Lattnera4f19972010-09-21 18:58:22 +00006796 MachinePointerInfo(StoresToEmit[i].second),
David Greene39c6d012010-02-15 17:00:31 +00006797 false, false, 0);
Bill Wendlingac087582009-12-22 01:25:10 +00006798 OutChains.push_back(Val);
Bill Wendlingac087582009-12-22 01:25:10 +00006799 }
6800
Dan Gohman575fad32008-09-03 16:12:24 +00006801 if (!OutChains.empty())
Craig Topper48d114b2014-04-26 18:35:24 +00006802 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
Bill Wendlingac087582009-12-22 01:25:10 +00006803
Dan Gohman575fad32008-09-03 16:12:24 +00006804 DAG.setRoot(Chain);
6805}
6806
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006807void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006808 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006809 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006810 getValue(I.getArgOperand(0)),
6811 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00006812}
6813
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006814void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
Eric Christopherd9134482014-08-04 21:25:23 +00006815 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Rafael Espindola5f57f462014-02-21 18:34:28 +00006816 const DataLayout &DL = *TLI->getDataLayout();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006817 SDValue V = DAG.getVAArg(TLI->getValueType(I.getType()), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00006818 getRoot(), getValue(I.getOperand(0)),
Rafael Espindolaa76eccf2010-07-11 04:01:49 +00006819 DAG.getSrcValue(I.getOperand(0)),
Rafael Espindola5f57f462014-02-21 18:34:28 +00006820 DL.getABITypeAlignment(I.getType()));
Dan Gohman575fad32008-09-03 16:12:24 +00006821 setValue(&I, V);
6822 DAG.setRoot(V.getValue(1));
6823}
6824
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006825void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006826 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006827 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006828 getValue(I.getArgOperand(0)),
6829 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00006830}
6831
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006832void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006833 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006834 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006835 getValue(I.getArgOperand(0)),
6836 getValue(I.getArgOperand(1)),
6837 DAG.getSrcValue(I.getArgOperand(0)),
6838 DAG.getSrcValue(I.getArgOperand(1))));
Dan Gohman575fad32008-09-03 16:12:24 +00006839}
6840
Andrew Trick74f4c742013-10-31 17:18:24 +00006841/// \brief Lower an argument list according to the target calling convention.
6842///
6843/// \return A tuple of <return-value, token-chain>
6844///
6845/// This is a helper for lowering intrinsics that follow a target calling
6846/// convention or require stack pointer adjustment. Only a subset of the
6847/// intrinsic's operands need to participate in the calling convention.
6848std::pair<SDValue, SDValue>
6849SelectionDAGBuilder::LowerCallOperands(const CallInst &CI, unsigned ArgIdx,
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006850 unsigned NumArgs, SDValue Callee,
6851 bool useVoidTy) {
Andrew Trick74f4c742013-10-31 17:18:24 +00006852 TargetLowering::ArgListTy Args;
6853 Args.reserve(NumArgs);
6854
6855 // Populate the argument list.
6856 // Attributes for args start at offset 1, after the return attribute.
6857 ImmutableCallSite CS(&CI);
6858 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6859 ArgI != ArgE; ++ArgI) {
6860 const Value *V = CI.getOperand(ArgI);
6861
6862 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6863
6864 TargetLowering::ArgListEntry Entry;
6865 Entry.Node = getValue(V);
6866 Entry.Ty = V->getType();
6867 Entry.setAttributes(&CS, AttrI);
6868 Args.push_back(Entry);
6869 }
6870
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006871 Type *retTy = useVoidTy ? Type::getVoidTy(*DAG.getContext()) : CI.getType();
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00006872 TargetLowering::CallLoweringInfo CLI(DAG);
6873 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00006874 .setCallee(CI.getCallingConv(), retTy, Callee, std::move(Args), NumArgs)
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00006875 .setDiscardResult(!CI.use_empty());
Andrew Trick74f4c742013-10-31 17:18:24 +00006876
Eric Christopherd9134482014-08-04 21:25:23 +00006877 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Andrew Trick74f4c742013-10-31 17:18:24 +00006878 return TLI->LowerCallTo(CLI);
6879}
6880
Andrew Trick4a1abb72013-11-22 19:07:36 +00006881/// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6882/// or patchpoint target node's operand list.
Andrew Trick391dbad2013-11-26 02:03:25 +00006883///
6884/// Constants are converted to TargetConstants purely as an optimization to
6885/// avoid constant materialization and register allocation.
6886///
6887/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6888/// generate addess computation nodes, and so ExpandISelPseudo can convert the
6889/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6890/// address materialization and register allocation, but may also be required
6891/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6892/// alloca in the entry block, then the runtime may assume that the alloca's
6893/// StackMap location can be read immediately after compilation and that the
6894/// location is valid at any point during execution (this is similar to the
6895/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6896/// only available in a register, then the runtime would need to trap when
6897/// execution reaches the StackMap in order to read the alloca's location.
Andrew Trick4a1abb72013-11-22 19:07:36 +00006898static void addStackMapLiveVars(const CallInst &CI, unsigned StartIdx,
6899 SmallVectorImpl<SDValue> &Ops,
6900 SelectionDAGBuilder &Builder) {
6901 for (unsigned i = StartIdx, e = CI.getNumArgOperands(); i != e; ++i) {
6902 SDValue OpVal = Builder.getValue(CI.getArgOperand(i));
6903 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6904 Ops.push_back(
6905 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
6906 Ops.push_back(
6907 Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
Andrew Trick391dbad2013-11-26 02:03:25 +00006908 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6909 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6910 Ops.push_back(
6911 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
Andrew Trick4a1abb72013-11-22 19:07:36 +00006912 } else
6913 Ops.push_back(OpVal);
6914 }
6915}
6916
Andrew Trick74f4c742013-10-31 17:18:24 +00006917/// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6918void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6919 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6920 // [live variables...])
6921
6922 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6923
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006924 SDValue Chain, InFlag, Callee, NullPtr;
6925 SmallVector<SDValue, 32> Ops;
Andrew Trick74f4c742013-10-31 17:18:24 +00006926
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006927 SDLoc DL = getCurSDLoc();
6928 Callee = getValue(CI.getCalledValue());
6929 NullPtr = DAG.getIntPtrConstant(0, true);
Andrew Trick74f4c742013-10-31 17:18:24 +00006930
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006931 // The stackmap intrinsic only records the live variables (the arguemnts
6932 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
6933 // intrinsic, this won't be lowered to a function call. This means we don't
6934 // have to worry about calling conventions and target specific lowering code.
6935 // Instead we perform the call lowering right here.
6936 //
6937 // chain, flag = CALLSEQ_START(chain, 0)
6938 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
6939 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
6940 //
6941 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
6942 InFlag = Chain.getValue(1);
Andrew Trick74f4c742013-10-31 17:18:24 +00006943
Juergen Ributzkaaa30da32014-02-12 22:17:10 +00006944 // Add the <id> and <numBytes> constants.
6945 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
6946 Ops.push_back(DAG.getTargetConstant(
6947 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
6948 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
6949 Ops.push_back(DAG.getTargetConstant(
6950 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006951
Andrew Trick74f4c742013-10-31 17:18:24 +00006952 // Push live variables for the stack map.
Andrew Trick4a1abb72013-11-22 19:07:36 +00006953 addStackMapLiveVars(CI, 2, Ops, *this);
Andrew Trick74f4c742013-10-31 17:18:24 +00006954
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006955 // We are not pushing any register mask info here on the operands list,
6956 // because the stackmap doesn't clobber anything.
Andrew Trick74f4c742013-10-31 17:18:24 +00006957
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006958 // Push the chain and the glue flag.
6959 Ops.push_back(Chain);
6960 Ops.push_back(InFlag);
Andrew Trick74f4c742013-10-31 17:18:24 +00006961
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006962 // Create the STACKMAP node.
Andrew Trick74f4c742013-10-31 17:18:24 +00006963 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006964 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
6965 Chain = SDValue(SM, 0);
6966 InFlag = Chain.getValue(1);
Andrew Trick6664df12013-11-05 22:44:04 +00006967
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006968 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
Andrew Trick6664df12013-11-05 22:44:04 +00006969
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006970 // Stackmaps don't generate values, so nothing goes into the NodeMap.
Andrew Trick6664df12013-11-05 22:44:04 +00006971
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006972 // Set the root to the target-lowered call chain.
6973 DAG.setRoot(Chain);
Juergen Ributzkae8294752013-12-14 06:53:06 +00006974
6975 // Inform the Frame Information that we have a stackmap in this function.
6976 FuncInfo.MF->getFrameInfo()->setHasStackMap();
Andrew Trick74f4c742013-10-31 17:18:24 +00006977}
6978
6979/// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
6980void SelectionDAGBuilder::visitPatchpoint(const CallInst &CI) {
Andrew Tricke8cba372013-12-13 18:37:10 +00006981 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
Andrew Trick561f2212013-11-14 06:54:10 +00006982 // i32 <numBytes>,
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006983 // i8* <target>,
6984 // i32 <numArgs>,
6985 // [Args...],
6986 // [live variables...])
Andrew Trick74f4c742013-10-31 17:18:24 +00006987
Juergen Ributzka87ed9062013-11-09 01:51:33 +00006988 CallingConv::ID CC = CI.getCallingConv();
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006989 bool isAnyRegCC = CC == CallingConv::AnyReg;
6990 bool hasDef = !CI.getType()->isVoidTy();
Andrew Trick74f4c742013-10-31 17:18:24 +00006991 SDValue Callee = getValue(CI.getOperand(2)); // <target>
6992
6993 // Get the real number of arguments participating in the call <numArgs>
Andrew Tricka2428e02013-11-22 19:07:33 +00006994 SDValue NArgVal = getValue(CI.getArgOperand(PatchPointOpers::NArgPos));
6995 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
Andrew Trick74f4c742013-10-31 17:18:24 +00006996
6997 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
Andrew Tricka2428e02013-11-22 19:07:33 +00006998 // Intrinsics include all meta-operands up to but not including CC.
6999 unsigned NumMetaOpers = PatchPointOpers::CCPos;
7000 assert(CI.getNumArgOperands() >= NumMetaOpers + NumArgs &&
Andrew Trick74f4c742013-10-31 17:18:24 +00007001 "Not enough arguments provided to the patchpoint intrinsic");
7002
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007003 // For AnyRegCC the arguments are lowered later on manually.
7004 unsigned NumCallArgs = isAnyRegCC ? 0 : NumArgs;
Andrew Trick74f4c742013-10-31 17:18:24 +00007005 std::pair<SDValue, SDValue> Result =
Andrew Tricka2428e02013-11-22 19:07:33 +00007006 LowerCallOperands(CI, NumMetaOpers, NumCallArgs, Callee, isAnyRegCC);
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007007
Andrew Trick74f4c742013-10-31 17:18:24 +00007008 // Set the root to the target-lowered call chain.
7009 SDValue Chain = Result.second;
7010 DAG.setRoot(Chain);
7011
7012 SDNode *CallEnd = Chain.getNode();
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007013 if (hasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7014 CallEnd = CallEnd->getOperand(0).getNode();
7015
Andrew Trick74f4c742013-10-31 17:18:24 +00007016 /// Get a call instruction from the call sequence chain.
7017 /// Tail calls are not allowed.
7018 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7019 "Expected a callseq node.");
7020 SDNode *Call = CallEnd->getOperand(0).getNode();
7021 bool hasGlue = Call->getGluedNode();
7022
7023 // Replace the target specific call node with the patchable intrinsic.
7024 SmallVector<SDValue, 8> Ops;
7025
Andrew Tricka2428e02013-11-22 19:07:33 +00007026 // Add the <id> and <numBytes> constants.
7027 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7028 Ops.push_back(DAG.getTargetConstant(
Andrew Tricke8cba372013-12-13 18:37:10 +00007029 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
Andrew Tricka2428e02013-11-22 19:07:33 +00007030 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7031 Ops.push_back(DAG.getTargetConstant(
7032 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
7033
Andrew Trick74f4c742013-10-31 17:18:24 +00007034 // Assume that the Callee is a constant address.
Andrew Tricka2428e02013-11-22 19:07:33 +00007035 // FIXME: handle function symbols in the future.
Andrew Trick74f4c742013-10-31 17:18:24 +00007036 Ops.push_back(
Juergen Ributzka87ed9062013-11-09 01:51:33 +00007037 DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
7038 /*isTarget=*/true));
Andrew Trick74f4c742013-10-31 17:18:24 +00007039
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007040 // Adjust <numArgs> to account for any arguments that have been passed on the
7041 // stack instead.
Andrew Trick74f4c742013-10-31 17:18:24 +00007042 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007043 unsigned NumCallRegArgs = Call->getNumOperands() - (hasGlue ? 4 : 3);
7044 NumCallRegArgs = isAnyRegCC ? NumArgs : NumCallRegArgs;
7045 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
7046
7047 // Add the calling convention
Juergen Ributzka87ed9062013-11-09 01:51:33 +00007048 Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007049
7050 // Add the arguments we omitted previously. The register allocator should
7051 // place these in any free register.
7052 if (isAnyRegCC)
Andrew Tricka2428e02013-11-22 19:07:33 +00007053 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007054 Ops.push_back(getValue(CI.getArgOperand(i)));
Andrew Trick74f4c742013-10-31 17:18:24 +00007055
Andrew Tricka2428e02013-11-22 19:07:33 +00007056 // Push the arguments from the call instruction up to the register mask.
Andrew Trick74f4c742013-10-31 17:18:24 +00007057 SDNode::op_iterator e = hasGlue ? Call->op_end()-2 : Call->op_end()-1;
7058 for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
7059 Ops.push_back(*i);
7060
7061 // Push live variables for the stack map.
Andrew Trick4a1abb72013-11-22 19:07:36 +00007062 addStackMapLiveVars(CI, NumMetaOpers + NumArgs, Ops, *this);
Andrew Trick74f4c742013-10-31 17:18:24 +00007063
7064 // Push the register mask info.
7065 if (hasGlue)
7066 Ops.push_back(*(Call->op_end()-2));
7067 else
7068 Ops.push_back(*(Call->op_end()-1));
7069
7070 // Push the chain (this is originally the first operand of the call, but
7071 // becomes now the last or second to last operand).
7072 Ops.push_back(*(Call->op_begin()));
7073
7074 // Push the glue flag (last operand).
7075 if (hasGlue)
7076 Ops.push_back(*(Call->op_end()-1));
7077
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007078 SDVTList NodeTys;
7079 if (isAnyRegCC && hasDef) {
7080 // Create the return types based on the intrinsic definition
7081 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7082 SmallVector<EVT, 3> ValueVTs;
7083 ComputeValueVTs(TLI, CI.getType(), ValueVTs);
7084 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
Andrew Trick6664df12013-11-05 22:44:04 +00007085
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007086 // There is always a chain and a glue type at the end
7087 ValueVTs.push_back(MVT::Other);
7088 ValueVTs.push_back(MVT::Glue);
Craig Topperabb4ac72014-04-16 06:10:51 +00007089 NodeTys = DAG.getVTList(ValueVTs);
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007090 } else
7091 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7092
7093 // Replace the target specific call node with a PATCHPOINT node.
Andrew Trick6664df12013-11-05 22:44:04 +00007094 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7095 getCurSDLoc(), NodeTys, Ops);
7096
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007097 // Update the NodeMap.
7098 if (hasDef) {
7099 if (isAnyRegCC)
7100 setValue(&CI, SDValue(MN, 0));
7101 else
7102 setValue(&CI, Result.first);
7103 }
Andrew Trick6664df12013-11-05 22:44:04 +00007104
7105 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007106 // call sequence. Furthermore the location of the chain and glue can change
7107 // when the AnyReg calling convention is used and the intrinsic returns a
7108 // value.
7109 if (isAnyRegCC && hasDef) {
7110 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7111 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7112 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7113 } else
7114 DAG.ReplaceAllUsesWith(Call, MN);
Andrew Trick6664df12013-11-05 22:44:04 +00007115 DAG.DeleteNode(Call);
Juergen Ributzkae8294752013-12-14 06:53:06 +00007116
7117 // Inform the Frame Information that we have a patchpoint in this function.
7118 FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
Andrew Trick74f4c742013-10-31 17:18:24 +00007119}
7120
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007121/// Returns an AttributeSet representing the attributes applied to the return
7122/// value of the given call.
7123static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7124 SmallVector<Attribute::AttrKind, 2> Attrs;
7125 if (CLI.RetSExt)
7126 Attrs.push_back(Attribute::SExt);
7127 if (CLI.RetZExt)
7128 Attrs.push_back(Attribute::ZExt);
7129 if (CLI.IsInReg)
7130 Attrs.push_back(Attribute::InReg);
7131
7132 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
7133 Attrs);
7134}
7135
Dan Gohman575fad32008-09-03 16:12:24 +00007136/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007137/// implementation, which just calls LowerCall.
7138/// FIXME: When all targets are
7139/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohman575fad32008-09-03 16:12:24 +00007140std::pair<SDValue, SDValue>
Justin Holewinskiaa583972012-05-25 16:35:28 +00007141TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
Stephen Lin699808c2013-04-30 22:49:28 +00007142 // Handle the incoming return values from the call.
7143 CLI.Ins.clear();
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007144 Type *OrigRetTy = CLI.RetTy;
Stephen Lin699808c2013-04-30 22:49:28 +00007145 SmallVector<EVT, 4> RetTys;
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007146 SmallVector<uint64_t, 4> Offsets;
7147 ComputeValueVTs(*this, CLI.RetTy, RetTys, &Offsets);
7148
7149 SmallVector<ISD::OutputArg, 4> Outs;
7150 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this);
7151
7152 bool CanLowerReturn =
7153 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7154 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7155
7156 SDValue DemoteStackSlot;
7157 int DemoteStackIdx = -100;
7158 if (!CanLowerReturn) {
7159 // FIXME: equivalent assert?
7160 // assert(!CS.hasInAllocaArgument() &&
7161 // "sret demotion is incompatible with inalloca");
7162 uint64_t TySize = getDataLayout()->getTypeAllocSize(CLI.RetTy);
7163 unsigned Align = getDataLayout()->getPrefTypeAlignment(CLI.RetTy);
7164 MachineFunction &MF = CLI.DAG.getMachineFunction();
7165 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
7166 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7167
7168 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy());
7169 ArgListEntry Entry;
7170 Entry.Node = DemoteStackSlot;
7171 Entry.Ty = StackSlotPtrType;
7172 Entry.isSExt = false;
7173 Entry.isZExt = false;
7174 Entry.isInReg = false;
7175 Entry.isSRet = true;
7176 Entry.isNest = false;
7177 Entry.isByVal = false;
7178 Entry.isReturned = false;
7179 Entry.Alignment = Align;
7180 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7181 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7182 } else {
7183 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7184 EVT VT = RetTys[I];
7185 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7186 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7187 for (unsigned i = 0; i != NumRegs; ++i) {
7188 ISD::InputArg MyFlags;
7189 MyFlags.VT = RegisterVT;
7190 MyFlags.ArgVT = VT;
7191 MyFlags.Used = CLI.IsReturnValueUsed;
7192 if (CLI.RetSExt)
7193 MyFlags.Flags.setSExt();
7194 if (CLI.RetZExt)
7195 MyFlags.Flags.setZExt();
7196 if (CLI.IsInReg)
7197 MyFlags.Flags.setInReg();
7198 CLI.Ins.push_back(MyFlags);
7199 }
Stephen Lin699808c2013-04-30 22:49:28 +00007200 }
7201 }
7202
Dan Gohman575fad32008-09-03 16:12:24 +00007203 // Handle all of the outgoing arguments.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007204 CLI.Outs.clear();
7205 CLI.OutVals.clear();
Saleem Abdulrasool9f664c12014-05-17 21:50:01 +00007206 ArgListTy &Args = CLI.getArgs();
Dan Gohman575fad32008-09-03 16:12:24 +00007207 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007208 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00007209 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
Oliver Stannardc24f2172014-05-09 14:01:47 +00007210 Type *FinalType = Args[i].Ty;
7211 if (Args[i].isByVal)
7212 FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
7213 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
7214 FinalType, CLI.CallConv, CLI.IsVarArg);
7215 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
7216 ++Value) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007217 EVT VT = ValueVTs[Value];
Justin Holewinskiaa583972012-05-25 16:35:28 +00007218 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
Chris Lattner160e8ab2008-10-18 18:49:30 +00007219 SDValue Op = SDValue(Args[i].Node.getNode(),
7220 Args[i].Node.getResNo() + Value);
Dan Gohman575fad32008-09-03 16:12:24 +00007221 ISD::ArgFlagsTy Flags;
Matt Arsenault443252c2014-04-21 18:39:13 +00007222 unsigned OriginalAlignment = getDataLayout()->getABITypeAlignment(ArgTy);
Dan Gohman575fad32008-09-03 16:12:24 +00007223
7224 if (Args[i].isZExt)
7225 Flags.setZExt();
7226 if (Args[i].isSExt)
7227 Flags.setSExt();
7228 if (Args[i].isInReg)
7229 Flags.setInReg();
7230 if (Args[i].isSRet)
7231 Flags.setSRet();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007232 if (Args[i].isByVal)
Dan Gohman575fad32008-09-03 16:12:24 +00007233 Flags.setByVal();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007234 if (Args[i].isInAlloca) {
7235 Flags.setInAlloca();
7236 // Set the byval flag for CCAssignFn callbacks that don't know about
7237 // inalloca. This way we can know how many bytes we should've allocated
7238 // and how many bytes a callee cleanup function will pop. If we port
7239 // inalloca to more targets, we'll have to add custom inalloca handling
7240 // in the various CC lowering callbacks.
7241 Flags.setByVal();
7242 }
7243 if (Args[i].isByVal || Args[i].isInAlloca) {
Chris Lattner229907c2011-07-18 04:54:35 +00007244 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7245 Type *ElementTy = Ty->getElementType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00007246 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
Dan Gohman575fad32008-09-03 16:12:24 +00007247 // For ByVal, alignment should come from FE. BE will guess if this
7248 // info is not there but there are cases it cannot get right.
Chris Lattner68254fc2011-05-22 23:23:02 +00007249 unsigned FrameAlign;
Dan Gohman575fad32008-09-03 16:12:24 +00007250 if (Args[i].Alignment)
7251 FrameAlign = Args[i].Alignment;
Chris Lattner68254fc2011-05-22 23:23:02 +00007252 else
7253 FrameAlign = getByValTypeAlignment(ElementTy);
Dan Gohman575fad32008-09-03 16:12:24 +00007254 Flags.setByValAlign(FrameAlign);
Dan Gohman575fad32008-09-03 16:12:24 +00007255 }
7256 if (Args[i].isNest)
7257 Flags.setNest();
Tim Northover4f1909f2014-05-27 10:43:38 +00007258 if (NeedsRegBlock)
Oliver Stannardc24f2172014-05-09 14:01:47 +00007259 Flags.setInConsecutiveRegs();
Dan Gohman575fad32008-09-03 16:12:24 +00007260 Flags.setOrigAlign(OriginalAlignment);
7261
Patrik Hagglundbad545c2012-12-19 11:48:16 +00007262 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
Justin Holewinskiaa583972012-05-25 16:35:28 +00007263 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohman575fad32008-09-03 16:12:24 +00007264 SmallVector<SDValue, 4> Parts(NumParts);
7265 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7266
7267 if (Args[i].isSExt)
7268 ExtendKind = ISD::SIGN_EXTEND;
7269 else if (Args[i].isZExt)
7270 ExtendKind = ISD::ZERO_EXTEND;
7271
Stephen Lin699808c2013-04-30 22:49:28 +00007272 // Conservatively only handle 'returned' on non-vectors for now
7273 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7274 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7275 "unexpected use of 'returned'");
7276 // Before passing 'returned' to the target lowering code, ensure that
7277 // either the register MVT and the actual EVT are the same size or that
7278 // the return value and argument are extended in the same way; in these
7279 // cases it's safe to pass the argument register value unchanged as the
7280 // return register value (although it's at the target's option whether
7281 // to do so)
7282 // TODO: allow code generation to take advantage of partially preserved
7283 // registers rather than clobbering the entire register when the
7284 // parameter extension method is not compatible with the return
7285 // extension method
7286 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7287 (ExtendKind != ISD::ANY_EXTEND &&
7288 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7289 Flags.setReturned();
7290 }
7291
Craig Topperc0196b12014-04-14 00:51:57 +00007292 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
7293 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
Dan Gohman575fad32008-09-03 16:12:24 +00007294
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007295 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohman575fad32008-09-03 16:12:24 +00007296 // if it isn't first piece, alignment must be 1
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007297 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
Manman Ren3d5af272012-11-01 23:49:58 +00007298 i < CLI.NumFixedArgs,
7299 i, j*Parts[j].getValueType().getStoreSize());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007300 if (NumParts > 1 && j == 0)
7301 MyFlags.Flags.setSplit();
7302 else if (j != 0)
7303 MyFlags.Flags.setOrigAlign(1);
Dan Gohman575fad32008-09-03 16:12:24 +00007304
Tim Northover4f1909f2014-05-27 10:43:38 +00007305 // Only mark the end at the last register of the last value.
7306 if (NeedsRegBlock && Value == NumValues - 1 && j == NumParts - 1)
7307 MyFlags.Flags.setInConsecutiveRegsLast();
7308
Justin Holewinskiaa583972012-05-25 16:35:28 +00007309 CLI.Outs.push_back(MyFlags);
7310 CLI.OutVals.push_back(Parts[j]);
Dan Gohman575fad32008-09-03 16:12:24 +00007311 }
7312 }
7313 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007314
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007315 SmallVector<SDValue, 4> InVals;
Justin Holewinskiaa583972012-05-25 16:35:28 +00007316 CLI.Chain = LowerCall(CLI, InVals);
Dan Gohman695d8112009-08-06 15:37:27 +00007317
7318 // Verify that the target's LowerCall behaved as expected.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007319 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00007320 "LowerCall didn't return a valid chain!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007321 assert((!CLI.IsTailCall || InVals.empty()) &&
Dan Gohman695d8112009-08-06 15:37:27 +00007322 "LowerCall emitted a return value for a tail call!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007323 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
Dan Gohman695d8112009-08-06 15:37:27 +00007324 "LowerCall didn't emit the correct number of values!");
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007325
7326 // For a tail call, the return value is merely live-out and there aren't
7327 // any nodes in the DAG representing it. Return a special value to
7328 // indicate that a tail call has been emitted and no more Instructions
7329 // should be processed in the current block.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007330 if (CLI.IsTailCall) {
7331 CLI.DAG.setRoot(CLI.Chain);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007332 return std::make_pair(SDValue(), SDValue());
7333 }
7334
Justin Holewinskiaa583972012-05-25 16:35:28 +00007335 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
Evan Cheng180704d2010-03-11 19:38:18 +00007336 assert(InVals[i].getNode() &&
7337 "LowerCall emitted a null value!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007338 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
Evan Cheng180704d2010-03-11 19:38:18 +00007339 "LowerCall emitted a value with the wrong type!");
7340 });
7341
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007342 SmallVector<SDValue, 4> ReturnValues;
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007343 if (!CanLowerReturn) {
7344 // The instruction result is the result of loading from the
7345 // hidden sret parameter.
7346 SmallVector<EVT, 1> PVTs;
7347 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007348
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007349 ComputeValueVTs(*this, PtrRetTy, PVTs);
7350 assert(PVTs.size() == 1 && "Pointers should fit in one register");
7351 EVT PtrVT = PVTs[0];
7352
7353 unsigned NumValues = RetTys.size();
7354 ReturnValues.resize(NumValues);
7355 SmallVector<SDValue, 4> Chains(NumValues);
7356
7357 for (unsigned i = 0; i < NumValues; ++i) {
7358 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
7359 CLI.DAG.getConstant(Offsets[i], PtrVT));
7360 SDValue L = CLI.DAG.getLoad(
7361 RetTys[i], CLI.DL, CLI.Chain, Add,
7362 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false,
7363 false, false, 1);
7364 ReturnValues[i] = L;
7365 Chains[i] = L.getValue(1);
7366 }
7367
7368 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
7369 } else {
7370 // Collect the legal value parts into potentially illegal values
7371 // that correspond to the original function's return values.
7372 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7373 if (CLI.RetSExt)
7374 AssertOp = ISD::AssertSext;
7375 else if (CLI.RetZExt)
7376 AssertOp = ISD::AssertZext;
7377 unsigned CurReg = 0;
7378 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7379 EVT VT = RetTys[I];
7380 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7381 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7382
7383 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7384 NumRegs, RegisterVT, VT, nullptr,
7385 AssertOp));
7386 CurReg += NumRegs;
7387 }
7388
7389 // For a function returning void, there is no return value. We can't create
7390 // such a node, so we just return a null return value in that case. In
7391 // that case, nothing will actually look at the value.
7392 if (ReturnValues.empty())
7393 return std::make_pair(SDValue(), CLI.Chain);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007394 }
7395
Justin Holewinskiaa583972012-05-25 16:35:28 +00007396 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
Craig Topper48d114b2014-04-26 18:35:24 +00007397 CLI.DAG.getVTList(RetTys), ReturnValues);
Justin Holewinskiaa583972012-05-25 16:35:28 +00007398 return std::make_pair(Res, CLI.Chain);
Dan Gohman575fad32008-09-03 16:12:24 +00007399}
7400
Duncan Sandsbe7e4142009-01-21 09:00:29 +00007401void TargetLowering::LowerOperationWrapper(SDNode *N,
7402 SmallVectorImpl<SDValue> &Results,
Dan Gohman21cea8a2010-04-17 15:26:15 +00007403 SelectionDAG &DAG) const {
Duncan Sandsbe7e4142009-01-21 09:00:29 +00007404 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptaa70798c2009-01-21 04:48:39 +00007405 if (Res.getNode())
7406 Results.push_back(Res);
7407}
7408
Dan Gohman21cea8a2010-04-17 15:26:15 +00007409SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
Torok Edwinfbcc6632009-07-14 16:55:14 +00007410 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohman575fad32008-09-03 16:12:24 +00007411}
7412
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007413void
7414SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
Dan Gohmand4322232010-07-01 01:59:43 +00007415 SDValue Op = getNonRegisterValue(V);
Dan Gohman575fad32008-09-03 16:12:24 +00007416 assert((Op.getOpcode() != ISD::CopyFromReg ||
7417 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7418 "Copy from a reg to the same reg!");
7419 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7420
Eric Christopherd9134482014-08-04 21:25:23 +00007421 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007422 RegsForValue RFV(V->getContext(), *TLI, Reg, V->getType());
Dan Gohman575fad32008-09-03 16:12:24 +00007423 SDValue Chain = DAG.getEntryNode();
Craig Topperc0196b12014-04-14 00:51:57 +00007424 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V);
Dan Gohman575fad32008-09-03 16:12:24 +00007425 PendingExports.push_back(Chain);
7426}
7427
7428#include "llvm/CodeGen/SelectionDAGISel.h"
7429
Eli Friedman441a01a2011-05-05 16:53:34 +00007430/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7431/// entry block, return true. This includes arguments used by switches, since
7432/// the switch may expand into multiple basic blocks.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007433static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007434 // With FastISel active, we may be splitting blocks, so force creation
7435 // of virtual registers for all non-dead arguments.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007436 if (FastISel)
Eli Friedman441a01a2011-05-05 16:53:34 +00007437 return A->use_empty();
7438
7439 const BasicBlock *Entry = A->getParent()->begin();
Chandler Carruthcdf47882014-03-09 03:16:01 +00007440 for (const User *U : A->users())
Eli Friedman441a01a2011-05-05 16:53:34 +00007441 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7442 return false; // Use not in entry block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00007443
Eli Friedman441a01a2011-05-05 16:53:34 +00007444 return true;
7445}
7446
Eli Bendersky33ebf832013-02-28 23:09:18 +00007447void SelectionDAGISel::LowerArguments(const Function &F) {
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007448 SelectionDAG &DAG = SDB->DAG;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007449 SDLoc dl = SDB->getCurSDLoc();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007450 const TargetLowering *TLI = getTargetLowering();
Rafael Espindola5f57f462014-02-21 18:34:28 +00007451 const DataLayout *DL = TLI->getDataLayout();
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007452 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohman575fad32008-09-03 16:12:24 +00007453
Dan Gohmand16aa542010-05-29 17:03:36 +00007454 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007455 // Put in an sret pointer parameter before all the other parameters.
7456 SmallVector<EVT, 1> ValueVTs;
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007457 ComputeValueVTs(*getTargetLowering(),
7458 PointerType::getUnqual(F.getReturnType()), ValueVTs);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007459
7460 // NOTE: Assuming that a pointer will never break down to more than one VT
7461 // or one register.
7462 ISD::ArgFlagsTy Flags;
7463 Flags.setSRet();
Bill Wendlingf7719082013-06-06 00:43:09 +00007464 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007465 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007466 Ins.push_back(RetArg);
7467 }
Kenneth Uildriks07119732009-11-07 02:11:54 +00007468
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007469 // Set up the incoming argument description vector.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007470 unsigned Idx = 1;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007471 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007472 I != E; ++I, ++Idx) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007473 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007474 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007475 bool isArgValueUsed = !I->use_empty();
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007476 unsigned PartBase = 0;
Oliver Stannardc24f2172014-05-09 14:01:47 +00007477 Type *FinalType = I->getType();
7478 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7479 FinalType = cast<PointerType>(FinalType)->getElementType();
7480 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7481 FinalType, F.getCallingConv(), F.isVarArg());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007482 for (unsigned Value = 0, NumValues = ValueVTs.size();
7483 Value != NumValues; ++Value) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007484 EVT VT = ValueVTs[Value];
Chris Lattner229907c2011-07-18 04:54:35 +00007485 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007486 ISD::ArgFlagsTy Flags;
Matt Arsenault443252c2014-04-21 18:39:13 +00007487 unsigned OriginalAlignment = DL->getABITypeAlignment(ArgTy);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007488
Bill Wendling94dcaf82012-12-30 12:45:13 +00007489 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007490 Flags.setZExt();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007491 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007492 Flags.setSExt();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007493 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007494 Flags.setInReg();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007495 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007496 Flags.setSRet();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007497 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007498 Flags.setByVal();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007499 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7500 Flags.setInAlloca();
7501 // Set the byval flag for CCAssignFn callbacks that don't know about
7502 // inalloca. This way we can know how many bytes we should've allocated
7503 // and how many bytes a callee cleanup function will pop. If we port
7504 // inalloca to more targets, we'll have to add custom inalloca handling
7505 // in the various CC lowering callbacks.
7506 Flags.setByVal();
7507 }
7508 if (Flags.isByVal() || Flags.isInAlloca()) {
Chris Lattner229907c2011-07-18 04:54:35 +00007509 PointerType *Ty = cast<PointerType>(I->getType());
7510 Type *ElementTy = Ty->getElementType();
Rafael Espindola5f57f462014-02-21 18:34:28 +00007511 Flags.setByValSize(DL->getTypeAllocSize(ElementTy));
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007512 // For ByVal, alignment should be passed from FE. BE will guess if
7513 // this info is not there but there are cases it cannot get right.
Chris Lattner68254fc2011-05-22 23:23:02 +00007514 unsigned FrameAlign;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007515 if (F.getParamAlignment(Idx))
7516 FrameAlign = F.getParamAlignment(Idx);
Chris Lattner68254fc2011-05-22 23:23:02 +00007517 else
Bill Wendlingf7719082013-06-06 00:43:09 +00007518 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007519 Flags.setByValAlign(FrameAlign);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007520 }
Bill Wendling94dcaf82012-12-30 12:45:13 +00007521 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007522 Flags.setNest();
Tim Northover4f1909f2014-05-27 10:43:38 +00007523 if (NeedsRegBlock)
Oliver Stannardc24f2172014-05-09 14:01:47 +00007524 Flags.setInConsecutiveRegs();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007525 Flags.setOrigAlign(OriginalAlignment);
7526
Bill Wendlingf7719082013-06-06 00:43:09 +00007527 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7528 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007529 for (unsigned i = 0; i != NumRegs; ++i) {
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007530 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7531 Idx-1, PartBase+i*RegisterVT.getStoreSize());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007532 if (NumRegs > 1 && i == 0)
7533 MyFlags.Flags.setSplit();
7534 // if it isn't first piece, alignment must be 1
7535 else if (i > 0)
7536 MyFlags.Flags.setOrigAlign(1);
Tim Northover4f1909f2014-05-27 10:43:38 +00007537
7538 // Only mark the end at the last register of the last value.
7539 if (NeedsRegBlock && Value == NumValues - 1 && i == NumRegs - 1)
7540 MyFlags.Flags.setInConsecutiveRegsLast();
7541
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007542 Ins.push_back(MyFlags);
7543 }
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007544 PartBase += VT.getStoreSize();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007545 }
7546 }
7547
7548 // Call the target to set up the argument values.
7549 SmallVector<SDValue, 8> InVals;
Bill Wendlingf7719082013-06-06 00:43:09 +00007550 SDValue NewRoot = TLI->LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
7551 F.isVarArg(), Ins,
7552 dl, DAG, InVals);
Dan Gohman695d8112009-08-06 15:37:27 +00007553
7554 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson9f944592009-08-11 20:47:22 +00007555 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00007556 "LowerFormalArguments didn't return a valid chain!");
7557 assert(InVals.size() == Ins.size() &&
7558 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendlingd8549812009-12-22 21:35:02 +00007559 DEBUG({
7560 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7561 assert(InVals[i].getNode() &&
7562 "LowerFormalArguments emitted a null value!");
Duncan Sandsf5dda012010-11-03 11:35:31 +00007563 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
Bill Wendlingd8549812009-12-22 21:35:02 +00007564 "LowerFormalArguments emitted a value with the wrong type!");
7565 }
7566 });
Bill Wendling919b7aa2009-12-22 02:10:19 +00007567
Dan Gohman695d8112009-08-06 15:37:27 +00007568 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007569 DAG.setRoot(NewRoot);
7570
7571 // Set up the argument values.
7572 unsigned i = 0;
7573 Idx = 1;
Dan Gohmand16aa542010-05-29 17:03:36 +00007574 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007575 // Create a virtual register for the sret pointer, and put in a copy
7576 // from the sret argument into it.
7577 SmallVector<EVT, 1> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007578 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00007579 MVT VT = ValueVTs[0].getSimpleVT();
Bill Wendlingf7719082013-06-06 00:43:09 +00007580 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007581 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling78c5b7a2010-03-02 01:55:18 +00007582 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
Craig Topperc0196b12014-04-14 00:51:57 +00007583 RegVT, VT, nullptr, AssertOp);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007584
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007585 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007586 MachineRegisterInfo& RegInfo = MF.getRegInfo();
Bill Wendlingf7719082013-06-06 00:43:09 +00007587 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
Dan Gohmand16aa542010-05-29 17:03:36 +00007588 FuncInfo->DemoteRegister = SRetReg;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007589 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(),
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00007590 SRetReg, ArgValue);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007591 DAG.setRoot(NewRoot);
Bill Wendling919b7aa2009-12-22 02:10:19 +00007592
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007593 // i indexes lowered arguments. Bump it past the hidden sret argument.
7594 // Idx indexes LLVM arguments. Don't touch it.
7595 ++i;
7596 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007597
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007598 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007599 ++I, ++Idx) {
7600 SmallVector<SDValue, 4> ArgValues;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007601 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007602 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00007603 unsigned NumValues = ValueVTs.size();
Devang Patelb0c76392010-06-01 19:59:01 +00007604
7605 // If this argument is unused then remember its value. It is used to generate
7606 // debugging information.
Adrian Prantl9c930592013-05-16 23:44:12 +00007607 if (I->use_empty() && NumValues) {
Devang Patelb0c76392010-06-01 19:59:01 +00007608 SDB->setUnusedArgValue(I, InVals[i]);
7609
Adrian Prantl9c930592013-05-16 23:44:12 +00007610 // Also remember any frame index for use in FastISel.
7611 if (FrameIndexSDNode *FI =
7612 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7613 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7614 }
7615
Eli Friedman441a01a2011-05-05 16:53:34 +00007616 for (unsigned Val = 0; Val != NumValues; ++Val) {
7617 EVT VT = ValueVTs[Val];
Bill Wendlingf7719082013-06-06 00:43:09 +00007618 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7619 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007620
7621 if (!I->use_empty()) {
7622 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling94dcaf82012-12-30 12:45:13 +00007623 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007624 AssertOp = ISD::AssertSext;
Bill Wendling94dcaf82012-12-30 12:45:13 +00007625 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007626 AssertOp = ISD::AssertZext;
7627
Bill Wendling78c5b7a2010-03-02 01:55:18 +00007628 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
Bill Wendling919b7aa2009-12-22 02:10:19 +00007629 NumParts, PartVT, VT,
Craig Topperc0196b12014-04-14 00:51:57 +00007630 nullptr, AssertOp));
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007631 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007632
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007633 i += NumParts;
7634 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007635
Eli Friedman441a01a2011-05-05 16:53:34 +00007636 // We don't need to do anything else for unused arguments.
7637 if (ArgValues.empty())
7638 continue;
7639
Devang Patel9d904e12011-09-08 22:59:09 +00007640 // Note down frame index.
7641 if (FrameIndexSDNode *FI =
Bill Wendlingd1634052012-07-19 00:04:14 +00007642 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
Devang Patel9d904e12011-09-08 22:59:09 +00007643 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
Devang Patel86ec8b32010-08-31 22:22:42 +00007644
Craig Topper2d2aa0c2014-04-30 07:17:30 +00007645 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007646 SDB->getCurSDLoc());
Devang Patel9d904e12011-09-08 22:59:09 +00007647
Eli Friedman441a01a2011-05-05 16:53:34 +00007648 SDB->setValue(I, Res);
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007649 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007650 if (LoadSDNode *LNode =
Devang Patel9d904e12011-09-08 22:59:09 +00007651 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7652 if (FrameIndexSDNode *FI =
7653 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7654 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7655 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007656
Eli Friedman441a01a2011-05-05 16:53:34 +00007657 // If this argument is live outside of the entry block, insert a copy from
7658 // wherever we got it to the vreg that other BB's will reference it as.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007659 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007660 // If we can, though, try to skip creating an unnecessary vreg.
7661 // FIXME: This isn't very clean... it would be nice to make this more
Eli Friedman768de0a2011-05-10 21:50:58 +00007662 // general. It's also subtly incompatible with the hacks FastISel
7663 // uses with vregs.
Eli Friedman441a01a2011-05-05 16:53:34 +00007664 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7665 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7666 FuncInfo->ValueMap[I] = Reg;
7667 continue;
7668 }
7669 }
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007670 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007671 FuncInfo->InitializeRegForValue(I);
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007672 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohman575fad32008-09-03 16:12:24 +00007673 }
Dan Gohman575fad32008-09-03 16:12:24 +00007674 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007675
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007676 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohman575fad32008-09-03 16:12:24 +00007677
7678 // Finally, if the target has anything special to do, allow it to do so.
7679 // FIXME: this should insert code into the DAG!
Dan Gohmanc87b74d2010-04-14 20:17:22 +00007680 EmitFunctionEntryCode();
Dan Gohman575fad32008-09-03 16:12:24 +00007681}
7682
7683/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7684/// ensure constants are generated when needed. Remember the virtual registers
7685/// that need to be added to the Machine PHI nodes as input. We cannot just
7686/// directly add them, because expansion might result in multiple MBB's for one
7687/// BB. As such, the start of the BB might correspond to a different MBB than
7688/// the end.
7689///
7690void
Dan Gohmanc594eab2010-04-22 20:46:50 +00007691SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007692 const TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohman575fad32008-09-03 16:12:24 +00007693
7694 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7695
7696 // Check successor nodes' PHI nodes that expect a constant to be available
7697 // from this block.
7698 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007699 const BasicBlock *SuccBB = TI->getSuccessor(succ);
Dan Gohman575fad32008-09-03 16:12:24 +00007700 if (!isa<PHINode>(SuccBB->begin())) continue;
Dan Gohmanc594eab2010-04-22 20:46:50 +00007701 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007702
Dan Gohman575fad32008-09-03 16:12:24 +00007703 // If this terminator has multiple identical successors (common for
7704 // switches), only handle each succ once.
7705 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007706
Dan Gohman575fad32008-09-03 16:12:24 +00007707 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Dan Gohman575fad32008-09-03 16:12:24 +00007708
7709 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7710 // nodes and Machine PHI nodes, but the incoming operands have not been
7711 // emitted yet.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007712 for (BasicBlock::const_iterator I = SuccBB->begin();
7713 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohman575fad32008-09-03 16:12:24 +00007714 // Ignore dead phi's.
7715 if (PN->use_empty()) continue;
7716
Rafael Espindolae53b7d12011-05-13 15:18:06 +00007717 // Skip empty types
7718 if (PN->getType()->isEmptyTy())
7719 continue;
7720
Dan Gohman575fad32008-09-03 16:12:24 +00007721 unsigned Reg;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007722 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00007723
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007724 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohmanc594eab2010-04-22 20:46:50 +00007725 unsigned &RegOut = ConstantsOut[C];
Dan Gohman575fad32008-09-03 16:12:24 +00007726 if (RegOut == 0) {
Dan Gohman93f59202010-07-02 00:10:16 +00007727 RegOut = FuncInfo.CreateRegs(C->getType());
Dan Gohmanc594eab2010-04-22 20:46:50 +00007728 CopyValueToVirtualRegister(C, RegOut);
Dan Gohman575fad32008-09-03 16:12:24 +00007729 }
7730 Reg = RegOut;
7731 } else {
Dan Gohman9576645a2010-07-01 01:33:21 +00007732 DenseMap<const Value *, unsigned>::iterator I =
7733 FuncInfo.ValueMap.find(PHIOp);
7734 if (I != FuncInfo.ValueMap.end())
7735 Reg = I->second;
7736 else {
Dan Gohman575fad32008-09-03 16:12:24 +00007737 assert(isa<AllocaInst>(PHIOp) &&
Dan Gohmanc594eab2010-04-22 20:46:50 +00007738 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
Dan Gohman575fad32008-09-03 16:12:24 +00007739 "Didn't codegen value into a register!??");
Dan Gohman93f59202010-07-02 00:10:16 +00007740 Reg = FuncInfo.CreateRegs(PHIOp->getType());
Dan Gohmanc594eab2010-04-22 20:46:50 +00007741 CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohman575fad32008-09-03 16:12:24 +00007742 }
7743 }
7744
7745 // Remember that this register needs to added to the machine PHI node as
7746 // the input for this MBB.
Owen Anderson53aa7a92009-08-10 22:56:29 +00007747 SmallVector<EVT, 4> ValueVTs;
Eric Christopherd9134482014-08-04 21:25:23 +00007748 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007749 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00007750 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007751 EVT VT = ValueVTs[vti];
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007752 unsigned NumRegisters = TLI->getNumRegisters(*DAG.getContext(), VT);
Dan Gohman575fad32008-09-03 16:12:24 +00007753 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohmanc594eab2010-04-22 20:46:50 +00007754 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohman575fad32008-09-03 16:12:24 +00007755 Reg += NumRegisters;
7756 }
7757 }
7758 }
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007759
Dan Gohmanc594eab2010-04-22 20:46:50 +00007760 ConstantsOut.clear();
Dan Gohman7bda51f2008-09-03 23:12:08 +00007761}
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00007762
7763/// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7764/// is 0.
7765MachineBasicBlock *
7766SelectionDAGBuilder::StackProtectorDescriptor::
7767AddSuccessorMBB(const BasicBlock *BB,
7768 MachineBasicBlock *ParentMBB,
7769 MachineBasicBlock *SuccMBB) {
7770 // If SuccBB has not been created yet, create it.
7771 if (!SuccMBB) {
7772 MachineFunction *MF = ParentMBB->getParent();
7773 MachineFunction::iterator BBI = ParentMBB;
7774 SuccMBB = MF->CreateMachineBasicBlock(BB);
7775 MF->insert(++BBI, SuccMBB);
7776 }
7777 // Add it as a successor of ParentMBB.
7778 ParentMBB->addSuccessor(SuccMBB);
7779 return SuccMBB;
7780}