blob: 6a626b90e3e9ffac310caf0410a164418958348a [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Evan Cheng381cb072008-08-08 07:27:28 +000015#include "llvm/CodeGen/SelectionDAGISel.h"
16#include "SimpleBBISel.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000017#include "llvm/ADT/BitVector.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000018#include "llvm/Analysis/AliasAnalysis.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer5694b6e2007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Dan Gohman78eca172008-08-19 22:33:34 +000029#include "llvm/CodeGen/FastISel.h"
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000030#include "llvm/CodeGen/GCStrategy.h"
Gordon Henriksen5eca0752008-08-17 18:44:35 +000031#include "llvm/CodeGen/GCMetadata.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineFrameInfo.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000035#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Cheng381cb072008-08-08 07:27:28 +000038#include "llvm/CodeGen/ScheduleDAG.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000039#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000040#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000041#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Target/TargetFrameInfo.h"
44#include "llvm/Target/TargetInstrInfo.h"
45#include "llvm/Target/TargetLowering.h"
46#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000047#include "llvm/Target/TargetOptions.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000048#include "llvm/Support/Compiler.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/MathExtras.h"
51#include "llvm/Support/Timer.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000052#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000053using namespace llvm;
54
Chris Lattneread0d882008-06-17 06:09:18 +000055static cl::opt<bool>
Chris Lattner70587ea2008-07-10 23:37:50 +000056EnableValueProp("enable-value-prop", cl::Hidden);
57static cl::opt<bool>
Duncan Sandsf00e74f2008-07-17 17:06:03 +000058EnableLegalizeTypes("enable-legalize-types", cl::Hidden);
Dan Gohman78eca172008-08-19 22:33:34 +000059static cl::opt<bool>
60EnableFastISel("fast-isel", cl::Hidden,
61 cl::desc("Enable the experimental \"fast\" instruction selector"));
Dan Gohman3e697cf2008-08-20 00:47:54 +000062static cl::opt<bool>
63DisableFastISelAbort("fast-isel-no-abort", cl::Hidden,
64 cl::desc("Use the SelectionDAGISel when \"fast\" instruction "
65 "selection fails"));
Chris Lattneread0d882008-06-17 06:09:18 +000066
Chris Lattnerda8abb02005-09-01 18:44:10 +000067#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000068static cl::opt<bool>
Dan Gohman462dc7f2008-07-21 20:00:07 +000069ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
70 cl::desc("Pop up a window to show dags before the first "
71 "dag combine pass"));
72static cl::opt<bool>
73ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
74 cl::desc("Pop up a window to show dags before legalize types"));
75static cl::opt<bool>
76ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
77 cl::desc("Pop up a window to show dags before legalize"));
78static cl::opt<bool>
79ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
80 cl::desc("Pop up a window to show dags before the second "
81 "dag combine pass"));
82static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000083ViewISelDAGs("view-isel-dags", cl::Hidden,
84 cl::desc("Pop up a window to show isel dags as they are selected"));
85static cl::opt<bool>
86ViewSchedDAGs("view-sched-dags", cl::Hidden,
87 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000088static cl::opt<bool>
89ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000090 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000091#else
Dan Gohman462dc7f2008-07-21 20:00:07 +000092static const bool ViewDAGCombine1 = false,
93 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
94 ViewDAGCombine2 = false,
95 ViewISelDAGs = false, ViewSchedDAGs = false,
96 ViewSUnitDAGs = false;
Chris Lattner7944d9d2005-01-12 03:41:21 +000097#endif
98
Jim Laskeyeb577ba2006-08-02 12:30:23 +000099//===---------------------------------------------------------------------===//
100///
101/// RegisterScheduler class - Track the registration of instruction schedulers.
102///
103//===---------------------------------------------------------------------===//
104MachinePassRegistry RegisterScheduler::Registry;
105
106//===---------------------------------------------------------------------===//
107///
108/// ISHeuristic command line option for instruction schedulers.
109///
110//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +0000111static cl::opt<RegisterScheduler::FunctionPassCtor, false,
112 RegisterPassParser<RegisterScheduler> >
113ISHeuristic("pre-RA-sched",
114 cl::init(&createDefaultScheduler),
115 cl::desc("Instruction schedulers available (before register"
116 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +0000117
Dan Gohman844731a2008-05-13 00:00:25 +0000118static RegisterScheduler
119defaultListDAGScheduler("default", " Best scheduler for the target",
120 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +0000121
Evan Cheng5c807602008-02-26 02:33:44 +0000122namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +0000123
Dan Gohman1d685a42008-06-07 02:02:36 +0000124/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
125/// insertvalue or extractvalue indices that identify a member, return
126/// the linearized index of the start of the member.
127///
128static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
129 const unsigned *Indices,
130 const unsigned *IndicesEnd,
131 unsigned CurIndex = 0) {
132 // Base case: We're done.
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000133 if (Indices && Indices == IndicesEnd)
Dan Gohman1d685a42008-06-07 02:02:36 +0000134 return CurIndex;
135
Chris Lattnerf899fce2008-04-27 23:48:12 +0000136 // Given a struct type, recursively traverse the elements.
137 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000138 for (StructType::element_iterator EB = STy->element_begin(),
139 EI = EB,
Dan Gohman1d685a42008-06-07 02:02:36 +0000140 EE = STy->element_end();
141 EI != EE; ++EI) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000142 if (Indices && *Indices == unsigned(EI - EB))
143 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
144 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +0000145 }
146 }
147 // Given an array type, recursively traverse the elements.
148 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
149 const Type *EltTy = ATy->getElementType();
150 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000151 if (Indices && *Indices == i)
152 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
153 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +0000154 }
155 }
156 // We haven't found the type we're looking for, so keep searching.
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000157 return CurIndex + 1;
Dan Gohman1d685a42008-06-07 02:02:36 +0000158}
159
160/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
161/// MVTs that represent all the individual underlying
162/// non-aggregate types that comprise it.
163///
164/// If Offsets is non-null, it points to a vector to be filled in
165/// with the in-memory offsets of each of the individual values.
166///
167static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
168 SmallVectorImpl<MVT> &ValueVTs,
169 SmallVectorImpl<uint64_t> *Offsets = 0,
170 uint64_t StartingOffset = 0) {
171 // Given a struct type, recursively traverse the elements.
172 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
173 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
174 for (StructType::element_iterator EB = STy->element_begin(),
175 EI = EB,
176 EE = STy->element_end();
177 EI != EE; ++EI)
178 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
179 StartingOffset + SL->getElementOffset(EI - EB));
Chris Lattnerf899fce2008-04-27 23:48:12 +0000180 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000181 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000182 // Given an array type, recursively traverse the elements.
183 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
184 const Type *EltTy = ATy->getElementType();
Dan Gohman1d685a42008-06-07 02:02:36 +0000185 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000186 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
Dan Gohman1d685a42008-06-07 02:02:36 +0000187 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
188 StartingOffset + i * EltSize);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000189 return;
190 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000191 // Base case: we can get an MVT for this LLVM IR type.
Chris Lattnerf899fce2008-04-27 23:48:12 +0000192 ValueVTs.push_back(TLI.getValueType(Ty));
Dan Gohman1d685a42008-06-07 02:02:36 +0000193 if (Offsets)
194 Offsets->push_back(StartingOffset);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000195}
Dan Gohman23ce5022008-04-25 18:27:55 +0000196
Chris Lattnerf899fce2008-04-27 23:48:12 +0000197namespace {
Dan Gohman0fe00902008-04-28 18:10:39 +0000198 /// RegsForValue - This struct represents the registers (physical or virtual)
199 /// that a particular set of values is assigned, and the type information about
200 /// the value. The most common situation is to represent one value at a time,
201 /// but struct or array values are handled element-wise as multiple values.
202 /// The splitting of aggregates is performed recursively, so that we never
203 /// have aggregate-typed registers. The values at this point do not necessarily
204 /// have legal types, so each value may require one or more registers of some
205 /// legal type.
206 ///
Chris Lattner95255282006-06-28 23:17:24 +0000207 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000208 /// TLI - The TargetLowering object.
Dan Gohman0fe00902008-04-28 18:10:39 +0000209 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000210 const TargetLowering *TLI;
211
Dan Gohman0fe00902008-04-28 18:10:39 +0000212 /// ValueVTs - The value types of the values, which may not be legal, and
213 /// may need be promoted or synthesized from one or more registers.
214 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000215 SmallVector<MVT, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000216
Dan Gohman0fe00902008-04-28 18:10:39 +0000217 /// RegVTs - The value types of the registers. This is the same size as
218 /// ValueVTs and it records, for each value, what the type of the assigned
219 /// register or registers are. (Individual values are never synthesized
220 /// from more than one type of register.)
221 ///
222 /// With virtual registers, the contents of RegVTs is redundant with TLI's
223 /// getRegisterType member function, however when with physical registers
224 /// it is necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000225 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000226 SmallVector<MVT, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000227
Dan Gohman0fe00902008-04-28 18:10:39 +0000228 /// Regs - This list holds the registers assigned to the values.
229 /// Each legal or promoted value requires one register, and each
230 /// expanded value requires multiple registers.
231 ///
232 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000233
Dan Gohman23ce5022008-04-25 18:27:55 +0000234 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000235
Dan Gohman23ce5022008-04-25 18:27:55 +0000236 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000237 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000238 MVT regvt, MVT valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000239 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000240 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000241 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000242 const SmallVector<MVT, 4> &regvts,
243 const SmallVector<MVT, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000244 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000245 RegsForValue(const TargetLowering &tli,
246 unsigned Reg, const Type *Ty) : TLI(&tli) {
247 ComputeValueVTs(tli, Ty, ValueVTs);
248
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000249 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000250 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000251 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000252 MVT RegisterVT = TLI->getRegisterType(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000253 for (unsigned i = 0; i != NumRegs; ++i)
254 Regs.push_back(Reg + i);
255 RegVTs.push_back(RegisterVT);
256 Reg += NumRegs;
257 }
Chris Lattner864635a2006-02-22 22:37:12 +0000258 }
259
Chris Lattner41f62592008-04-29 04:29:54 +0000260 /// append - Add the specified values to this one.
261 void append(const RegsForValue &RHS) {
262 TLI = RHS.TLI;
263 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
264 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
265 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
266 }
267
268
Chris Lattner864635a2006-02-22 22:37:12 +0000269 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000270 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000271 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000272 /// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +0000273 SDValue getCopyFromRegs(SelectionDAG &DAG,
274 SDValue &Chain, SDValue *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000275
276 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
277 /// specified value into the registers specified by this object. This uses
278 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000279 /// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +0000280 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
281 SDValue &Chain, SDValue *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000282
283 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
284 /// operand list. This adds the code marker and includes the number of
285 /// values added into it.
286 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +0000287 std::vector<SDValue> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000288 };
289}
Evan Cheng4ef10862006-01-23 07:01:07 +0000290
Chris Lattner1c08c712005-01-07 07:47:53 +0000291namespace llvm {
292 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000293 /// createDefaultScheduler - This creates an instruction scheduler appropriate
294 /// for the target.
295 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
296 SelectionDAG *DAG,
Evan Cheng4576f6d2008-07-01 18:05:03 +0000297 MachineBasicBlock *BB,
298 bool Fast) {
Jim Laskey9373beb2006-08-01 19:14:14 +0000299 TargetLowering &TLI = IS->getTargetLowering();
300
301 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
Evan Cheng4576f6d2008-07-01 18:05:03 +0000302 return createTDListDAGScheduler(IS, DAG, BB, Fast);
Jim Laskey9373beb2006-08-01 19:14:14 +0000303 } else {
304 assert(TLI.getSchedulingPreference() ==
305 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
Evan Cheng4576f6d2008-07-01 18:05:03 +0000306 return createBURRListDAGScheduler(IS, DAG, BB, Fast);
Jim Laskey9373beb2006-08-01 19:14:14 +0000307 }
308 }
309
310
311 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000312 /// FunctionLoweringInfo - This contains information that is global to a
313 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000314 class FunctionLoweringInfo {
315 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000316 TargetLowering &TLI;
317 Function &Fn;
318 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000319 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000320
321 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
322
323 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
324 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
325
326 /// ValueMap - Since we emit code for the function a basic block at a time,
327 /// we must remember which virtual registers hold the values for
328 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000329 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000330
331 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
332 /// the entry block. This allows the allocas to be efficiently referenced
333 /// anywhere in the function.
334 std::map<const AllocaInst*, int> StaticAllocaMap;
335
Duncan Sandsf4070822007-06-15 19:04:19 +0000336#ifndef NDEBUG
337 SmallSet<Instruction*, 8> CatchInfoLost;
338 SmallSet<Instruction*, 8> CatchInfoFound;
339#endif
340
Duncan Sands83ec4b62008-06-06 12:08:01 +0000341 unsigned MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000342 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000343 }
Chris Lattner571e4342006-10-27 21:36:01 +0000344
345 /// isExportedInst - Return true if the specified value is an instruction
346 /// exported from its block.
347 bool isExportedInst(const Value *V) {
348 return ValueMap.count(V);
349 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000350
Chris Lattner3c384492006-03-16 19:51:18 +0000351 unsigned CreateRegForValue(const Value *V);
352
Chris Lattner1c08c712005-01-07 07:47:53 +0000353 unsigned InitializeRegForValue(const Value *V) {
354 unsigned &R = ValueMap[V];
355 assert(R == 0 && "Already initialized this value register!");
356 return R = CreateRegForValue(V);
357 }
Chris Lattneread0d882008-06-17 06:09:18 +0000358
359 struct LiveOutInfo {
360 unsigned NumSignBits;
361 APInt KnownOne, KnownZero;
362 LiveOutInfo() : NumSignBits(0) {}
363 };
364
365 /// LiveOutRegInfo - Information about live out vregs, indexed by their
366 /// register number offset by 'FirstVirtualRegister'.
367 std::vector<LiveOutInfo> LiveOutRegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000368 };
369}
370
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000371/// isSelector - Return true if this instruction is a call to the
372/// eh.selector intrinsic.
373static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000374 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000375 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
376 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000377 return false;
378}
379
Chris Lattner1c08c712005-01-07 07:47:53 +0000380/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000381/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000382/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000383static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
384 if (isa<PHINode>(I)) return true;
385 BasicBlock *BB = I->getParent();
386 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000387 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000388 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000389 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000390 return true;
391 return false;
392}
393
Chris Lattnerbf209482005-10-30 19:42:35 +0000394/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000395/// entry block, return true. This includes arguments used by switches, since
396/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000397static bool isOnlyUsedInEntryBlock(Argument *A) {
398 BasicBlock *Entry = A->getParent()->begin();
399 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000400 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000401 return false; // Use not in entry block.
402 return true;
403}
404
Chris Lattner1c08c712005-01-07 07:47:53 +0000405FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000406 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000407 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000408
Chris Lattnerbf209482005-10-30 19:42:35 +0000409 // Create a vreg for each argument register that is not dead and is used
410 // outside of the entry block for the function.
411 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
412 AI != E; ++AI)
413 if (!isOnlyUsedInEntryBlock(AI))
414 InitializeRegForValue(AI);
415
Chris Lattner1c08c712005-01-07 07:47:53 +0000416 // Initialize the mapping of values to registers. This is only set up for
417 // instruction values that are used outside of the block that defines
418 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000419 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000420 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
421 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000422 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000423 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000424 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000425 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000426 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000427 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000428
Reid Spencerb83eb642006-10-20 07:07:24 +0000429 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000430 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000431 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000432 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000433 }
434
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000435 for (; BB != EB; ++BB)
436 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000437 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
438 if (!isa<AllocaInst>(I) ||
439 !StaticAllocaMap.count(cast<AllocaInst>(I)))
440 InitializeRegForValue(I);
441
442 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
443 // also creates the initial PHI MachineInstrs, though none of the input
444 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000445 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Dan Gohman0e5f1302008-07-07 23:02:41 +0000446 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000447 MBBMap[BB] = MBB;
Dan Gohman0e5f1302008-07-07 23:02:41 +0000448 MF.push_back(MBB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000449
450 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
451 // appropriate.
452 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000453 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
454 if (PN->use_empty()) continue;
455
Chris Lattner8c494ab2006-10-27 23:50:33 +0000456 unsigned PHIReg = ValueMap[PN];
457 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Dan Gohman6f498b02008-08-04 23:42:46 +0000458
459 SmallVector<MVT, 4> ValueVTs;
460 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
461 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
462 MVT VT = ValueVTs[vti];
463 unsigned NumRegisters = TLI.getNumRegisters(VT);
464 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
465 for (unsigned i = 0; i != NumRegisters; ++i)
466 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
467 PHIReg += NumRegisters;
468 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000469 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000470 }
471}
472
Chris Lattner3c384492006-03-16 19:51:18 +0000473/// CreateRegForValue - Allocate the appropriate number of virtual registers of
474/// the correctly promoted or expanded types. Assign these registers
475/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000476///
477/// In the case that the given value has struct or array type, this function
478/// will assign registers for each member or element.
479///
Chris Lattner3c384492006-03-16 19:51:18 +0000480unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000481 SmallVector<MVT, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000482 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000483
Dan Gohman23ce5022008-04-25 18:27:55 +0000484 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000485 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000486 MVT ValueVT = ValueVTs[Value];
487 MVT RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000488
Chris Lattnerb606dba2008-04-28 06:44:42 +0000489 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000490 for (unsigned i = 0; i != NumRegs; ++i) {
491 unsigned R = MakeReg(RegisterVT);
492 if (!FirstReg) FirstReg = R;
493 }
494 }
495 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000496}
Chris Lattner1c08c712005-01-07 07:47:53 +0000497
498//===----------------------------------------------------------------------===//
499/// SelectionDAGLowering - This is the common target-independent lowering
500/// implementation that is parameterized by a TargetLowering object.
501/// Also, targets can overload any lowering method.
502///
503namespace llvm {
504class SelectionDAGLowering {
505 MachineBasicBlock *CurMBB;
506
Dan Gohman475871a2008-07-27 21:46:04 +0000507 DenseMap<const Value*, SDValue> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000508
Chris Lattnerd3948112005-01-17 22:19:26 +0000509 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
510 /// them up and then emit token factor nodes when possible. This allows us to
511 /// get simple disambiguation between loads without worrying about alias
512 /// analysis.
Dan Gohman475871a2008-07-27 21:46:04 +0000513 SmallVector<SDValue, 8> PendingLoads;
Chris Lattnerd3948112005-01-17 22:19:26 +0000514
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000515 /// PendingExports - CopyToReg nodes that copy values to virtual registers
516 /// for export to other blocks need to be emitted before any terminator
517 /// instruction, but they have no other ordering requirements. We bunch them
518 /// up and the emit a single tokenfactor for them just before terminator
519 /// instructions.
Dan Gohman475871a2008-07-27 21:46:04 +0000520 std::vector<SDValue> PendingExports;
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000521
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000522 /// Case - A struct to record the Value for a switch case, and the
523 /// case's target basic block.
524 struct Case {
525 Constant* Low;
526 Constant* High;
527 MachineBasicBlock* BB;
528
529 Case() : Low(0), High(0), BB(0) { }
530 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
531 Low(low), High(high), BB(bb) { }
532 uint64_t size() const {
533 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
534 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
535 return (rHigh - rLow + 1ULL);
536 }
537 };
538
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000539 struct CaseBits {
540 uint64_t Mask;
541 MachineBasicBlock* BB;
542 unsigned Bits;
543
544 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
545 Mask(mask), BB(bb), Bits(bits) { }
546 };
547
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000548 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000549 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000550 typedef CaseVector::iterator CaseItr;
551 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000552
553 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
554 /// of conditional branches.
555 struct CaseRec {
556 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
557 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
558
559 /// CaseBB - The MBB in which to emit the compare and branch
560 MachineBasicBlock *CaseBB;
561 /// LT, GE - If nonzero, we know the current case value must be less-than or
562 /// greater-than-or-equal-to these Constants.
563 Constant *LT;
564 Constant *GE;
565 /// Range - A pair of iterators representing the range of case values to be
566 /// processed at this point in the binary search tree.
567 CaseRange Range;
568 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000569
570 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000571
572 /// The comparison function for sorting the switch case values in the vector.
573 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000574 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000575 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000576 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
577 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
578 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
579 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000580 }
581 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000582
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000583 struct CaseBitsCmp {
584 bool operator () (const CaseBits& C1, const CaseBits& C2) {
585 return C1.Bits > C2.Bits;
586 }
587 };
588
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000589 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000590
Chris Lattner1c08c712005-01-07 07:47:53 +0000591public:
592 // TLI - This is information that describes the available target features we
593 // need for lowering. This indicates when operations are unavailable,
594 // implemented with a libcall, etc.
595 TargetLowering &TLI;
596 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000597 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000598 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000599
Nate Begemanf15485a2006-03-27 01:32:24 +0000600 /// SwitchCases - Vector of CaseBlock structures used to communicate
601 /// SwitchInst code generation information.
602 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000603 /// JTCases - Vector of JumpTable structures used to communicate
604 /// SwitchInst code generation information.
605 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000606 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000607
Chris Lattner1c08c712005-01-07 07:47:53 +0000608 /// FuncInfo - Information about the function as a whole.
609 ///
610 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000611
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000612 /// GFI - Garbage collection metadata for the function.
613 GCFunctionInfo *GFI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000614
615 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000616 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000617 FunctionLoweringInfo &funcinfo,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000618 GCFunctionInfo *gfi)
Dan Gohman5f43f922007-08-27 16:26:13 +0000619 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000620 FuncInfo(funcinfo), GFI(gfi) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000621 }
622
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000623 /// getRoot - Return the current virtual root of the Selection DAG,
624 /// flushing any PendingLoad items. This must be done before emitting
625 /// a store or any other node that may need to be ordered after any
626 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000627 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000628 SDValue getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000629 if (PendingLoads.empty())
630 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000631
Chris Lattnerd3948112005-01-17 22:19:26 +0000632 if (PendingLoads.size() == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +0000633 SDValue Root = PendingLoads[0];
Chris Lattnerd3948112005-01-17 22:19:26 +0000634 DAG.setRoot(Root);
635 PendingLoads.clear();
636 return Root;
637 }
638
639 // Otherwise, we have to make a token factor node.
Dan Gohman475871a2008-07-27 21:46:04 +0000640 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000641 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000642 PendingLoads.clear();
643 DAG.setRoot(Root);
644 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000645 }
646
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000647 /// getControlRoot - Similar to getRoot, but instead of flushing all the
648 /// PendingLoad items, flush all the PendingExports items. It is necessary
649 /// to do this before emitting a terminator instruction.
650 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000651 SDValue getControlRoot() {
652 SDValue Root = DAG.getRoot();
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000653
654 if (PendingExports.empty())
655 return Root;
656
657 // Turn all of the CopyToReg chains into one factored node.
658 if (Root.getOpcode() != ISD::EntryToken) {
659 unsigned i = 0, e = PendingExports.size();
660 for (; i != e; ++i) {
661 assert(PendingExports[i].Val->getNumOperands() > 1);
662 if (PendingExports[i].Val->getOperand(0) == Root)
663 break; // Don't add the root if we already indirectly depend on it.
664 }
665
666 if (i == e)
667 PendingExports.push_back(Root);
668 }
669
670 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
671 &PendingExports[0],
672 PendingExports.size());
673 PendingExports.clear();
674 DAG.setRoot(Root);
675 return Root;
676 }
677
678 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000679
Chris Lattner1c08c712005-01-07 07:47:53 +0000680 void visit(Instruction &I) { visit(I.getOpcode(), I); }
681
682 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000683 // Note: this doesn't use InstVisitor, because it has to work with
684 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000685 switch (Opcode) {
686 default: assert(0 && "Unknown instruction type encountered!");
687 abort();
688 // Build the switch statement using the Instruction.def file.
689#define HANDLE_INST(NUM, OPCODE, CLASS) \
690 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
691#include "llvm/Instruction.def"
692 }
693 }
694
695 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
696
Dan Gohman475871a2008-07-27 21:46:04 +0000697 SDValue getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000698
Dan Gohman475871a2008-07-27 21:46:04 +0000699 void setValue(const Value *V, SDValue NewN) {
700 SDValue &N = NodeMap[V];
Chris Lattner1c08c712005-01-07 07:47:53 +0000701 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000702 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000703 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000704
Evan Cheng5c807602008-02-26 02:33:44 +0000705 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000706 std::set<unsigned> &OutputRegs,
707 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000708
Chris Lattner571e4342006-10-27 21:36:01 +0000709 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
710 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
711 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000712 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000713 void ExportFromCurrentBlock(Value *V);
Dan Gohman475871a2008-07-27 21:46:04 +0000714 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000715 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000716
Chris Lattner1c08c712005-01-07 07:47:53 +0000717 // Terminator instructions.
718 void visitRet(ReturnInst &I);
719 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000720 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000721 void visitUnreachable(UnreachableInst &I) { /* noop */ }
722
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000723 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000724 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000725 CaseRecVector& WorkList,
726 Value* SV,
727 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000728 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000729 CaseRecVector& WorkList,
730 Value* SV,
731 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000732 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000733 CaseRecVector& WorkList,
734 Value* SV,
735 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000736 bool handleBitTestsSwitchCase(CaseRec& CR,
737 CaseRecVector& WorkList,
738 Value* SV,
739 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000740 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000741 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
742 void visitBitTestCase(MachineBasicBlock* NextMBB,
743 unsigned Reg,
744 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000745 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000746 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
747 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000748
Chris Lattner1c08c712005-01-07 07:47:53 +0000749 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000750 void visitInvoke(InvokeInst &I);
751 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000752
Dan Gohman7f321562007-06-25 16:23:39 +0000753 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000754 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000755 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000756 if (I.getType()->isFPOrFPVector())
757 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000758 else
Dan Gohman7f321562007-06-25 16:23:39 +0000759 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000760 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000761 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000762 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000763 if (I.getType()->isFPOrFPVector())
764 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000765 else
Dan Gohman7f321562007-06-25 16:23:39 +0000766 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000767 }
Dan Gohman7f321562007-06-25 16:23:39 +0000768 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
769 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
770 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
771 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
772 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
773 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
774 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
775 void visitOr (User &I) { visitBinary(I, ISD::OR); }
776 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000777 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000778 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
779 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000780 void visitICmp(User &I);
781 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000782 void visitVICmp(User &I);
783 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000784 // Visit the conversion instructions
785 void visitTrunc(User &I);
786 void visitZExt(User &I);
787 void visitSExt(User &I);
788 void visitFPTrunc(User &I);
789 void visitFPExt(User &I);
790 void visitFPToUI(User &I);
791 void visitFPToSI(User &I);
792 void visitUIToFP(User &I);
793 void visitSIToFP(User &I);
794 void visitPtrToInt(User &I);
795 void visitIntToPtr(User &I);
796 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000797
Chris Lattner2bbd8102006-03-29 00:11:43 +0000798 void visitExtractElement(User &I);
799 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000800 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000801
Dan Gohman1d685a42008-06-07 02:02:36 +0000802 void visitExtractValue(ExtractValueInst &I);
803 void visitInsertValue(InsertValueInst &I);
Dan Gohman041e2eb2008-05-15 19:50:34 +0000804
Chris Lattner1c08c712005-01-07 07:47:53 +0000805 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000806 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000807
808 void visitMalloc(MallocInst &I);
809 void visitFree(FreeInst &I);
810 void visitAlloca(AllocaInst &I);
811 void visitLoad(LoadInst &I);
812 void visitStore(StoreInst &I);
813 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
814 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000815 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000816 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000817 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000818
Chris Lattner1c08c712005-01-07 07:47:53 +0000819 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000820 void visitVAArg(VAArgInst &I);
821 void visitVAEnd(CallInst &I);
822 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000823
Chris Lattner1c08c712005-01-07 07:47:53 +0000824 void visitUserOp1(Instruction &I) {
825 assert(0 && "UserOp1 should not exist at instruction selection time!");
826 abort();
827 }
828 void visitUserOp2(Instruction &I) {
829 assert(0 && "UserOp2 should not exist at instruction selection time!");
830 abort();
831 }
Mon P Wang63307c32008-05-05 19:05:59 +0000832
833private:
834 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
835
Chris Lattner1c08c712005-01-07 07:47:53 +0000836};
837} // end namespace llvm
838
Dan Gohman6183f782007-07-05 20:12:34 +0000839
Duncan Sandsb988bac2008-02-11 20:58:28 +0000840/// getCopyFromParts - Create a value that contains the specified legal parts
841/// combined into the value they represent. If the parts combine to a type
842/// larger then ValueVT then AssertOp can be used to specify whether the extra
843/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000844/// (ISD::AssertSext).
Dan Gohman475871a2008-07-27 21:46:04 +0000845static SDValue getCopyFromParts(SelectionDAG &DAG,
846 const SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +0000847 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000848 MVT PartVT,
849 MVT ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000850 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000851 assert(NumParts > 0 && "No parts to assemble!");
852 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman475871a2008-07-27 21:46:04 +0000853 SDValue Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000854
Duncan Sands014e04a2008-02-12 20:46:31 +0000855 if (NumParts > 1) {
856 // Assemble the value from multiple parts.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000857 if (!ValueVT.isVector()) {
858 unsigned PartBits = PartVT.getSizeInBits();
859 unsigned ValueBits = ValueVT.getSizeInBits();
Dan Gohman6183f782007-07-05 20:12:34 +0000860
Duncan Sands014e04a2008-02-12 20:46:31 +0000861 // Assemble the power of 2 part.
862 unsigned RoundParts = NumParts & (NumParts - 1) ?
863 1 << Log2_32(NumParts) : NumParts;
864 unsigned RoundBits = PartBits * RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000865 MVT RoundVT = RoundBits == ValueBits ?
866 ValueVT : MVT::getIntegerVT(RoundBits);
Dan Gohman475871a2008-07-27 21:46:04 +0000867 SDValue Lo, Hi;
Duncan Sands014e04a2008-02-12 20:46:31 +0000868
869 if (RoundParts > 2) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000870 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sands014e04a2008-02-12 20:46:31 +0000871 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
872 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
873 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000874 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000875 Lo = Parts[0];
876 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000877 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000878 if (TLI.isBigEndian())
879 std::swap(Lo, Hi);
880 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
881
882 if (RoundParts < NumParts) {
883 // Assemble the trailing non-power-of-2 part.
884 unsigned OddParts = NumParts - RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000885 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000886 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
887
888 // Combine the round and odd parts.
889 Lo = Val;
890 if (TLI.isBigEndian())
891 std::swap(Lo, Hi);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000892 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000893 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
894 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000895 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands014e04a2008-02-12 20:46:31 +0000896 TLI.getShiftAmountTy()));
897 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
898 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
899 }
900 } else {
901 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000902 MVT IntermediateVT, RegisterVT;
Duncan Sands014e04a2008-02-12 20:46:31 +0000903 unsigned NumIntermediates;
904 unsigned NumRegs =
905 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
906 RegisterVT);
Duncan Sands014e04a2008-02-12 20:46:31 +0000907 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +0000908 NumParts = NumRegs; // Silence a compiler warning.
Duncan Sands014e04a2008-02-12 20:46:31 +0000909 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
910 assert(RegisterVT == Parts[0].getValueType() &&
911 "Part type doesn't match part!");
912
913 // Assemble the parts into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +0000914 SmallVector<SDValue, 8> Ops(NumIntermediates);
Duncan Sands014e04a2008-02-12 20:46:31 +0000915 if (NumIntermediates == NumParts) {
916 // If the register was not expanded, truncate or copy the value,
917 // as appropriate.
918 for (unsigned i = 0; i != NumParts; ++i)
919 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
920 PartVT, IntermediateVT);
921 } else if (NumParts > 0) {
922 // If the intermediate type was expanded, build the intermediate operands
923 // from the parts.
924 assert(NumParts % NumIntermediates == 0 &&
925 "Must expand into a divisible number of parts!");
926 unsigned Factor = NumParts / NumIntermediates;
927 for (unsigned i = 0; i != NumIntermediates; ++i)
928 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
929 PartVT, IntermediateVT);
930 }
931
932 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
933 // operands.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000934 Val = DAG.getNode(IntermediateVT.isVector() ?
Duncan Sands014e04a2008-02-12 20:46:31 +0000935 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
936 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000937 }
Dan Gohman6183f782007-07-05 20:12:34 +0000938 }
939
Duncan Sands014e04a2008-02-12 20:46:31 +0000940 // There is now one part, held in Val. Correct it to match ValueVT.
941 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000942
Duncan Sands014e04a2008-02-12 20:46:31 +0000943 if (PartVT == ValueVT)
944 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000945
Duncan Sands83ec4b62008-06-06 12:08:01 +0000946 if (PartVT.isVector()) {
947 assert(ValueVT.isVector() && "Unknown vector conversion!");
Duncan Sands014e04a2008-02-12 20:46:31 +0000948 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000949 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000950
Duncan Sands83ec4b62008-06-06 12:08:01 +0000951 if (ValueVT.isVector()) {
952 assert(ValueVT.getVectorElementType() == PartVT &&
953 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000954 "Only trivial scalar-to-vector conversions should get here!");
955 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
956 }
957
Duncan Sands83ec4b62008-06-06 12:08:01 +0000958 if (PartVT.isInteger() &&
959 ValueVT.isInteger()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000960 if (ValueVT.bitsLT(PartVT)) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000961 // For a truncate, see if we have any information to
962 // indicate whether the truncated bits will always be
963 // zero or sign-extension.
964 if (AssertOp != ISD::DELETED_NODE)
965 Val = DAG.getNode(AssertOp, PartVT, Val,
966 DAG.getValueType(ValueVT));
967 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
968 } else {
969 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
970 }
971 }
972
Duncan Sands83ec4b62008-06-06 12:08:01 +0000973 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000974 if (ValueVT.bitsLT(Val.getValueType()))
Chris Lattner4468c1f2008-03-09 09:38:46 +0000975 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000976 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000977 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000978 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
979 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000980
Duncan Sands83ec4b62008-06-06 12:08:01 +0000981 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Duncan Sands014e04a2008-02-12 20:46:31 +0000982 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
983
984 assert(0 && "Unknown mismatch!");
Dan Gohman475871a2008-07-27 21:46:04 +0000985 return SDValue();
Dan Gohman6183f782007-07-05 20:12:34 +0000986}
987
Duncan Sandsb988bac2008-02-11 20:58:28 +0000988/// getCopyToParts - Create a series of nodes that contain the specified value
989/// split into legal parts. If the parts contain more bits than Val, then, for
990/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000991static void getCopyToParts(SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +0000992 SDValue Val,
993 SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +0000994 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000995 MVT PartVT,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000996 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000997 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000998 MVT PtrVT = TLI.getPointerTy();
999 MVT ValueVT = Val.getValueType();
1000 unsigned PartBits = PartVT.getSizeInBits();
Duncan Sands014e04a2008-02-12 20:46:31 +00001001 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +00001002
Duncan Sands014e04a2008-02-12 20:46:31 +00001003 if (!NumParts)
1004 return;
1005
Duncan Sands83ec4b62008-06-06 12:08:01 +00001006 if (!ValueVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001007 if (PartVT == ValueVT) {
1008 assert(NumParts == 1 && "No-op copy with multiple parts!");
1009 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +00001010 return;
1011 }
1012
Duncan Sands83ec4b62008-06-06 12:08:01 +00001013 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001014 // If the parts cover more bits than the value has, promote the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001015 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001016 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +00001017 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001018 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
1019 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001020 Val = DAG.getNode(ExtendKind, ValueVT, Val);
1021 } else {
1022 assert(0 && "Unknown mismatch!");
1023 }
Duncan Sands83ec4b62008-06-06 12:08:01 +00001024 } else if (PartBits == ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001025 // Different types of the same size.
1026 assert(NumParts == 1 && PartVT != ValueVT);
1027 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001028 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001029 // If the parts cover less bits than value has, truncate the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001030 if (PartVT.isInteger() && ValueVT.isInteger()) {
1031 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001032 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +00001033 } else {
1034 assert(0 && "Unknown mismatch!");
1035 }
1036 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001037
1038 // The value may have changed - recompute ValueVT.
1039 ValueVT = Val.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001040 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001041 "Failed to tile the value with PartVT!");
1042
1043 if (NumParts == 1) {
1044 assert(PartVT == ValueVT && "Type conversion failed!");
1045 Parts[0] = Val;
1046 return;
1047 }
1048
1049 // Expand the value into multiple parts.
1050 if (NumParts & (NumParts - 1)) {
1051 // The number of parts is not a power of 2. Split off and copy the tail.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001052 assert(PartVT.isInteger() && ValueVT.isInteger() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001053 "Do not know what to expand to!");
1054 unsigned RoundParts = 1 << Log2_32(NumParts);
1055 unsigned RoundBits = RoundParts * PartBits;
1056 unsigned OddParts = NumParts - RoundParts;
Dan Gohman475871a2008-07-27 21:46:04 +00001057 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
Duncan Sands014e04a2008-02-12 20:46:31 +00001058 DAG.getConstant(RoundBits,
1059 TLI.getShiftAmountTy()));
1060 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1061 if (TLI.isBigEndian())
1062 // The odd parts were reversed by getCopyToParts - unreverse them.
1063 std::reverse(Parts + RoundParts, Parts + NumParts);
1064 NumParts = RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001065 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001066 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1067 }
1068
1069 // The number of parts is a power of 2. Repeatedly bisect the value using
1070 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +00001071 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001072 MVT::getIntegerVT(ValueVT.getSizeInBits()),
Duncan Sands25eb0432008-03-12 20:30:08 +00001073 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +00001074 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1075 for (unsigned i = 0; i < NumParts; i += StepSize) {
1076 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001077 MVT ThisVT = MVT::getIntegerVT (ThisBits);
Dan Gohman475871a2008-07-27 21:46:04 +00001078 SDValue &Part0 = Parts[i];
1079 SDValue &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +00001080
Duncan Sands25eb0432008-03-12 20:30:08 +00001081 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1082 DAG.getConstant(1, PtrVT));
1083 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1084 DAG.getConstant(0, PtrVT));
1085
1086 if (ThisBits == PartBits && ThisVT != PartVT) {
1087 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1088 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1089 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001090 }
1091 }
1092
1093 if (TLI.isBigEndian())
1094 std::reverse(Parts, Parts + NumParts);
1095
1096 return;
1097 }
1098
1099 // Vector ValueVT.
1100 if (NumParts == 1) {
1101 if (PartVT != ValueVT) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001102 if (PartVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001103 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1104 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001105 assert(ValueVT.getVectorElementType() == PartVT &&
1106 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001107 "Only trivial vector-to-scalar conversions should get here!");
1108 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1109 DAG.getConstant(0, PtrVT));
1110 }
1111 }
1112
Dan Gohman6183f782007-07-05 20:12:34 +00001113 Parts[0] = Val;
1114 return;
1115 }
1116
1117 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001118 MVT IntermediateVT, RegisterVT;
Dan Gohman6183f782007-07-05 20:12:34 +00001119 unsigned NumIntermediates;
1120 unsigned NumRegs =
1121 DAG.getTargetLoweringInfo()
1122 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1123 RegisterVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001124 unsigned NumElements = ValueVT.getVectorNumElements();
Dan Gohman6183f782007-07-05 20:12:34 +00001125
1126 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001127 NumParts = NumRegs; // Silence a compiler warning.
Dan Gohman6183f782007-07-05 20:12:34 +00001128 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1129
1130 // Split the vector into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +00001131 SmallVector<SDValue, 8> Ops(NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +00001132 for (unsigned i = 0; i != NumIntermediates; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +00001133 if (IntermediateVT.isVector())
Dan Gohman6183f782007-07-05 20:12:34 +00001134 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1135 IntermediateVT, Val,
1136 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001137 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001138 else
1139 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1140 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001141 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001142
1143 // Split the intermediate operands into legal parts.
1144 if (NumParts == NumIntermediates) {
1145 // If the register was not expanded, promote or copy the value,
1146 // as appropriate.
1147 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001148 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001149 } else if (NumParts > 0) {
1150 // If the intermediate type was expanded, split each the value into
1151 // legal parts.
1152 assert(NumParts % NumIntermediates == 0 &&
1153 "Must expand into a divisible number of parts!");
1154 unsigned Factor = NumParts / NumIntermediates;
1155 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001156 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001157 }
1158}
1159
1160
Dan Gohman475871a2008-07-27 21:46:04 +00001161SDValue SelectionDAGLowering::getValue(const Value *V) {
1162 SDValue &N = NodeMap[V];
Chris Lattner199862b2006-03-16 19:57:50 +00001163 if (N.Val) return N;
1164
Chris Lattner199862b2006-03-16 19:57:50 +00001165 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001166 MVT VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001167
1168 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1169 return N = DAG.getConstant(CI->getValue(), VT);
1170
1171 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001172 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001173
1174 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001175 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001176
1177 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1178 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1179
Dan Gohman1d685a42008-06-07 02:02:36 +00001180 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1181 !V->getType()->isAggregateType())
Chris Lattner6833b062008-04-28 07:16:35 +00001182 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001183
1184 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1185 visit(CE->getOpcode(), *CE);
Dan Gohman475871a2008-07-27 21:46:04 +00001186 SDValue N1 = NodeMap[V];
Chris Lattnerb606dba2008-04-28 06:44:42 +00001187 assert(N1.Val && "visit didn't populate the ValueMap!");
1188 return N1;
1189 }
1190
Dan Gohman1d685a42008-06-07 02:02:36 +00001191 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
Dan Gohman475871a2008-07-27 21:46:04 +00001192 SmallVector<SDValue, 4> Constants;
Dan Gohman1d685a42008-06-07 02:02:36 +00001193 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1194 OI != OE; ++OI) {
1195 SDNode *Val = getValue(*OI).Val;
Duncan Sands4bdcb612008-07-02 17:40:58 +00001196 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
Dan Gohman475871a2008-07-27 21:46:04 +00001197 Constants.push_back(SDValue(Val, i));
Dan Gohman1d685a42008-06-07 02:02:36 +00001198 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00001199 return DAG.getMergeValues(&Constants[0], Constants.size());
Dan Gohman1d685a42008-06-07 02:02:36 +00001200 }
1201
Dan Gohman1f565bc2008-08-04 23:30:41 +00001202 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
Dan Gohman1d685a42008-06-07 02:02:36 +00001203 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
Dan Gohman1f565bc2008-08-04 23:30:41 +00001204 "Unknown struct or array constant!");
Dan Gohman1d685a42008-06-07 02:02:36 +00001205
Dan Gohman1f565bc2008-08-04 23:30:41 +00001206 SmallVector<MVT, 4> ValueVTs;
1207 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1208 unsigned NumElts = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00001209 if (NumElts == 0)
Dan Gohman475871a2008-07-27 21:46:04 +00001210 return SDValue(); // empty struct
1211 SmallVector<SDValue, 4> Constants(NumElts);
Dan Gohman1f565bc2008-08-04 23:30:41 +00001212 for (unsigned i = 0; i != NumElts; ++i) {
1213 MVT EltVT = ValueVTs[i];
Dan Gohman1d685a42008-06-07 02:02:36 +00001214 if (isa<UndefValue>(C))
1215 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1216 else if (EltVT.isFloatingPoint())
1217 Constants[i] = DAG.getConstantFP(0, EltVT);
1218 else
1219 Constants[i] = DAG.getConstant(0, EltVT);
1220 }
Dan Gohman1f565bc2008-08-04 23:30:41 +00001221 return DAG.getMergeValues(&Constants[0], NumElts);
Dan Gohman1d685a42008-06-07 02:02:36 +00001222 }
1223
Chris Lattner6833b062008-04-28 07:16:35 +00001224 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001225 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001226
Chris Lattner6833b062008-04-28 07:16:35 +00001227 // Now that we know the number and type of the elements, get that number of
1228 // elements into the Ops array based on what kind of constant it is.
Dan Gohman475871a2008-07-27 21:46:04 +00001229 SmallVector<SDValue, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001230 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1231 for (unsigned i = 0; i != NumElements; ++i)
1232 Ops.push_back(getValue(CP->getOperand(i)));
1233 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001234 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1235 "Unknown vector constant!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001236 MVT EltVT = TLI.getValueType(VecTy->getElementType());
Chris Lattner6833b062008-04-28 07:16:35 +00001237
Dan Gohman475871a2008-07-27 21:46:04 +00001238 SDValue Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001239 if (isa<UndefValue>(C))
1240 Op = DAG.getNode(ISD::UNDEF, EltVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001241 else if (EltVT.isFloatingPoint())
Chris Lattner6833b062008-04-28 07:16:35 +00001242 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001243 else
Chris Lattner6833b062008-04-28 07:16:35 +00001244 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001245 Ops.assign(NumElements, Op);
1246 }
1247
1248 // Create a BUILD_VECTOR node.
1249 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001250 }
1251
Chris Lattnerb606dba2008-04-28 06:44:42 +00001252 // If this is a static alloca, generate it as the frameindex instead of
1253 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001254 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1255 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001256 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001257 if (SI != FuncInfo.StaticAllocaMap.end())
1258 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1259 }
1260
Chris Lattner251db182007-02-25 18:40:32 +00001261 unsigned InReg = FuncInfo.ValueMap[V];
1262 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001263
Chris Lattner6833b062008-04-28 07:16:35 +00001264 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00001265 SDValue Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001266 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001267}
1268
1269
Chris Lattner1c08c712005-01-07 07:47:53 +00001270void SelectionDAGLowering::visitRet(ReturnInst &I) {
1271 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001272 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001273 return;
1274 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001275
Dan Gohman475871a2008-07-27 21:46:04 +00001276 SmallVector<SDValue, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001277 NewValues.push_back(getControlRoot());
1278 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00001279 SDValue RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001280
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001281 SmallVector<MVT, 4> ValueVTs;
1282 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1283 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
1284 MVT VT = ValueVTs[j];
Duncan Sandsb988bac2008-02-11 20:58:28 +00001285
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001286 // FIXME: C calling convention requires the return type to be promoted to
1287 // at least 32-bit. But this is not necessary for non-C calling conventions.
1288 if (VT.isInteger()) {
1289 MVT MinVT = TLI.getRegisterType(MVT::i32);
1290 if (VT.bitsLT(MinVT))
1291 VT = MinVT;
1292 }
Duncan Sandsb988bac2008-02-11 20:58:28 +00001293
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001294 unsigned NumParts = TLI.getNumRegisters(VT);
1295 MVT PartVT = TLI.getRegisterType(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00001296 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001297 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1298
1299 const Function *F = I.getParent()->getParent();
1300 if (F->paramHasAttr(0, ParamAttr::SExt))
1301 ExtendKind = ISD::SIGN_EXTEND;
1302 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1303 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00001304
Dan Gohman475871a2008-07-27 21:46:04 +00001305 getCopyToParts(DAG, SDValue(RetOp.Val, RetOp.ResNo + j),
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001306 &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00001307
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001308 for (unsigned i = 0; i < NumParts; ++i) {
1309 NewValues.push_back(Parts[i]);
1310 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1311 }
Nate Begemanee625572006-01-27 21:09:22 +00001312 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001313 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001314 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1315 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001316}
1317
Chris Lattner571e4342006-10-27 21:36:01 +00001318/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1319/// the current basic block, add it to ValueMap now so that we'll get a
1320/// CopyTo/FromReg.
1321void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1322 // No need to export constants.
1323 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1324
1325 // Already exported?
1326 if (FuncInfo.isExportedInst(V)) return;
1327
1328 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001329 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001330}
1331
Chris Lattner8c494ab2006-10-27 23:50:33 +00001332bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1333 const BasicBlock *FromBB) {
1334 // The operands of the setcc have to be in this block. We don't know
1335 // how to export them from some other block.
1336 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1337 // Can export from current BB.
1338 if (VI->getParent() == FromBB)
1339 return true;
1340
1341 // Is already exported, noop.
1342 return FuncInfo.isExportedInst(V);
1343 }
1344
1345 // If this is an argument, we can export it if the BB is the entry block or
1346 // if it is already exported.
1347 if (isa<Argument>(V)) {
1348 if (FromBB == &FromBB->getParent()->getEntryBlock())
1349 return true;
1350
1351 // Otherwise, can only export this if it is already exported.
1352 return FuncInfo.isExportedInst(V);
1353 }
1354
1355 // Otherwise, constants can always be exported.
1356 return true;
1357}
1358
Chris Lattner6a586c82006-10-29 21:01:20 +00001359static bool InBlock(const Value *V, const BasicBlock *BB) {
1360 if (const Instruction *I = dyn_cast<Instruction>(V))
1361 return I->getParent() == BB;
1362 return true;
1363}
1364
Chris Lattner571e4342006-10-27 21:36:01 +00001365/// FindMergedConditions - If Cond is an expression like
1366void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1367 MachineBasicBlock *TBB,
1368 MachineBasicBlock *FBB,
1369 MachineBasicBlock *CurBB,
1370 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001371 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001372 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001373
Reid Spencere4d87aa2006-12-23 06:05:41 +00001374 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1375 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001376 BOp->getParent() != CurBB->getBasicBlock() ||
1377 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1378 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001379 const BasicBlock *BB = CurBB->getBasicBlock();
1380
Reid Spencere4d87aa2006-12-23 06:05:41 +00001381 // If the leaf of the tree is a comparison, merge the condition into
1382 // the caseblock.
1383 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1384 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001385 // how to export them from some other block. If this is the first block
1386 // of the sequence, no exporting is needed.
1387 (CurBB == CurMBB ||
1388 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1389 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001390 BOp = cast<Instruction>(Cond);
1391 ISD::CondCode Condition;
1392 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1393 switch (IC->getPredicate()) {
1394 default: assert(0 && "Unknown icmp predicate opcode!");
1395 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1396 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1397 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1398 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1399 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1400 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1401 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1402 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1403 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1404 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1405 }
1406 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1407 ISD::CondCode FPC, FOC;
1408 switch (FC->getPredicate()) {
1409 default: assert(0 && "Unknown fcmp predicate opcode!");
1410 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1411 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1412 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1413 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1414 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1415 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1416 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001417 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1418 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001419 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1420 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1421 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1422 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1423 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1424 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1425 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1426 }
1427 if (FiniteOnlyFPMath())
1428 Condition = FOC;
1429 else
1430 Condition = FPC;
1431 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001432 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001433 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001434 }
1435
Chris Lattner571e4342006-10-27 21:36:01 +00001436 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001437 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001438 SwitchCases.push_back(CB);
1439 return;
1440 }
1441
1442 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001443 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001444 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001445 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001446 return;
1447 }
1448
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001449
1450 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001451 MachineFunction::iterator BBI = CurBB;
Dan Gohman0e5f1302008-07-07 23:02:41 +00001452 MachineFunction &MF = DAG.getMachineFunction();
1453 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1454 CurBB->getParent()->insert(++BBI, TmpBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001455
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001456 if (Opc == Instruction::Or) {
1457 // Codegen X | Y as:
1458 // jmp_if_X TBB
1459 // jmp TmpBB
1460 // TmpBB:
1461 // jmp_if_Y TBB
1462 // jmp FBB
1463 //
Chris Lattner571e4342006-10-27 21:36:01 +00001464
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001465 // Emit the LHS condition.
1466 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1467
1468 // Emit the RHS condition into TmpBB.
1469 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1470 } else {
1471 assert(Opc == Instruction::And && "Unknown merge op!");
1472 // Codegen X & Y as:
1473 // jmp_if_X TmpBB
1474 // jmp FBB
1475 // TmpBB:
1476 // jmp_if_Y TBB
1477 // jmp FBB
1478 //
1479 // This requires creation of TmpBB after CurBB.
1480
1481 // Emit the LHS condition.
1482 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1483
1484 // Emit the RHS condition into TmpBB.
1485 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1486 }
Chris Lattner571e4342006-10-27 21:36:01 +00001487}
1488
Chris Lattnerdf19f272006-10-31 22:37:42 +00001489/// If the set of cases should be emitted as a series of branches, return true.
1490/// If we should emit this as a bunch of and/or'd together conditions, return
1491/// false.
1492static bool
1493ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1494 if (Cases.size() != 2) return true;
1495
Chris Lattner0ccb5002006-10-31 23:06:00 +00001496 // If this is two comparisons of the same values or'd or and'd together, they
1497 // will get folded into a single comparison, so don't emit two blocks.
1498 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1499 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1500 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1501 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1502 return false;
1503 }
1504
Chris Lattnerdf19f272006-10-31 22:37:42 +00001505 return true;
1506}
1507
Chris Lattner1c08c712005-01-07 07:47:53 +00001508void SelectionDAGLowering::visitBr(BranchInst &I) {
1509 // Update machine-CFG edges.
1510 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001511
1512 // Figure out which block is immediately after the current one.
1513 MachineBasicBlock *NextBlock = 0;
1514 MachineFunction::iterator BBI = CurMBB;
1515 if (++BBI != CurMBB->getParent()->end())
1516 NextBlock = BBI;
1517
1518 if (I.isUnconditional()) {
Owen Anderson2d389e82008-06-07 00:00:23 +00001519 // Update machine-CFG edges.
1520 CurMBB->addSuccessor(Succ0MBB);
1521
Chris Lattner1c08c712005-01-07 07:47:53 +00001522 // If this is not a fall-through branch, emit the branch.
1523 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001524 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001525 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner57ab6592006-10-24 17:57:59 +00001526 return;
1527 }
1528
1529 // If this condition is one of the special cases we handle, do special stuff
1530 // now.
1531 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001532 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001533
1534 // If this is a series of conditions that are or'd or and'd together, emit
1535 // this as a sequence of branches instead of setcc's with and/or operations.
1536 // For example, instead of something like:
1537 // cmp A, B
1538 // C = seteq
1539 // cmp D, E
1540 // F = setle
1541 // or C, F
1542 // jnz foo
1543 // Emit:
1544 // cmp A, B
1545 // je foo
1546 // cmp D, E
1547 // jle foo
1548 //
1549 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1550 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001551 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001552 BOp->getOpcode() == Instruction::Or)) {
1553 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001554 // If the compares in later blocks need to use values not currently
1555 // exported from this block, export them now. This block should always
1556 // be the first entry.
1557 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1558
Chris Lattnerdf19f272006-10-31 22:37:42 +00001559 // Allow some cases to be rejected.
1560 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001561 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1562 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1563 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1564 }
1565
1566 // Emit the branch for this block.
1567 visitSwitchCase(SwitchCases[0]);
1568 SwitchCases.erase(SwitchCases.begin());
1569 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001570 }
1571
Chris Lattner0ccb5002006-10-31 23:06:00 +00001572 // Okay, we decided not to do this, remove any inserted MBB's and clear
1573 // SwitchCases.
1574 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0e5f1302008-07-07 23:02:41 +00001575 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Chris Lattner0ccb5002006-10-31 23:06:00 +00001576
Chris Lattnerdf19f272006-10-31 22:37:42 +00001577 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001578 }
1579 }
Chris Lattner24525952006-10-24 18:07:37 +00001580
1581 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001582 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001583 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001584 // Use visitSwitchCase to actually insert the fast branch sequence for this
1585 // cond branch.
1586 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001587}
1588
Nate Begemanf15485a2006-03-27 01:32:24 +00001589/// visitSwitchCase - Emits the necessary code to represent a single node in
1590/// the binary search tree resulting from lowering a switch instruction.
1591void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Dan Gohman475871a2008-07-27 21:46:04 +00001592 SDValue Cond;
1593 SDValue CondLHS = getValue(CB.CmpLHS);
Chris Lattner57ab6592006-10-24 17:57:59 +00001594
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001595 // Build the setcc now.
1596 if (CB.CmpMHS == NULL) {
1597 // Fold "(X == true)" to X and "(X == false)" to !X to
1598 // handle common cases produced by branch lowering.
1599 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1600 Cond = CondLHS;
1601 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Dan Gohman475871a2008-07-27 21:46:04 +00001602 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001603 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1604 } else
1605 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1606 } else {
1607 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001608
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001609 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1610 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1611
Dan Gohman475871a2008-07-27 21:46:04 +00001612 SDValue CmpOp = getValue(CB.CmpMHS);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001613 MVT VT = CmpOp.getValueType();
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001614
1615 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1616 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1617 } else {
Dan Gohman475871a2008-07-27 21:46:04 +00001618 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001619 Cond = DAG.getSetCC(MVT::i1, SUB,
1620 DAG.getConstant(High-Low, VT), ISD::SETULE);
1621 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001622 }
1623
Owen Anderson2d389e82008-06-07 00:00:23 +00001624 // Update successor info
1625 CurMBB->addSuccessor(CB.TrueBB);
1626 CurMBB->addSuccessor(CB.FalseBB);
1627
Nate Begemanf15485a2006-03-27 01:32:24 +00001628 // Set NextBlock to be the MBB immediately after the current one, if any.
1629 // This is used to avoid emitting unnecessary branches to the next block.
1630 MachineBasicBlock *NextBlock = 0;
1631 MachineFunction::iterator BBI = CurMBB;
1632 if (++BBI != CurMBB->getParent()->end())
1633 NextBlock = BBI;
1634
1635 // If the lhs block is the next block, invert the condition so that we can
1636 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001637 if (CB.TrueBB == NextBlock) {
1638 std::swap(CB.TrueBB, CB.FalseBB);
Dan Gohman475871a2008-07-27 21:46:04 +00001639 SDValue True = DAG.getConstant(1, Cond.getValueType());
Nate Begemanf15485a2006-03-27 01:32:24 +00001640 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1641 }
Dan Gohman475871a2008-07-27 21:46:04 +00001642 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001643 DAG.getBasicBlock(CB.TrueBB));
Owen Andersonbd3ba462008-08-04 23:54:43 +00001644
1645 // If the branch was constant folded, fix up the CFG.
1646 if (BrCond.getOpcode() == ISD::BR) {
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001647 CurMBB->removeSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001648 DAG.setRoot(BrCond);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001649 } else {
1650 // Otherwise, go ahead and insert the false branch.
1651 if (BrCond == getControlRoot())
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001652 CurMBB->removeSuccessor(CB.TrueBB);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001653
1654 if (CB.FalseBB == NextBlock)
1655 DAG.setRoot(BrCond);
1656 else
1657 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1658 DAG.getBasicBlock(CB.FalseBB)));
1659 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001660}
1661
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001662/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001663void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001664 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001665 assert(JT.Reg != -1U && "Should lower JT Header first!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001666 MVT PTy = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00001667 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1668 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001669 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1670 Table, Index));
1671 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001672}
1673
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001674/// visitJumpTableHeader - This function emits necessary code to produce index
1675/// in the JumpTable from switch case.
1676void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1677 SelectionDAGISel::JumpTableHeader &JTH) {
1678 // Subtract the lowest switch case value from the value being switched on
1679 // and conditional branch to default mbb if the result is greater than the
1680 // difference between smallest and largest cases.
Dan Gohman475871a2008-07-27 21:46:04 +00001681 SDValue SwitchOp = getValue(JTH.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001682 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001683 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001684 DAG.getConstant(JTH.First, VT));
1685
1686 // The SDNode we just created, which holds the value being switched on
1687 // minus the the smallest case value, needs to be copied to a virtual
1688 // register so it can be used as an index into the jump table in a
1689 // subsequent basic block. This value may be smaller or larger than the
1690 // target's pointer type, and therefore require extension or truncating.
Duncan Sands8e4eb092008-06-08 20:54:56 +00001691 if (VT.bitsGT(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001692 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1693 else
1694 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1695
1696 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001697 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001698 JT.Reg = JumpTableReg;
1699
1700 // Emit the range check for the jump table, and branch to the default
1701 // block for the switch statement if the value being switched on exceeds
1702 // the largest case in the switch.
Dan Gohman475871a2008-07-27 21:46:04 +00001703 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001704 DAG.getConstant(JTH.Last-JTH.First,VT),
1705 ISD::SETUGT);
1706
1707 // Set NextBlock to be the MBB immediately after the current one, if any.
1708 // This is used to avoid emitting unnecessary branches to the next block.
1709 MachineBasicBlock *NextBlock = 0;
1710 MachineFunction::iterator BBI = CurMBB;
1711 if (++BBI != CurMBB->getParent()->end())
1712 NextBlock = BBI;
1713
Dan Gohman475871a2008-07-27 21:46:04 +00001714 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001715 DAG.getBasicBlock(JT.Default));
1716
1717 if (JT.MBB == NextBlock)
1718 DAG.setRoot(BrCond);
1719 else
1720 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001721 DAG.getBasicBlock(JT.MBB)));
1722
1723 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001724}
1725
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001726/// visitBitTestHeader - This function emits necessary code to produce value
1727/// suitable for "bit tests"
1728void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1729 // Subtract the minimum value
Dan Gohman475871a2008-07-27 21:46:04 +00001730 SDValue SwitchOp = getValue(B.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001731 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001732 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001733 DAG.getConstant(B.First, VT));
1734
1735 // Check range
Dan Gohman475871a2008-07-27 21:46:04 +00001736 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001737 DAG.getConstant(B.Range, VT),
1738 ISD::SETUGT);
1739
Dan Gohman475871a2008-07-27 21:46:04 +00001740 SDValue ShiftOp;
Duncan Sands8e4eb092008-06-08 20:54:56 +00001741 if (VT.bitsGT(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001742 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1743 else
1744 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1745
1746 // Make desired shift
Dan Gohman475871a2008-07-27 21:46:04 +00001747 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001748 DAG.getConstant(1, TLI.getPointerTy()),
1749 ShiftOp);
1750
1751 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001752 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001753 B.Reg = SwitchReg;
1754
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001755 // Set NextBlock to be the MBB immediately after the current one, if any.
1756 // This is used to avoid emitting unnecessary branches to the next block.
1757 MachineBasicBlock *NextBlock = 0;
1758 MachineFunction::iterator BBI = CurMBB;
1759 if (++BBI != CurMBB->getParent()->end())
1760 NextBlock = BBI;
1761
1762 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
Owen Anderson2d389e82008-06-07 00:00:23 +00001763
1764 CurMBB->addSuccessor(B.Default);
1765 CurMBB->addSuccessor(MBB);
1766
Dan Gohman475871a2008-07-27 21:46:04 +00001767 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
Owen Anderson2d389e82008-06-07 00:00:23 +00001768 DAG.getBasicBlock(B.Default));
1769
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001770 if (MBB == NextBlock)
1771 DAG.setRoot(BrRange);
1772 else
1773 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1774 DAG.getBasicBlock(MBB)));
1775
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001776 return;
1777}
1778
1779/// visitBitTestCase - this function produces one "bit test"
1780void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1781 unsigned Reg,
1782 SelectionDAGISel::BitTestCase &B) {
1783 // Emit bit tests and jumps
Dan Gohman475871a2008-07-27 21:46:04 +00001784 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
Chris Lattneread0d882008-06-17 06:09:18 +00001785 TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001786
Dan Gohman475871a2008-07-27 21:46:04 +00001787 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
Chris Lattneread0d882008-06-17 06:09:18 +00001788 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dan Gohman475871a2008-07-27 21:46:04 +00001789 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001790 DAG.getConstant(0, TLI.getPointerTy()),
1791 ISD::SETNE);
Owen Anderson2d389e82008-06-07 00:00:23 +00001792
1793 CurMBB->addSuccessor(B.TargetBB);
1794 CurMBB->addSuccessor(NextMBB);
1795
Dan Gohman475871a2008-07-27 21:46:04 +00001796 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001797 AndCmp, DAG.getBasicBlock(B.TargetBB));
1798
1799 // Set NextBlock to be the MBB immediately after the current one, if any.
1800 // This is used to avoid emitting unnecessary branches to the next block.
1801 MachineBasicBlock *NextBlock = 0;
1802 MachineFunction::iterator BBI = CurMBB;
1803 if (++BBI != CurMBB->getParent()->end())
1804 NextBlock = BBI;
1805
1806 if (NextMBB == NextBlock)
1807 DAG.setRoot(BrAnd);
1808 else
1809 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1810 DAG.getBasicBlock(NextMBB)));
1811
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001812 return;
1813}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001814
Jim Laskeyb180aa12007-02-21 22:53:45 +00001815void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1816 // Retrieve successors.
1817 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001818 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001819
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001820 if (isa<InlineAsm>(I.getCalledValue()))
1821 visitInlineAsm(&I);
1822 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001823 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001824
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001825 // If the value of the invoke is used outside of its defining block, make it
1826 // available as a virtual register.
1827 if (!I.use_empty()) {
1828 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1829 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001830 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001831 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001832
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001833 // Update successor info
1834 CurMBB->addSuccessor(Return);
1835 CurMBB->addSuccessor(LandingPad);
Owen Anderson2d389e82008-06-07 00:00:23 +00001836
1837 // Drop into normal successor.
1838 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1839 DAG.getBasicBlock(Return)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001840}
1841
1842void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1843}
1844
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001845/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001846/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001847bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001848 CaseRecVector& WorkList,
1849 Value* SV,
1850 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001851 Case& BackCase = *(CR.Range.second-1);
1852
1853 // Size is the number of Cases represented by this range.
1854 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001855 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001856 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001857
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001858 // Get the MachineFunction which holds the current MBB. This is used when
1859 // inserting any additional MBBs necessary to represent the switch.
1860 MachineFunction *CurMF = CurMBB->getParent();
1861
1862 // Figure out which block is immediately after the current one.
1863 MachineBasicBlock *NextBlock = 0;
1864 MachineFunction::iterator BBI = CR.CaseBB;
1865
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001866 if (++BBI != CurMBB->getParent()->end())
1867 NextBlock = BBI;
1868
1869 // TODO: If any two of the cases has the same destination, and if one value
1870 // is the same as the other, but has one bit unset that the other has set,
1871 // use bit manipulation to do two compares at once. For example:
1872 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1873
1874 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001875 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001876 // The last case block won't fall through into 'NextBlock' if we emit the
1877 // branches in this order. See if rearranging a case value would help.
1878 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001879 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001880 std::swap(*I, BackCase);
1881 break;
1882 }
1883 }
1884 }
1885
1886 // Create a CaseBlock record representing a conditional branch to
1887 // the Case's target mbb if the value being switched on SV is equal
1888 // to C.
1889 MachineBasicBlock *CurBlock = CR.CaseBB;
1890 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1891 MachineBasicBlock *FallThrough;
1892 if (I != E-1) {
Dan Gohman0e5f1302008-07-07 23:02:41 +00001893 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1894 CurMF->insert(BBI, FallThrough);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001895 } else {
1896 // If the last case doesn't match, go to the default block.
1897 FallThrough = Default;
1898 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001899
1900 Value *RHS, *LHS, *MHS;
1901 ISD::CondCode CC;
1902 if (I->High == I->Low) {
1903 // This is just small small case range :) containing exactly 1 case
1904 CC = ISD::SETEQ;
1905 LHS = SV; RHS = I->High; MHS = NULL;
1906 } else {
1907 CC = ISD::SETLE;
1908 LHS = I->Low; MHS = SV; RHS = I->High;
1909 }
1910 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1911 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001912
1913 // If emitting the first comparison, just call visitSwitchCase to emit the
1914 // code into the current block. Otherwise, push the CaseBlock onto the
1915 // vector to be later processed by SDISel, and insert the node's MBB
1916 // before the next MBB.
1917 if (CurBlock == CurMBB)
1918 visitSwitchCase(CB);
1919 else
1920 SwitchCases.push_back(CB);
1921
1922 CurBlock = FallThrough;
1923 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001924
1925 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001926}
1927
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001928static inline bool areJTsAllowed(const TargetLowering &TLI) {
Dale Johannesen72324642008-07-31 18:13:12 +00001929 return !DisableJumpTables &&
1930 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1931 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001932}
1933
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001934/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001935bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001936 CaseRecVector& WorkList,
1937 Value* SV,
1938 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001939 Case& FrontCase = *CR.Range.first;
1940 Case& BackCase = *(CR.Range.second-1);
1941
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001942 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1943 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1944
1945 uint64_t TSize = 0;
1946 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1947 I!=E; ++I)
1948 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001949
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001950 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001951 return false;
1952
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001953 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1954 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001955 return false;
1956
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001957 DOUT << "Lowering jump table\n"
1958 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001959 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001960
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001961 // Get the MachineFunction which holds the current MBB. This is used when
1962 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001963 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001964
1965 // Figure out which block is immediately after the current one.
1966 MachineBasicBlock *NextBlock = 0;
1967 MachineFunction::iterator BBI = CR.CaseBB;
1968
1969 if (++BBI != CurMBB->getParent()->end())
1970 NextBlock = BBI;
1971
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001972 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1973
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001974 // Create a new basic block to hold the code for loading the address
1975 // of the jump table, and jumping to it. Update successor information;
1976 // we will either branch to the default case for the switch, or the jump
1977 // table.
Dan Gohman0e5f1302008-07-07 23:02:41 +00001978 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1979 CurMF->insert(BBI, JumpTableBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001980 CR.CaseBB->addSuccessor(Default);
1981 CR.CaseBB->addSuccessor(JumpTableBB);
1982
1983 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001984 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001985 // a case statement, push the case's BB onto the vector, otherwise, push
1986 // the default BB.
1987 std::vector<MachineBasicBlock*> DestBBs;
1988 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001989 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1990 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1991 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1992
1993 if ((Low <= TEI) && (TEI <= High)) {
1994 DestBBs.push_back(I->BB);
1995 if (TEI==High)
1996 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001997 } else {
1998 DestBBs.push_back(Default);
1999 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002000 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002001
2002 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002003 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002004 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2005 E = DestBBs.end(); I != E; ++I) {
2006 if (!SuccsHandled[(*I)->getNumber()]) {
2007 SuccsHandled[(*I)->getNumber()] = true;
2008 JumpTableBB->addSuccessor(*I);
2009 }
2010 }
2011
2012 // Create a jump table index for this jump table, or return an existing
2013 // one.
2014 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
2015
2016 // Set the jump table information so that we can codegen it as a second
2017 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00002018 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002019 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
2020 (CR.CaseBB == CurMBB));
2021 if (CR.CaseBB == CurMBB)
2022 visitJumpTableHeader(JT, JTH);
2023
2024 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002025
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002026 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002027}
2028
2029/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2030/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002031bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002032 CaseRecVector& WorkList,
2033 Value* SV,
2034 MachineBasicBlock* Default) {
2035 // Get the MachineFunction which holds the current MBB. This is used when
2036 // inserting any additional MBBs necessary to represent the switch.
2037 MachineFunction *CurMF = CurMBB->getParent();
2038
2039 // Figure out which block is immediately after the current one.
2040 MachineBasicBlock *NextBlock = 0;
2041 MachineFunction::iterator BBI = CR.CaseBB;
2042
2043 if (++BBI != CurMBB->getParent()->end())
2044 NextBlock = BBI;
2045
2046 Case& FrontCase = *CR.Range.first;
2047 Case& BackCase = *(CR.Range.second-1);
2048 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2049
2050 // Size is the number of Cases represented by this range.
2051 unsigned Size = CR.Range.second - CR.Range.first;
2052
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002053 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2054 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002055 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002056 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002057
2058 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2059 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002060 uint64_t TSize = 0;
2061 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2062 I!=E; ++I)
2063 TSize += I->size();
2064
2065 uint64_t LSize = FrontCase.size();
2066 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002067 DOUT << "Selecting best pivot: \n"
2068 << "First: " << First << ", Last: " << Last <<"\n"
2069 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002070 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002071 J!=E; ++I, ++J) {
2072 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2073 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002074 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002075 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2076 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00002077 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002078 // Should always split in some non-trivial place
2079 DOUT <<"=>Step\n"
2080 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2081 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2082 << "Metric: " << Metric << "\n";
2083 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002084 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002085 FMetric = Metric;
2086 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002087 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002088
2089 LSize += J->size();
2090 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002091 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002092 if (areJTsAllowed(TLI)) {
2093 // If our case is dense we *really* should handle it earlier!
2094 assert((FMetric > 0) && "Should handle dense range earlier!");
2095 } else {
2096 Pivot = CR.Range.first + Size/2;
2097 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002098
2099 CaseRange LHSR(CR.Range.first, Pivot);
2100 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002101 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002102 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2103
2104 // We know that we branch to the LHS if the Value being switched on is
2105 // less than the Pivot value, C. We use this to optimize our binary
2106 // tree a bit, by recognizing that if SV is greater than or equal to the
2107 // LHS's Case Value, and that Case Value is exactly one less than the
2108 // Pivot's Value, then we can branch directly to the LHS's Target,
2109 // rather than creating a leaf node for it.
2110 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002111 LHSR.first->High == CR.GE &&
2112 cast<ConstantInt>(C)->getSExtValue() ==
2113 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2114 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002115 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002116 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2117 CurMF->insert(BBI, TrueBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002118 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2119 }
2120
2121 // Similar to the optimization above, if the Value being switched on is
2122 // known to be less than the Constant CR.LT, and the current Case Value
2123 // is CR.LT - 1, then we can branch directly to the target block for
2124 // the current Case Value, rather than emitting a RHS leaf node for it.
2125 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002126 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2127 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2128 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002129 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002130 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2131 CurMF->insert(BBI, FalseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002132 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2133 }
2134
2135 // Create a CaseBlock record representing a conditional branch to
2136 // the LHS node if the value being switched on SV is less than C.
2137 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002138 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
2139 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002140
2141 if (CR.CaseBB == CurMBB)
2142 visitSwitchCase(CB);
2143 else
2144 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002145
2146 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002147}
2148
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002149/// handleBitTestsSwitchCase - if current case range has few destination and
2150/// range span less, than machine word bitwidth, encode case range into series
2151/// of masks and emit bit tests with these masks.
2152bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2153 CaseRecVector& WorkList,
2154 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002155 MachineBasicBlock* Default){
Duncan Sands83ec4b62008-06-06 12:08:01 +00002156 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002157
2158 Case& FrontCase = *CR.Range.first;
2159 Case& BackCase = *(CR.Range.second-1);
2160
2161 // Get the MachineFunction which holds the current MBB. This is used when
2162 // inserting any additional MBBs necessary to represent the switch.
2163 MachineFunction *CurMF = CurMBB->getParent();
2164
2165 unsigned numCmps = 0;
2166 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2167 I!=E; ++I) {
2168 // Single case counts one, case range - two.
2169 if (I->Low == I->High)
2170 numCmps +=1;
2171 else
2172 numCmps +=2;
2173 }
2174
2175 // Count unique destinations
2176 SmallSet<MachineBasicBlock*, 4> Dests;
2177 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2178 Dests.insert(I->BB);
2179 if (Dests.size() > 3)
2180 // Don't bother the code below, if there are too much unique destinations
2181 return false;
2182 }
2183 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2184 << "Total number of comparisons: " << numCmps << "\n";
2185
2186 // Compute span of values.
2187 Constant* minValue = FrontCase.Low;
2188 Constant* maxValue = BackCase.High;
2189 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2190 cast<ConstantInt>(minValue)->getSExtValue();
2191 DOUT << "Compare range: " << range << "\n"
2192 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2193 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2194
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002195 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002196 (!(Dests.size() == 1 && numCmps >= 3) &&
2197 !(Dests.size() == 2 && numCmps >= 5) &&
2198 !(Dests.size() >= 3 && numCmps >= 6)))
2199 return false;
2200
2201 DOUT << "Emitting bit tests\n";
2202 int64_t lowBound = 0;
2203
2204 // Optimize the case where all the case values fit in a
2205 // word without having to subtract minValue. In this case,
2206 // we can optimize away the subtraction.
2207 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002208 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002209 range = cast<ConstantInt>(maxValue)->getSExtValue();
2210 } else {
2211 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2212 }
2213
2214 CaseBitsVector CasesBits;
2215 unsigned i, count = 0;
2216
2217 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2218 MachineBasicBlock* Dest = I->BB;
2219 for (i = 0; i < count; ++i)
2220 if (Dest == CasesBits[i].BB)
2221 break;
2222
2223 if (i == count) {
2224 assert((count < 3) && "Too much destinations to test!");
2225 CasesBits.push_back(CaseBits(0, Dest, 0));
2226 count++;
2227 }
2228
2229 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2230 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2231
2232 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002233 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002234 CasesBits[i].Bits++;
2235 }
2236
2237 }
2238 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2239
2240 SelectionDAGISel::BitTestInfo BTC;
2241
2242 // Figure out which block is immediately after the current one.
2243 MachineFunction::iterator BBI = CR.CaseBB;
2244 ++BBI;
2245
2246 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2247
2248 DOUT << "Cases:\n";
2249 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2250 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2251 << ", BB: " << CasesBits[i].BB << "\n";
2252
Dan Gohman0e5f1302008-07-07 23:02:41 +00002253 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2254 CurMF->insert(BBI, CaseBB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002255 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2256 CaseBB,
2257 CasesBits[i].BB));
2258 }
2259
2260 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002261 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002262 CR.CaseBB, Default, BTC);
2263
2264 if (CR.CaseBB == CurMBB)
2265 visitBitTestHeader(BTB);
2266
2267 BitTestCases.push_back(BTB);
2268
2269 return true;
2270}
2271
2272
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002273/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002274unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2275 const SwitchInst& SI) {
2276 unsigned numCmps = 0;
2277
2278 // Start with "simple" cases
2279 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2280 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2281 Cases.push_back(Case(SI.getSuccessorValue(i),
2282 SI.getSuccessorValue(i),
2283 SMBB));
2284 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002285 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002286
2287 // Merge case into clusters
2288 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002289 // Must recompute end() each iteration because it may be
2290 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002291 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002292 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2293 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2294 MachineBasicBlock* nextBB = J->BB;
2295 MachineBasicBlock* currentBB = I->BB;
2296
2297 // If the two neighboring cases go to the same destination, merge them
2298 // into a single case.
2299 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2300 I->High = J->High;
2301 J = Cases.erase(J);
2302 } else {
2303 I = J++;
2304 }
2305 }
2306
2307 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2308 if (I->Low != I->High)
2309 // A range counts double, since it requires two compares.
2310 ++numCmps;
2311 }
2312
2313 return numCmps;
2314}
2315
2316void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002317 // Figure out which block is immediately after the current one.
2318 MachineBasicBlock *NextBlock = 0;
2319 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002320
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002321 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002322
Nate Begemanf15485a2006-03-27 01:32:24 +00002323 // If there is only the default destination, branch to it if it is not the
2324 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002325 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002326 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002327
Nate Begemanf15485a2006-03-27 01:32:24 +00002328 // If this is not a fall-through branch, emit the branch.
Owen Anderson2d389e82008-06-07 00:00:23 +00002329 CurMBB->addSuccessor(Default);
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002330 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002331 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002332 DAG.getBasicBlock(Default)));
Owen Anderson2d389e82008-06-07 00:00:23 +00002333
Nate Begemanf15485a2006-03-27 01:32:24 +00002334 return;
2335 }
2336
2337 // If there are any non-default case statements, create a vector of Cases
2338 // representing each one, and sort the vector so that we can efficiently
2339 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002340 CaseVector Cases;
2341 unsigned numCmps = Clusterify(Cases, SI);
2342 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2343 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002344
Nate Begemanf15485a2006-03-27 01:32:24 +00002345 // Get the Value to be switched on and default basic blocks, which will be
2346 // inserted into CaseBlock records, representing basic blocks in the binary
2347 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002348 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002349
Nate Begemanf15485a2006-03-27 01:32:24 +00002350 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002351 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002352 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2353
2354 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002355 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002356 CaseRec CR = WorkList.back();
2357 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002358
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002359 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2360 continue;
2361
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002362 // If the range has few cases (two or less) emit a series of specific
2363 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002364 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2365 continue;
2366
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002367 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002368 // target supports indirect branches, then emit a jump table rather than
2369 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002370 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2371 continue;
2372
2373 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2374 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2375 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002376 }
2377}
2378
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002379
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002380void SelectionDAGLowering::visitSub(User &I) {
2381 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002382 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002383 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002384 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2385 const VectorType *DestTy = cast<VectorType>(I.getType());
2386 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002387 if (ElTy->isFloatingPoint()) {
2388 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002389 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002390 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2391 if (CV == CNZ) {
Dan Gohman475871a2008-07-27 21:46:04 +00002392 SDValue Op2 = getValue(I.getOperand(1));
Evan Chengc45453f2007-06-29 21:44:35 +00002393 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2394 return;
2395 }
Dan Gohman7f321562007-06-25 16:23:39 +00002396 }
2397 }
2398 }
2399 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002400 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002401 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohman475871a2008-07-27 21:46:04 +00002402 SDValue Op2 = getValue(I.getOperand(1));
Chris Lattner01b3d732005-09-28 22:28:18 +00002403 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2404 return;
2405 }
Dan Gohman7f321562007-06-25 16:23:39 +00002406 }
2407
2408 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002409}
2410
Dan Gohman7f321562007-06-25 16:23:39 +00002411void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002412 SDValue Op1 = getValue(I.getOperand(0));
2413 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002414
2415 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002416}
2417
Nate Begemane21ea612005-11-18 07:42:56 +00002418void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002419 SDValue Op1 = getValue(I.getOperand(0));
2420 SDValue Op2 = getValue(I.getOperand(1));
Nate Begeman5bc1ea02008-07-29 15:49:41 +00002421 if (!isa<VectorType>(I.getType())) {
2422 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2423 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2424 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2425 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2426 }
Nate Begemane21ea612005-11-18 07:42:56 +00002427
Chris Lattner1c08c712005-01-07 07:47:53 +00002428 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2429}
2430
Reid Spencer45fb3f32006-11-20 01:22:35 +00002431void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002432 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2433 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2434 predicate = IC->getPredicate();
2435 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2436 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002437 SDValue Op1 = getValue(I.getOperand(0));
2438 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002439 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002440 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002441 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2442 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2443 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2444 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2445 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2446 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2447 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2448 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2449 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2450 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2451 default:
2452 assert(!"Invalid ICmp predicate value");
2453 Opcode = ISD::SETEQ;
2454 break;
2455 }
2456 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2457}
2458
2459void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002460 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2461 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2462 predicate = FC->getPredicate();
2463 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2464 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002465 SDValue Op1 = getValue(I.getOperand(0));
2466 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002467 ISD::CondCode Condition, FOC, FPC;
2468 switch (predicate) {
2469 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2470 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2471 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2472 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2473 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2474 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2475 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002476 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2477 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002478 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2479 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2480 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2481 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2482 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2483 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2484 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2485 default:
2486 assert(!"Invalid FCmp predicate value");
2487 FOC = FPC = ISD::SETFALSE;
2488 break;
2489 }
2490 if (FiniteOnlyFPMath())
2491 Condition = FOC;
2492 else
2493 Condition = FPC;
2494 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002495}
2496
Nate Begemanb43e9c12008-05-12 19:40:03 +00002497void SelectionDAGLowering::visitVICmp(User &I) {
2498 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2499 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2500 predicate = IC->getPredicate();
2501 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2502 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002503 SDValue Op1 = getValue(I.getOperand(0));
2504 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002505 ISD::CondCode Opcode;
2506 switch (predicate) {
2507 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2508 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2509 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2510 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2511 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2512 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2513 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2514 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2515 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2516 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2517 default:
2518 assert(!"Invalid ICmp predicate value");
2519 Opcode = ISD::SETEQ;
2520 break;
2521 }
2522 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2523}
2524
2525void SelectionDAGLowering::visitVFCmp(User &I) {
2526 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2527 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2528 predicate = FC->getPredicate();
2529 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2530 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002531 SDValue Op1 = getValue(I.getOperand(0));
2532 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002533 ISD::CondCode Condition, FOC, FPC;
2534 switch (predicate) {
2535 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2536 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2537 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2538 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2539 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2540 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2541 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2542 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2543 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2544 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2545 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2546 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2547 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2548 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2549 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2550 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2551 default:
2552 assert(!"Invalid VFCmp predicate value");
2553 FOC = FPC = ISD::SETFALSE;
2554 break;
2555 }
2556 if (FiniteOnlyFPMath())
2557 Condition = FOC;
2558 else
2559 Condition = FPC;
2560
Duncan Sands83ec4b62008-06-06 12:08:01 +00002561 MVT DestVT = TLI.getValueType(I.getType());
Nate Begemanb43e9c12008-05-12 19:40:03 +00002562
2563 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2564}
2565
Chris Lattner1c08c712005-01-07 07:47:53 +00002566void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002567 SDValue Cond = getValue(I.getOperand(0));
2568 SDValue TrueVal = getValue(I.getOperand(1));
2569 SDValue FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002570 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2571 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002572}
2573
Reid Spencer3da59db2006-11-27 01:05:10 +00002574
2575void SelectionDAGLowering::visitTrunc(User &I) {
2576 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
Dan Gohman475871a2008-07-27 21:46:04 +00002577 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002578 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002579 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2580}
2581
2582void SelectionDAGLowering::visitZExt(User &I) {
2583 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2584 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002585 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002586 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002587 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2588}
2589
2590void SelectionDAGLowering::visitSExt(User &I) {
2591 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2592 // SExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002593 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002594 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002595 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2596}
2597
2598void SelectionDAGLowering::visitFPTrunc(User &I) {
2599 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002600 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002601 MVT DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002602 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002603}
2604
2605void SelectionDAGLowering::visitFPExt(User &I){
2606 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002607 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002608 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002609 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2610}
2611
2612void SelectionDAGLowering::visitFPToUI(User &I) {
2613 // FPToUI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002614 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002615 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002616 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2617}
2618
2619void SelectionDAGLowering::visitFPToSI(User &I) {
2620 // FPToSI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002621 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002622 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002623 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2624}
2625
2626void SelectionDAGLowering::visitUIToFP(User &I) {
2627 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002628 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002629 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002630 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2631}
2632
2633void SelectionDAGLowering::visitSIToFP(User &I){
2634 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002635 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002636 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002637 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2638}
2639
2640void SelectionDAGLowering::visitPtrToInt(User &I) {
2641 // What to do depends on the size of the integer and the size of the pointer.
2642 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002643 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002644 MVT SrcVT = N.getValueType();
2645 MVT DestVT = TLI.getValueType(I.getType());
Dan Gohman475871a2008-07-27 21:46:04 +00002646 SDValue Result;
Duncan Sands8e4eb092008-06-08 20:54:56 +00002647 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002648 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2649 else
2650 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2651 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2652 setValue(&I, Result);
2653}
Chris Lattner1c08c712005-01-07 07:47:53 +00002654
Reid Spencer3da59db2006-11-27 01:05:10 +00002655void SelectionDAGLowering::visitIntToPtr(User &I) {
2656 // What to do depends on the size of the integer and the size of the pointer.
2657 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002658 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002659 MVT SrcVT = N.getValueType();
2660 MVT DestVT = TLI.getValueType(I.getType());
Duncan Sands8e4eb092008-06-08 20:54:56 +00002661 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002662 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2663 else
2664 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2665 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2666}
2667
2668void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002669 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002670 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002671
2672 // BitCast assures us that source and destination are the same size so this
2673 // is either a BIT_CONVERT or a no-op.
2674 if (DestVT != N.getValueType())
2675 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2676 else
2677 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002678}
2679
Chris Lattner2bbd8102006-03-29 00:11:43 +00002680void SelectionDAGLowering::visitInsertElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002681 SDValue InVec = getValue(I.getOperand(0));
2682 SDValue InVal = getValue(I.getOperand(1));
2683 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattnerc7029802006-03-18 01:44:44 +00002684 getValue(I.getOperand(2)));
2685
Dan Gohman7f321562007-06-25 16:23:39 +00002686 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2687 TLI.getValueType(I.getType()),
2688 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002689}
2690
Chris Lattner2bbd8102006-03-29 00:11:43 +00002691void SelectionDAGLowering::visitExtractElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002692 SDValue InVec = getValue(I.getOperand(0));
2693 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattner384504c2006-03-21 20:44:12 +00002694 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002695 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002696 TLI.getValueType(I.getType()), InVec, InIdx));
2697}
Chris Lattnerc7029802006-03-18 01:44:44 +00002698
Chris Lattner3e104b12006-04-08 04:15:24 +00002699void SelectionDAGLowering::visitShuffleVector(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002700 SDValue V1 = getValue(I.getOperand(0));
2701 SDValue V2 = getValue(I.getOperand(1));
2702 SDValue Mask = getValue(I.getOperand(2));
Chris Lattner3e104b12006-04-08 04:15:24 +00002703
Dan Gohman7f321562007-06-25 16:23:39 +00002704 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2705 TLI.getValueType(I.getType()),
2706 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002707}
2708
Dan Gohman1d685a42008-06-07 02:02:36 +00002709void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2710 const Value *Op0 = I.getOperand(0);
2711 const Value *Op1 = I.getOperand(1);
2712 const Type *AggTy = I.getType();
2713 const Type *ValTy = Op1->getType();
2714 bool IntoUndef = isa<UndefValue>(Op0);
2715 bool FromUndef = isa<UndefValue>(Op1);
2716
2717 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2718 I.idx_begin(), I.idx_end());
2719
2720 SmallVector<MVT, 4> AggValueVTs;
2721 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2722 SmallVector<MVT, 4> ValValueVTs;
2723 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2724
2725 unsigned NumAggValues = AggValueVTs.size();
2726 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002727 SmallVector<SDValue, 4> Values(NumAggValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002728
Dan Gohman475871a2008-07-27 21:46:04 +00002729 SDValue Agg = getValue(Op0);
2730 SDValue Val = getValue(Op1);
Dan Gohman1d685a42008-06-07 02:02:36 +00002731 unsigned i = 0;
2732 // Copy the beginning value(s) from the original aggregate.
2733 for (; i != LinearIndex; ++i)
2734 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002735 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002736 // Copy values from the inserted value(s).
2737 for (; i != LinearIndex + NumValValues; ++i)
2738 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002739 SDValue(Val.Val, Val.ResNo + i - LinearIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +00002740 // Copy remaining value(s) from the original aggregate.
2741 for (; i != NumAggValues; ++i)
2742 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002743 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002744
Duncan Sandsf9516202008-06-30 10:19:09 +00002745 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2746 &Values[0], NumAggValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002747}
2748
Dan Gohman1d685a42008-06-07 02:02:36 +00002749void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2750 const Value *Op0 = I.getOperand(0);
2751 const Type *AggTy = Op0->getType();
2752 const Type *ValTy = I.getType();
2753 bool OutOfUndef = isa<UndefValue>(Op0);
2754
2755 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2756 I.idx_begin(), I.idx_end());
2757
2758 SmallVector<MVT, 4> ValValueVTs;
2759 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2760
2761 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002762 SmallVector<SDValue, 4> Values(NumValValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002763
Dan Gohman475871a2008-07-27 21:46:04 +00002764 SDValue Agg = getValue(Op0);
Dan Gohman1d685a42008-06-07 02:02:36 +00002765 // Copy out the selected value(s).
2766 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2767 Values[i - LinearIndex] =
Dan Gohmandded0fd2008-06-20 00:54:19 +00002768 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(Agg.ResNo + i)) :
Dan Gohman475871a2008-07-27 21:46:04 +00002769 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002770
Duncan Sandsf9516202008-06-30 10:19:09 +00002771 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2772 &Values[0], NumValValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002773}
2774
Chris Lattner3e104b12006-04-08 04:15:24 +00002775
Chris Lattner1c08c712005-01-07 07:47:53 +00002776void SelectionDAGLowering::visitGetElementPtr(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002777 SDValue N = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00002778 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002779
2780 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2781 OI != E; ++OI) {
2782 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002783 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002784 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002785 if (Field) {
2786 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002787 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002788 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002789 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002790 }
2791 Ty = StTy->getElementType(Field);
2792 } else {
2793 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002794
Chris Lattner7c0104b2005-11-09 04:45:33 +00002795 // If this is a constant subscript, handle it quickly.
2796 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002797 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002798 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002799 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002800 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2801 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002802 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002803 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002804
2805 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002806 uint64_t ElementSize = TD->getABITypeSize(Ty);
Dan Gohman475871a2008-07-27 21:46:04 +00002807 SDValue IdxN = getValue(Idx);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002808
2809 // If the index is smaller or larger than intptr_t, truncate or extend
2810 // it.
Duncan Sands8e4eb092008-06-08 20:54:56 +00002811 if (IdxN.getValueType().bitsLT(N.getValueType())) {
Reid Spencer47857812006-12-31 05:55:36 +00002812 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002813 } else if (IdxN.getValueType().bitsGT(N.getValueType()))
Chris Lattner7c0104b2005-11-09 04:45:33 +00002814 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2815
2816 // If this is a multiply by a power of two, turn it into a shl
2817 // immediately. This is a very common case.
2818 if (isPowerOf2_64(ElementSize)) {
2819 unsigned Amt = Log2_64(ElementSize);
2820 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002821 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002822 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2823 continue;
2824 }
2825
Dan Gohman475871a2008-07-27 21:46:04 +00002826 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002827 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2828 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002829 }
2830 }
2831 setValue(&I, N);
2832}
2833
2834void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2835 // If this is a fixed sized alloca in the entry block of the function,
2836 // allocate it statically on the stack.
2837 if (FuncInfo.StaticAllocaMap.count(&I))
2838 return; // getValue will auto-populate this.
2839
2840 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002841 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002842 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002843 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002844 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002845
Dan Gohman475871a2008-07-27 21:46:04 +00002846 SDValue AllocSize = getValue(I.getArraySize());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002847 MVT IntPtr = TLI.getPointerTy();
Duncan Sands8e4eb092008-06-08 20:54:56 +00002848 if (IntPtr.bitsLT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002849 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002850 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002851 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002852
Chris Lattner68cd65e2005-01-22 23:04:37 +00002853 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002854 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002855
Evan Cheng45157792007-08-16 23:46:29 +00002856 // Handle alignment. If the requested alignment is less than or equal to
2857 // the stack alignment, ignore it. If the size is greater than or equal to
2858 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002859 unsigned StackAlign =
2860 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002861 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002862 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002863
2864 // Round the size of the allocation up to the stack alignment size
2865 // by add SA-1 to the size.
2866 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002867 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002868 // Mask out the low bits for alignment purposes.
2869 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002870 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002871
Dan Gohman475871a2008-07-27 21:46:04 +00002872 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Duncan Sands83ec4b62008-06-06 12:08:01 +00002873 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002874 MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00002875 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002876 setValue(&I, DSA);
2877 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002878
2879 // Inform the Frame Information that we have just allocated a variable-sized
2880 // object.
2881 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2882}
2883
Chris Lattner1c08c712005-01-07 07:47:53 +00002884void SelectionDAGLowering::visitLoad(LoadInst &I) {
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002885 const Value *SV = I.getOperand(0);
Dan Gohman475871a2008-07-27 21:46:04 +00002886 SDValue Ptr = getValue(SV);
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002887
2888 const Type *Ty = I.getType();
2889 bool isVolatile = I.isVolatile();
2890 unsigned Alignment = I.getAlignment();
2891
2892 SmallVector<MVT, 4> ValueVTs;
2893 SmallVector<uint64_t, 4> Offsets;
2894 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2895 unsigned NumValues = ValueVTs.size();
2896 if (NumValues == 0)
2897 return;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002898
Dan Gohman475871a2008-07-27 21:46:04 +00002899 SDValue Root;
Dan Gohman8b4588f2008-07-25 00:04:14 +00002900 bool ConstantMemory = false;
Chris Lattnerd3948112005-01-17 22:19:26 +00002901 if (I.isVolatile())
Dan Gohman8b4588f2008-07-25 00:04:14 +00002902 // Serialize volatile loads with other side effects.
Chris Lattnerd3948112005-01-17 22:19:26 +00002903 Root = getRoot();
Dan Gohman8b4588f2008-07-25 00:04:14 +00002904 else if (AA.pointsToConstantMemory(SV)) {
2905 // Do not serialize (non-volatile) loads of constant memory with anything.
2906 Root = DAG.getEntryNode();
2907 ConstantMemory = true;
2908 } else {
Chris Lattnerd3948112005-01-17 22:19:26 +00002909 // Do not serialize non-volatile loads against each other.
2910 Root = DAG.getRoot();
2911 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002912
Dan Gohman475871a2008-07-27 21:46:04 +00002913 SmallVector<SDValue, 4> Values(NumValues);
2914 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002915 MVT PtrVT = Ptr.getValueType();
2916 for (unsigned i = 0; i != NumValues; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00002917 SDValue L = DAG.getLoad(ValueVTs[i], Root,
Dan Gohman1d685a42008-06-07 02:02:36 +00002918 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2919 DAG.getConstant(Offsets[i], PtrVT)),
2920 SV, Offsets[i],
2921 isVolatile, Alignment);
2922 Values[i] = L;
2923 Chains[i] = L.getValue(1);
2924 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002925
Dan Gohman8b4588f2008-07-25 00:04:14 +00002926 if (!ConstantMemory) {
Dan Gohman475871a2008-07-27 21:46:04 +00002927 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
Dan Gohman8b4588f2008-07-25 00:04:14 +00002928 &Chains[0], NumValues);
2929 if (isVolatile)
2930 DAG.setRoot(Chain);
2931 else
2932 PendingLoads.push_back(Chain);
2933 }
Dan Gohman1d685a42008-06-07 02:02:36 +00002934
Duncan Sandsf9516202008-06-30 10:19:09 +00002935 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2936 &Values[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002937}
2938
2939
2940void SelectionDAGLowering::visitStore(StoreInst &I) {
2941 Value *SrcV = I.getOperand(0);
Dan Gohman1d685a42008-06-07 02:02:36 +00002942 Value *PtrV = I.getOperand(1);
Dan Gohman1d685a42008-06-07 02:02:36 +00002943
2944 SmallVector<MVT, 4> ValueVTs;
2945 SmallVector<uint64_t, 4> Offsets;
2946 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2947 unsigned NumValues = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002948 if (NumValues == 0)
2949 return;
Dan Gohman1d685a42008-06-07 02:02:36 +00002950
Dan Gohman90d33ee2008-07-30 18:36:51 +00002951 // Get the lowered operands. Note that we do this after
2952 // checking if NumResults is zero, because with zero results
2953 // the operands won't have values in the map.
2954 SDValue Src = getValue(SrcV);
2955 SDValue Ptr = getValue(PtrV);
2956
Dan Gohman475871a2008-07-27 21:46:04 +00002957 SDValue Root = getRoot();
2958 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002959 MVT PtrVT = Ptr.getValueType();
2960 bool isVolatile = I.isVolatile();
2961 unsigned Alignment = I.getAlignment();
2962 for (unsigned i = 0; i != NumValues; ++i)
Dan Gohman475871a2008-07-27 21:46:04 +00002963 Chains[i] = DAG.getStore(Root, SDValue(Src.Val, Src.ResNo + i),
Dan Gohman1d685a42008-06-07 02:02:36 +00002964 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2965 DAG.getConstant(Offsets[i], PtrVT)),
2966 PtrV, Offsets[i],
2967 isVolatile, Alignment);
2968
2969 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002970}
2971
Chris Lattner0eade312006-03-24 02:22:33 +00002972/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2973/// node.
2974void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2975 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002976 bool HasChain = !I.doesNotAccessMemory();
2977 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2978
Chris Lattner0eade312006-03-24 02:22:33 +00002979 // Build the operand list.
Dan Gohman475871a2008-07-27 21:46:04 +00002980 SmallVector<SDValue, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002981 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2982 if (OnlyLoad) {
2983 // We don't need to serialize loads against other loads.
2984 Ops.push_back(DAG.getRoot());
2985 } else {
2986 Ops.push_back(getRoot());
2987 }
2988 }
Chris Lattner0eade312006-03-24 02:22:33 +00002989
2990 // Add the intrinsic ID as an integer operand.
2991 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2992
2993 // Add all operands of the call to the operand list.
2994 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00002995 SDValue Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002996 assert(TLI.isTypeLegal(Op.getValueType()) &&
2997 "Intrinsic uses a non-legal type?");
2998 Ops.push_back(Op);
2999 }
3000
Duncan Sands83ec4b62008-06-06 12:08:01 +00003001 std::vector<MVT> VTs;
Chris Lattner0eade312006-03-24 02:22:33 +00003002 if (I.getType() != Type::VoidTy) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003003 MVT VT = TLI.getValueType(I.getType());
3004 if (VT.isVector()) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003005 const VectorType *DestTy = cast<VectorType>(I.getType());
Duncan Sands83ec4b62008-06-06 12:08:01 +00003006 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Chris Lattner0eade312006-03-24 02:22:33 +00003007
Duncan Sands83ec4b62008-06-06 12:08:01 +00003008 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
Chris Lattner0eade312006-03-24 02:22:33 +00003009 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
3010 }
3011
3012 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
3013 VTs.push_back(VT);
3014 }
3015 if (HasChain)
3016 VTs.push_back(MVT::Other);
3017
Duncan Sands83ec4b62008-06-06 12:08:01 +00003018 const MVT *VTList = DAG.getNodeValueTypes(VTs);
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003019
Chris Lattner0eade312006-03-24 02:22:33 +00003020 // Create the node.
Dan Gohman475871a2008-07-27 21:46:04 +00003021 SDValue Result;
Chris Lattner48b61a72006-03-28 00:40:33 +00003022 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003023 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
3024 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003025 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003026 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
3027 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003028 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003029 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
3030 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003031
Chris Lattnere58a7802006-04-02 03:41:14 +00003032 if (HasChain) {
Dan Gohman475871a2008-07-27 21:46:04 +00003033 SDValue Chain = Result.getValue(Result.Val->getNumValues()-1);
Chris Lattnere58a7802006-04-02 03:41:14 +00003034 if (OnlyLoad)
3035 PendingLoads.push_back(Chain);
3036 else
3037 DAG.setRoot(Chain);
3038 }
Chris Lattner0eade312006-03-24 02:22:33 +00003039 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003040 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003041 MVT VT = TLI.getValueType(PTy);
Dan Gohman7f321562007-06-25 16:23:39 +00003042 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00003043 }
3044 setValue(&I, Result);
3045 }
3046}
3047
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003048/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003049static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003050 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003051 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00003052 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003053 "TypeInfo must be a global variable or NULL");
3054 return GV;
3055}
3056
Duncan Sandsf4070822007-06-15 19:04:19 +00003057/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003058/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00003059static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3060 MachineBasicBlock *MBB) {
3061 // Inform the MachineModuleInfo of the personality for this landing pad.
3062 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3063 assert(CE->getOpcode() == Instruction::BitCast &&
3064 isa<Function>(CE->getOperand(0)) &&
3065 "Personality should be a function");
3066 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3067
3068 // Gather all the type infos for this landing pad and pass them along to
3069 // MachineModuleInfo.
3070 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003071 unsigned N = I.getNumOperands();
3072
3073 for (unsigned i = N - 1; i > 2; --i) {
3074 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3075 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00003076 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003077 assert (FirstCatch <= N && "Invalid filter length");
3078
3079 if (FirstCatch < N) {
3080 TyInfo.reserve(N - FirstCatch);
3081 for (unsigned j = FirstCatch; j < N; ++j)
3082 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3083 MMI->addCatchTypeInfo(MBB, TyInfo);
3084 TyInfo.clear();
3085 }
3086
Duncan Sands6590b042007-08-27 15:47:50 +00003087 if (!FilterLength) {
3088 // Cleanup.
3089 MMI->addCleanup(MBB);
3090 } else {
3091 // Filter.
3092 TyInfo.reserve(FilterLength - 1);
3093 for (unsigned j = i + 1; j < FirstCatch; ++j)
3094 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3095 MMI->addFilterTypeInfo(MBB, TyInfo);
3096 TyInfo.clear();
3097 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003098
3099 N = i;
3100 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003101 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003102
3103 if (N > 3) {
3104 TyInfo.reserve(N - 3);
3105 for (unsigned j = 3; j < N; ++j)
3106 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00003107 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003108 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003109}
3110
Mon P Wang63307c32008-05-05 19:05:59 +00003111
3112/// Inlined utility function to implement binary input atomic intrinsics for
3113// visitIntrinsicCall: I is a call instruction
3114// Op is the associated NodeType for I
3115const char *
3116SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Dan Gohman475871a2008-07-27 21:46:04 +00003117 SDValue Root = getRoot();
3118 SDValue L = DAG.getAtomic(Op, Root,
Mon P Wang63307c32008-05-05 19:05:59 +00003119 getValue(I.getOperand(1)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003120 getValue(I.getOperand(2)),
Mon P Wang28873102008-06-25 08:15:39 +00003121 I.getOperand(1));
Mon P Wang63307c32008-05-05 19:05:59 +00003122 setValue(&I, L);
3123 DAG.setRoot(L.getValue(1));
3124 return 0;
3125}
3126
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003127/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3128/// we want to emit this as a call to a named external function, return the name
3129/// otherwise lower it and return null.
3130const char *
3131SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3132 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00003133 default:
3134 // By default, turn this into a target intrinsic node.
3135 visitTargetIntrinsic(I, Intrinsic);
3136 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003137 case Intrinsic::vastart: visitVAStart(I); return 0;
3138 case Intrinsic::vaend: visitVAEnd(I); return 0;
3139 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00003140 case Intrinsic::returnaddress:
3141 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3142 getValue(I.getOperand(1))));
3143 return 0;
3144 case Intrinsic::frameaddress:
3145 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3146 getValue(I.getOperand(1))));
3147 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003148 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003149 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003150 break;
3151 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003152 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003153 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00003154 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003155 case Intrinsic::memcpy_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003156 SDValue Op1 = getValue(I.getOperand(1));
3157 SDValue Op2 = getValue(I.getOperand(2));
3158 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003159 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3160 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3161 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003162 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003163 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003164 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003165 case Intrinsic::memset_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003166 SDValue Op1 = getValue(I.getOperand(1));
3167 SDValue Op2 = getValue(I.getOperand(2));
3168 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003169 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3170 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3171 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003172 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003173 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003174 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003175 case Intrinsic::memmove_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003176 SDValue Op1 = getValue(I.getOperand(1));
3177 SDValue Op2 = getValue(I.getOperand(2));
3178 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003179 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3180
3181 // If the source and destination are known to not be aliases, we can
3182 // lower memmove as memcpy.
3183 uint64_t Size = -1ULL;
3184 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3185 Size = C->getValue();
3186 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3187 AliasAnalysis::NoAlias) {
3188 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3189 I.getOperand(1), 0, I.getOperand(2), 0));
3190 return 0;
3191 }
3192
3193 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3194 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003195 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003196 }
Chris Lattner86cb6432005-12-13 17:40:33 +00003197 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003198 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003199 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003200 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003201 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00003202 assert(DD && "Not a debug information descriptor");
Dan Gohman7f460202008-06-30 20:59:49 +00003203 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3204 SPI.getLine(),
3205 SPI.getColumn(),
3206 cast<CompileUnitDesc>(DD)));
Chris Lattner86cb6432005-12-13 17:40:33 +00003207 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003208
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003209 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00003210 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003211 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003212 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003213 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003214 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3215 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003216 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003217 }
3218
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003219 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003220 }
3221 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003222 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003223 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003224 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3225 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003226 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003227 }
3228
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003229 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003230 }
3231 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003232 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003233 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003234 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003235 Value *SP = FSI.getSubprogram();
3236 if (SP && MMI->Verify(SP)) {
3237 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3238 // what (most?) gdb expects.
3239 DebugInfoDesc *DD = MMI->getDescFor(SP);
3240 assert(DD && "Not a debug information descriptor");
3241 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3242 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
Dan Gohman99fe47b2008-06-30 22:21:03 +00003243 unsigned SrcFile = MMI->RecordSource(CompileUnit);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003244 // Record the source line but does create a label. It will be emitted
3245 // at asm emission time.
3246 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00003247 }
3248
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003249 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003250 }
3251 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003252 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003253 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003254 Value *Variable = DI.getVariable();
3255 if (MMI && Variable && MMI->Verify(Variable))
3256 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3257 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003258 return 0;
3259 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003260
Jim Laskeyb180aa12007-02-21 22:53:45 +00003261 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003262 if (!CurMBB->isLandingPad()) {
3263 // FIXME: Mark exception register as live in. Hack for PR1508.
3264 unsigned Reg = TLI.getExceptionAddressRegister();
3265 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003266 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003267 // Insert the EXCEPTIONADDR instruction.
3268 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003269 SDValue Ops[1];
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003270 Ops[0] = DAG.getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003271 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003272 setValue(&I, Op);
3273 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003274 return 0;
3275 }
3276
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003277 case Intrinsic::eh_selector_i32:
3278 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003279 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003280 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003281 MVT::i32 : MVT::i64);
3282
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003283 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003284 if (CurMBB->isLandingPad())
3285 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003286 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003287#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003288 FuncInfo.CatchInfoLost.insert(&I);
3289#endif
Duncan Sands90291952007-07-06 09:18:59 +00003290 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3291 unsigned Reg = TLI.getExceptionSelectorRegister();
3292 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003293 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003294
3295 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003296 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003297 SDValue Ops[2];
Jim Laskey735b6f82007-02-22 15:38:06 +00003298 Ops[0] = getValue(I.getOperand(1));
3299 Ops[1] = getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003300 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
Jim Laskey735b6f82007-02-22 15:38:06 +00003301 setValue(&I, Op);
3302 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003303 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003304 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003305 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003306
3307 return 0;
3308 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003309
3310 case Intrinsic::eh_typeid_for_i32:
3311 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003312 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003313 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003314 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003315
Jim Laskey735b6f82007-02-22 15:38:06 +00003316 if (MMI) {
3317 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003318 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003319
Jim Laskey735b6f82007-02-22 15:38:06 +00003320 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003321 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003322 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003323 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003324 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003325 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003326
3327 return 0;
3328 }
3329
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003330 case Intrinsic::eh_return: {
3331 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3332
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003333 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003334 MMI->setCallsEHReturn(true);
3335 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3336 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003337 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003338 getValue(I.getOperand(1)),
3339 getValue(I.getOperand(2))));
3340 } else {
3341 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3342 }
3343
3344 return 0;
3345 }
3346
3347 case Intrinsic::eh_unwind_init: {
3348 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3349 MMI->setCallsUnwindInit(true);
3350 }
3351
3352 return 0;
3353 }
3354
3355 case Intrinsic::eh_dwarf_cfa: {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003356 MVT VT = getValue(I.getOperand(1)).getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003357 SDValue CfaArg;
Duncan Sands8e4eb092008-06-08 20:54:56 +00003358 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003359 CfaArg = DAG.getNode(ISD::TRUNCATE,
3360 TLI.getPointerTy(), getValue(I.getOperand(1)));
3361 else
3362 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3363 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003364
Dan Gohman475871a2008-07-27 21:46:04 +00003365 SDValue Offset = DAG.getNode(ISD::ADD,
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003366 TLI.getPointerTy(),
3367 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3368 TLI.getPointerTy()),
3369 CfaArg);
3370 setValue(&I, DAG.getNode(ISD::ADD,
3371 TLI.getPointerTy(),
3372 DAG.getNode(ISD::FRAMEADDR,
3373 TLI.getPointerTy(),
3374 DAG.getConstant(0,
3375 TLI.getPointerTy())),
3376 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003377 return 0;
3378 }
3379
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003380 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003381 setValue(&I, DAG.getNode(ISD::FSQRT,
3382 getValue(I.getOperand(1)).getValueType(),
3383 getValue(I.getOperand(1))));
3384 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003385 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003386 setValue(&I, DAG.getNode(ISD::FPOWI,
3387 getValue(I.getOperand(1)).getValueType(),
3388 getValue(I.getOperand(1)),
3389 getValue(I.getOperand(2))));
3390 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003391 case Intrinsic::sin:
3392 setValue(&I, DAG.getNode(ISD::FSIN,
3393 getValue(I.getOperand(1)).getValueType(),
3394 getValue(I.getOperand(1))));
3395 return 0;
3396 case Intrinsic::cos:
3397 setValue(&I, DAG.getNode(ISD::FCOS,
3398 getValue(I.getOperand(1)).getValueType(),
3399 getValue(I.getOperand(1))));
3400 return 0;
3401 case Intrinsic::pow:
3402 setValue(&I, DAG.getNode(ISD::FPOW,
3403 getValue(I.getOperand(1)).getValueType(),
3404 getValue(I.getOperand(1)),
3405 getValue(I.getOperand(2))));
3406 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003407 case Intrinsic::pcmarker: {
Dan Gohman475871a2008-07-27 21:46:04 +00003408 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003409 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3410 return 0;
3411 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003412 case Intrinsic::readcyclecounter: {
Dan Gohman475871a2008-07-27 21:46:04 +00003413 SDValue Op = getRoot();
3414 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003415 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3416 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003417 setValue(&I, Tmp);
3418 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003419 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003420 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003421 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003422 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003423 assert(0 && "part_select intrinsic not implemented");
3424 abort();
3425 }
3426 case Intrinsic::part_set: {
3427 // Currently not implemented: just abort
3428 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003429 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003430 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003431 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003432 setValue(&I, DAG.getNode(ISD::BSWAP,
3433 getValue(I.getOperand(1)).getValueType(),
3434 getValue(I.getOperand(1))));
3435 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003436 case Intrinsic::cttz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003437 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003438 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003439 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003440 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003441 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003442 }
3443 case Intrinsic::ctlz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003444 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003445 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003446 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003447 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003448 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003449 }
3450 case Intrinsic::ctpop: {
Dan Gohman475871a2008-07-27 21:46:04 +00003451 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003452 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003453 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003454 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003455 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003456 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003457 case Intrinsic::stacksave: {
Dan Gohman475871a2008-07-27 21:46:04 +00003458 SDValue Op = getRoot();
3459 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003460 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003461 setValue(&I, Tmp);
3462 DAG.setRoot(Tmp.getValue(1));
3463 return 0;
3464 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003465 case Intrinsic::stackrestore: {
Dan Gohman475871a2008-07-27 21:46:04 +00003466 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner39a17dd2006-01-23 05:22:07 +00003467 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003468 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003469 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003470 case Intrinsic::var_annotation:
3471 // Discard annotate attributes
3472 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003473
Duncan Sands36397f52007-07-27 12:58:54 +00003474 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003475 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003476
Dan Gohman475871a2008-07-27 21:46:04 +00003477 SDValue Ops[6];
Duncan Sands36397f52007-07-27 12:58:54 +00003478 Ops[0] = getRoot();
3479 Ops[1] = getValue(I.getOperand(1));
3480 Ops[2] = getValue(I.getOperand(2));
3481 Ops[3] = getValue(I.getOperand(3));
3482 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3483 Ops[5] = DAG.getSrcValue(F);
3484
Dan Gohman475871a2008-07-27 21:46:04 +00003485 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
Duncan Sandsf7331b32007-09-11 14:10:23 +00003486 DAG.getNodeValueTypes(TLI.getPointerTy(),
3487 MVT::Other), 2,
3488 Ops, 6);
3489
3490 setValue(&I, Tmp);
3491 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003492 return 0;
3493 }
Gordon Henriksence224772008-01-07 01:30:38 +00003494
3495 case Intrinsic::gcroot:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003496 if (GFI) {
Gordon Henriksence224772008-01-07 01:30:38 +00003497 Value *Alloca = I.getOperand(1);
3498 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3499
3500 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003501 GFI->addStackRoot(FI->getIndex(), TypeMap);
Gordon Henriksence224772008-01-07 01:30:38 +00003502 }
3503 return 0;
3504
3505 case Intrinsic::gcread:
3506 case Intrinsic::gcwrite:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003507 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
Gordon Henriksence224772008-01-07 01:30:38 +00003508 return 0;
3509
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003510 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003511 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003512 return 0;
3513 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003514
3515 case Intrinsic::trap: {
3516 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3517 return 0;
3518 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003519 case Intrinsic::prefetch: {
Dan Gohman475871a2008-07-27 21:46:04 +00003520 SDValue Ops[4];
Evan Cheng27b7db52008-03-08 00:58:38 +00003521 Ops[0] = getRoot();
3522 Ops[1] = getValue(I.getOperand(1));
3523 Ops[2] = getValue(I.getOperand(2));
3524 Ops[3] = getValue(I.getOperand(3));
3525 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3526 return 0;
3527 }
3528
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003529 case Intrinsic::memory_barrier: {
Dan Gohman475871a2008-07-27 21:46:04 +00003530 SDValue Ops[6];
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003531 Ops[0] = getRoot();
3532 for (int x = 1; x < 6; ++x)
3533 Ops[x] = getValue(I.getOperand(x));
3534
3535 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3536 return 0;
3537 }
Mon P Wang28873102008-06-25 08:15:39 +00003538 case Intrinsic::atomic_cmp_swap: {
Dan Gohman475871a2008-07-27 21:46:04 +00003539 SDValue Root = getRoot();
3540 SDValue L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, Root,
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003541 getValue(I.getOperand(1)),
3542 getValue(I.getOperand(2)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003543 getValue(I.getOperand(3)),
Mon P Wang28873102008-06-25 08:15:39 +00003544 I.getOperand(1));
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003545 setValue(&I, L);
3546 DAG.setRoot(L.getValue(1));
3547 return 0;
3548 }
Mon P Wang28873102008-06-25 08:15:39 +00003549 case Intrinsic::atomic_load_add:
3550 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
3551 case Intrinsic::atomic_load_sub:
3552 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Mon P Wang63307c32008-05-05 19:05:59 +00003553 case Intrinsic::atomic_load_and:
3554 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3555 case Intrinsic::atomic_load_or:
3556 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3557 case Intrinsic::atomic_load_xor:
3558 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Andrew Lenharth507a58a2008-06-14 05:48:15 +00003559 case Intrinsic::atomic_load_nand:
3560 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Mon P Wang63307c32008-05-05 19:05:59 +00003561 case Intrinsic::atomic_load_min:
3562 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3563 case Intrinsic::atomic_load_max:
3564 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3565 case Intrinsic::atomic_load_umin:
3566 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3567 case Intrinsic::atomic_load_umax:
3568 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3569 case Intrinsic::atomic_swap:
3570 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003571 }
3572}
3573
3574
Dan Gohman475871a2008-07-27 21:46:04 +00003575void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003576 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003577 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003578 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003579 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003580 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3581 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003582
Jim Laskey735b6f82007-02-22 15:38:06 +00003583 TargetLowering::ArgListTy Args;
3584 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003585 Args.reserve(CS.arg_size());
3586 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3587 i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003588 SDValue ArgNode = getValue(*i);
Duncan Sands6f74b482007-12-19 09:48:52 +00003589 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003590
Duncan Sands6f74b482007-12-19 09:48:52 +00003591 unsigned attrInd = i - CS.arg_begin() + 1;
3592 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3593 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3594 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3595 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3596 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3597 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003598 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003599 Args.push_back(Entry);
3600 }
3601
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003602 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003603 // Insert a label before the invoke call to mark the try range. This can be
3604 // used to detect deletion of the invoke via the MachineModuleInfo.
3605 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003606 // Both PendingLoads and PendingExports must be flushed here;
3607 // this call might not return.
3608 (void)getRoot();
Dan Gohman44066042008-07-01 00:05:16 +00003609 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003610 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003611
Dan Gohman475871a2008-07-27 21:46:04 +00003612 std::pair<SDValue,SDValue> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003613 TLI.LowerCallTo(getRoot(), CS.getType(),
3614 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003615 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003616 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003617 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003618 if (CS.getType() != Type::VoidTy)
3619 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003620 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003621
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003622 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003623 // Insert a label at the end of the invoke call to mark the try range. This
3624 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3625 EndLabel = MMI->NextLabelID();
Dan Gohman44066042008-07-01 00:05:16 +00003626 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003627
Duncan Sands6f74b482007-12-19 09:48:52 +00003628 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003629 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3630 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003631}
3632
3633
Chris Lattner1c08c712005-01-07 07:47:53 +00003634void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003635 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003636 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003637 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003638 if (unsigned IID = F->getIntrinsicID()) {
3639 RenameFn = visitIntrinsicCall(I, IID);
3640 if (!RenameFn)
3641 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003642 }
3643 }
3644
3645 // Check for well-known libc/libm calls. If the function is internal, it
3646 // can't be a library call.
3647 unsigned NameLen = F->getNameLen();
3648 if (!F->hasInternalLinkage() && NameLen) {
3649 const char *NameStr = F->getNameStart();
3650 if (NameStr[0] == 'c' &&
3651 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3652 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3653 if (I.getNumOperands() == 3 && // Basic sanity checks.
3654 I.getOperand(1)->getType()->isFloatingPoint() &&
3655 I.getType() == I.getOperand(1)->getType() &&
3656 I.getType() == I.getOperand(2)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003657 SDValue LHS = getValue(I.getOperand(1));
3658 SDValue RHS = getValue(I.getOperand(2));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003659 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3660 LHS, RHS));
3661 return;
3662 }
3663 } else if (NameStr[0] == 'f' &&
3664 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003665 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3666 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003667 if (I.getNumOperands() == 2 && // Basic sanity checks.
3668 I.getOperand(1)->getType()->isFloatingPoint() &&
3669 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003670 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003671 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3672 return;
3673 }
3674 } else if (NameStr[0] == 's' &&
3675 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003676 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3677 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003678 if (I.getNumOperands() == 2 && // Basic sanity checks.
3679 I.getOperand(1)->getType()->isFloatingPoint() &&
3680 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003681 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003682 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3683 return;
3684 }
3685 } else if (NameStr[0] == 'c' &&
3686 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003687 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3688 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003689 if (I.getNumOperands() == 2 && // Basic sanity checks.
3690 I.getOperand(1)->getType()->isFloatingPoint() &&
3691 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003692 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003693 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3694 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003695 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003696 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003697 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003698 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003699 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003700 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003701 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003702
Dan Gohman475871a2008-07-27 21:46:04 +00003703 SDValue Callee;
Chris Lattner64e14b12005-01-08 22:48:57 +00003704 if (!RenameFn)
3705 Callee = getValue(I.getOperand(0));
3706 else
3707 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003708
Duncan Sands6f74b482007-12-19 09:48:52 +00003709 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003710}
3711
Jim Laskey735b6f82007-02-22 15:38:06 +00003712
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003713/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3714/// this value and returns the result as a ValueVT value. This uses
3715/// Chain/Flag as the input and updates them for the output Chain/Flag.
3716/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00003717SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3718 SDValue &Chain,
3719 SDValue *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003720 // Assemble the legal parts into the final values.
Dan Gohman475871a2008-07-27 21:46:04 +00003721 SmallVector<SDValue, 4> Values(ValueVTs.size());
3722 SmallVector<SDValue, 8> Parts;
Chris Lattner6833b062008-04-28 07:16:35 +00003723 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003724 // Copy the legal parts from the registers.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003725 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003726 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003727 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003728
Chris Lattner6833b062008-04-28 07:16:35 +00003729 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003730 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003731 SDValue P;
Chris Lattner6833b062008-04-28 07:16:35 +00003732 if (Flag == 0)
3733 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3734 else {
3735 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003736 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003737 }
3738 Chain = P.getValue(1);
Chris Lattneread0d882008-06-17 06:09:18 +00003739
3740 // If the source register was virtual and if we know something about it,
3741 // add an assert node.
3742 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
3743 RegisterVT.isInteger() && !RegisterVT.isVector()) {
3744 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
3745 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
3746 if (FLI.LiveOutRegInfo.size() > SlotNo) {
3747 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
3748
3749 unsigned RegSize = RegisterVT.getSizeInBits();
3750 unsigned NumSignBits = LOI.NumSignBits;
3751 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
3752
3753 // FIXME: We capture more information than the dag can represent. For
3754 // now, just use the tightest assertzext/assertsext possible.
3755 bool isSExt = true;
3756 MVT FromVT(MVT::Other);
3757 if (NumSignBits == RegSize)
3758 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
3759 else if (NumZeroBits >= RegSize-1)
3760 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
3761 else if (NumSignBits > RegSize-8)
3762 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
3763 else if (NumZeroBits >= RegSize-9)
3764 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
3765 else if (NumSignBits > RegSize-16)
3766 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
3767 else if (NumZeroBits >= RegSize-17)
3768 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
3769 else if (NumSignBits > RegSize-32)
3770 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
3771 else if (NumZeroBits >= RegSize-33)
3772 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
3773
3774 if (FromVT != MVT::Other) {
3775 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
3776 RegisterVT, P, DAG.getValueType(FromVT));
3777
3778 }
3779 }
3780 }
3781
Dan Gohman23ce5022008-04-25 18:27:55 +00003782 Parts[Part+i] = P;
3783 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003784
Dan Gohman23ce5022008-04-25 18:27:55 +00003785 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3786 ValueVT);
3787 Part += NumRegs;
3788 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00003789
Duncan Sandsf9516202008-06-30 10:19:09 +00003790 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3791 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003792}
3793
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003794/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3795/// specified value into the registers specified by this object. This uses
3796/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003797/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00003798void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
3799 SDValue &Chain, SDValue *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003800 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003801 unsigned NumRegs = Regs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00003802 SmallVector<SDValue, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003803 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003804 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003805 unsigned NumParts = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003806 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003807
3808 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3809 &Parts[Part], NumParts, RegisterVT);
3810 Part += NumParts;
3811 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003812
3813 // Copy the parts into the registers.
Dan Gohman475871a2008-07-27 21:46:04 +00003814 SmallVector<SDValue, 8> Chains(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003815 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003816 SDValue Part;
Chris Lattner6833b062008-04-28 07:16:35 +00003817 if (Flag == 0)
3818 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3819 else {
3820 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003821 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003822 }
3823 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003824 }
Chris Lattner6833b062008-04-28 07:16:35 +00003825
Evan Cheng33bf38a2008-04-28 22:07:13 +00003826 if (NumRegs == 1 || Flag)
3827 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3828 // flagged to it. That is the CopyToReg nodes and the user are considered
3829 // a single scheduling unit. If we create a TokenFactor and return it as
3830 // chain, then the TokenFactor is both a predecessor (operand) of the
3831 // user as well as a successor (the TF operands are flagged to the user).
3832 // c1, f1 = CopyToReg
3833 // c2, f2 = CopyToReg
3834 // c3 = TokenFactor c1, c2
3835 // ...
3836 // = op c3, ..., f2
3837 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003838 else
3839 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003840}
Chris Lattner864635a2006-02-22 22:37:12 +00003841
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003842/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3843/// operand list. This adds the code marker and includes the number of
3844/// values added into it.
3845void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00003846 std::vector<SDValue> &Ops) const {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003847 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner4b993b12007-04-09 00:33:58 +00003848 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003849 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3850 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003851 MVT RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003852 for (unsigned i = 0; i != NumRegs; ++i)
3853 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003854 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003855}
Chris Lattner864635a2006-02-22 22:37:12 +00003856
3857/// isAllocatableRegister - If the specified register is safe to allocate,
3858/// i.e. it isn't a stack pointer or some other special register, return the
3859/// register class for the register. Otherwise, return null.
3860static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003861isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003862 const TargetLowering &TLI,
3863 const TargetRegisterInfo *TRI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003864 MVT FoundVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003865 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003866 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3867 E = TRI->regclass_end(); RCI != E; ++RCI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003868 MVT ThisVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003869
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003870 const TargetRegisterClass *RC = *RCI;
3871 // If none of the the value types for this register class are valid, we
3872 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003873 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3874 I != E; ++I) {
3875 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003876 // If we have already found this register in a different register class,
3877 // choose the one with the largest VT specified. For example, on
3878 // PowerPC, we favor f64 register classes over f32.
Duncan Sands8e4eb092008-06-08 20:54:56 +00003879 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003880 ThisVT = *I;
3881 break;
3882 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003883 }
3884 }
3885
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003886 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003887
Chris Lattner864635a2006-02-22 22:37:12 +00003888 // NOTE: This isn't ideal. In particular, this might allocate the
3889 // frame pointer in functions that need it (due to them not being taken
3890 // out of allocation, because a variable sized allocation hasn't been seen
3891 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003892 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3893 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003894 if (*I == Reg) {
3895 // We found a matching register class. Keep looking at others in case
3896 // we find one with larger registers that this physreg is also in.
3897 FoundRC = RC;
3898 FoundVT = ThisVT;
3899 break;
3900 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003901 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003902 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003903}
3904
Chris Lattner4e4b5762006-02-01 18:59:47 +00003905
Chris Lattner0c583402007-04-28 20:49:53 +00003906namespace {
3907/// AsmOperandInfo - This contains information for each constraint that we are
3908/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003909struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3910 /// CallOperand - If this is the result output operand or a clobber
3911 /// this is null, otherwise it is the incoming operand to the CallInst.
3912 /// This gets modified as the asm is processed.
Dan Gohman475871a2008-07-27 21:46:04 +00003913 SDValue CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003914
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003915 /// AssignedRegs - If this is a register or register class operand, this
3916 /// contains the set of register corresponding to the operand.
3917 RegsForValue AssignedRegs;
3918
Dan Gohman23ce5022008-04-25 18:27:55 +00003919 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003920 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003921 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003922
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003923 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3924 /// busy in OutputRegs/InputRegs.
3925 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3926 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003927 std::set<unsigned> &InputRegs,
3928 const TargetRegisterInfo &TRI) const {
3929 if (isOutReg) {
3930 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3931 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3932 }
3933 if (isInReg) {
3934 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3935 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3936 }
3937 }
3938
3939private:
3940 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3941 /// specified set.
3942 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3943 const TargetRegisterInfo &TRI) {
3944 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3945 Regs.insert(Reg);
3946 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3947 for (; *Aliases; ++Aliases)
3948 Regs.insert(*Aliases);
3949 }
Chris Lattner0c583402007-04-28 20:49:53 +00003950};
3951} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003952
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003953
Chris Lattner0fe71e92008-02-21 19:43:13 +00003954/// GetRegistersForValue - Assign registers (virtual or physical) for the
3955/// specified operand. We prefer to assign virtual registers, to allow the
3956/// register allocator handle the assignment process. However, if the asm uses
3957/// features that we can't model on machineinstrs, we have SDISel do the
3958/// allocation. This produces generally horrible, but correct, code.
3959///
3960/// OpInfo describes the operand.
3961/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3962/// or any explicitly clobbered registers.
3963/// Input and OutputRegs are the set of already allocated physical registers.
3964///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003965void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003966GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003967 std::set<unsigned> &OutputRegs,
3968 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003969 // Compute whether this value requires an input register, an output register,
3970 // or both.
3971 bool isOutReg = false;
3972 bool isInReg = false;
3973 switch (OpInfo.Type) {
3974 case InlineAsm::isOutput:
3975 isOutReg = true;
3976
3977 // If this is an early-clobber output, or if there is an input
3978 // constraint that matches this, we need to reserve the input register
3979 // so no other inputs allocate to it.
3980 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3981 break;
3982 case InlineAsm::isInput:
3983 isInReg = true;
3984 isOutReg = false;
3985 break;
3986 case InlineAsm::isClobber:
3987 isOutReg = true;
3988 isInReg = true;
3989 break;
3990 }
3991
3992
3993 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003994 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003995
3996 // If this is a constraint for a single physreg, or a constraint for a
3997 // register class, find it.
3998 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3999 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4000 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004001
4002 unsigned NumRegs = 1;
4003 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00004004 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004005 MVT RegVT;
4006 MVT ValueVT = OpInfo.ConstraintVT;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004007
Chris Lattnerbf996f12007-04-30 17:29:31 +00004008
4009 // If this is a constraint for a specific physical register, like {r17},
4010 // assign it now.
4011 if (PhysReg.first) {
4012 if (OpInfo.ConstraintVT == MVT::Other)
4013 ValueVT = *PhysReg.second->vt_begin();
4014
4015 // Get the actual register value type. This is important, because the user
4016 // may have asked for (e.g.) the AX register in i32 type. We need to
4017 // remember that AX is actually i16 to get the right extension.
4018 RegVT = *PhysReg.second->vt_begin();
4019
4020 // This is a explicit reference to a physical register.
4021 Regs.push_back(PhysReg.first);
4022
4023 // If this is an expanded reference, add the rest of the regs to Regs.
4024 if (NumRegs != 1) {
4025 TargetRegisterClass::iterator I = PhysReg.second->begin();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004026 for (; *I != PhysReg.first; ++I)
Evan Cheng50871242008-05-14 20:07:51 +00004027 assert(I != PhysReg.second->end() && "Didn't find reg!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004028
4029 // Already added the first reg.
4030 --NumRegs; ++I;
4031 for (; NumRegs; --NumRegs, ++I) {
Evan Cheng50871242008-05-14 20:07:51 +00004032 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004033 Regs.push_back(*I);
4034 }
4035 }
Dan Gohman23ce5022008-04-25 18:27:55 +00004036 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004037 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4038 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004039 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004040 }
4041
4042 // Otherwise, if this was a reference to an LLVM register class, create vregs
4043 // for this reference.
4044 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004045 const TargetRegisterClass *RC = PhysReg.second;
4046 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004047 // If this is an early clobber or tied register, our regalloc doesn't know
4048 // how to maintain the constraint. If it isn't, go ahead and create vreg
4049 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004050 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4051 // If there is some other early clobber and this is an input register,
4052 // then we are forced to pre-allocate the input reg so it doesn't
4053 // conflict with the earlyclobber.
4054 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004055 RegVT = *PhysReg.second->vt_begin();
4056
4057 if (OpInfo.ConstraintVT == MVT::Other)
4058 ValueVT = RegVT;
4059
4060 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00004061 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004062 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00004063 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00004064
Dan Gohman23ce5022008-04-25 18:27:55 +00004065 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004066 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004067 }
4068
4069 // Otherwise, we can't allocate it. Let the code below figure out how to
4070 // maintain these constraints.
4071 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4072
4073 } else {
4074 // This is a reference to a register class that doesn't directly correspond
4075 // to an LLVM register class. Allocate NumRegs consecutive, available,
4076 // registers from the class.
4077 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4078 OpInfo.ConstraintVT);
4079 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004080
Dan Gohman6f0d0242008-02-10 18:45:23 +00004081 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004082 unsigned NumAllocated = 0;
4083 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4084 unsigned Reg = RegClassRegs[i];
4085 // See if this register is available.
4086 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4087 (isInReg && InputRegs.count(Reg))) { // Already used.
4088 // Make sure we find consecutive registers.
4089 NumAllocated = 0;
4090 continue;
4091 }
4092
4093 // Check to see if this register is allocatable (i.e. don't give out the
4094 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004095 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00004096 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004097 if (!RC) { // Couldn't allocate this register.
4098 // Reset NumAllocated to make sure we return consecutive registers.
4099 NumAllocated = 0;
4100 continue;
4101 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00004102 }
4103
4104 // Okay, this register is good, we can use it.
4105 ++NumAllocated;
4106
4107 // If we allocated enough consecutive registers, succeed.
4108 if (NumAllocated == NumRegs) {
4109 unsigned RegStart = (i-NumAllocated)+1;
4110 unsigned RegEnd = i+1;
4111 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004112 for (unsigned i = RegStart; i != RegEnd; ++i)
4113 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004114
Dan Gohman23ce5022008-04-25 18:27:55 +00004115 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004116 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004117 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004118 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004119 }
4120 }
4121
4122 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00004123}
4124
4125
Chris Lattnerce7518c2006-01-26 22:24:51 +00004126/// visitInlineAsm - Handle a call to an InlineAsm object.
4127///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004128void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4129 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004130
Chris Lattner0c583402007-04-28 20:49:53 +00004131 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00004132 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004133
Dan Gohman475871a2008-07-27 21:46:04 +00004134 SDValue Chain = getRoot();
4135 SDValue Flag;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004136
Chris Lattner4e4b5762006-02-01 18:59:47 +00004137 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004138
Chris Lattner0c583402007-04-28 20:49:53 +00004139 // Do a prepass over the constraints, canonicalizing them, and building up the
4140 // ConstraintOperands list.
4141 std::vector<InlineAsm::ConstraintInfo>
4142 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004143
4144 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4145 // constraint. If so, we can't let the register allocator allocate any input
4146 // registers, because it will not know to avoid the earlyclobbered output reg.
4147 bool SawEarlyClobber = false;
4148
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004149 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00004150 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00004151 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004152 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4153 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00004154
Duncan Sands83ec4b62008-06-06 12:08:01 +00004155 MVT OpVT = MVT::Other;
Chris Lattner0c583402007-04-28 20:49:53 +00004156
4157 // Compute the value type for each operand.
4158 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00004159 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00004160 // Indirect outputs just consume an argument.
4161 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004162 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00004163 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004164 }
Chris Lattneracf8b012008-04-27 23:44:28 +00004165 // The return value of the call is this value. As such, there is no
4166 // corresponding argument.
4167 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4168 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4169 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4170 } else {
4171 assert(ResNo == 0 && "Asm only has one result!");
4172 OpVT = TLI.getValueType(CS.getType());
4173 }
4174 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004175 break;
4176 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004177 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00004178 break;
4179 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00004180 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00004181 break;
4182 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004183
Chris Lattner0c583402007-04-28 20:49:53 +00004184 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004185 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00004186 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00004187 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4188 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004189 else {
4190 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4191 const Type *OpTy = OpInfo.CallOperandVal->getType();
4192 // If this is an indirect operand, the operand is a pointer to the
4193 // accessed type.
4194 if (OpInfo.isIndirect)
4195 OpTy = cast<PointerType>(OpTy)->getElementType();
4196
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004197 // If OpTy is not a single value, it may be a struct/union that we
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004198 // can tile with integers.
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004199 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004200 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4201 switch (BitSize) {
4202 default: break;
4203 case 1:
4204 case 8:
4205 case 16:
4206 case 32:
4207 case 64:
4208 OpTy = IntegerType::get(BitSize);
4209 break;
4210 }
Chris Lattner6995cf62007-04-29 18:58:03 +00004211 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004212
4213 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00004214 }
4215 }
4216
4217 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00004218
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004219 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00004220 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00004221
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004222 // Keep track of whether we see an earlyclobber.
4223 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004224
Chris Lattner0fe71e92008-02-21 19:43:13 +00004225 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00004226 if (!SawEarlyClobber &&
4227 OpInfo.Type == InlineAsm::isClobber &&
4228 OpInfo.ConstraintType == TargetLowering::C_Register) {
4229 // Note that we want to ignore things that we don't trick here, like
4230 // dirflag, fpsr, flags, etc.
4231 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4232 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4233 OpInfo.ConstraintVT);
4234 if (PhysReg.first || PhysReg.second) {
4235 // This is a register we know of.
4236 SawEarlyClobber = true;
4237 }
4238 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00004239
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004240 // If this is a memory input, and if the operand is not indirect, do what we
4241 // need to to provide an address for the memory input.
4242 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4243 !OpInfo.isIndirect) {
4244 assert(OpInfo.Type == InlineAsm::isInput &&
4245 "Can only indirectify direct input operands!");
4246
4247 // Memory operands really want the address of the value. If we don't have
4248 // an indirect input, put it in the constpool if we can, otherwise spill
4249 // it to a stack slot.
4250
4251 // If the operand is a float, integer, or vector constant, spill to a
4252 // constant pool entry to get its address.
4253 Value *OpVal = OpInfo.CallOperandVal;
4254 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4255 isa<ConstantVector>(OpVal)) {
4256 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4257 TLI.getPointerTy());
4258 } else {
4259 // Otherwise, create a stack slot and emit a store to it before the
4260 // asm.
4261 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00004262 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004263 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4264 MachineFunction &MF = DAG.getMachineFunction();
4265 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
Dan Gohman475871a2008-07-27 21:46:04 +00004266 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004267 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4268 OpInfo.CallOperand = StackSlot;
4269 }
4270
4271 // There is no longer a Value* corresponding to this operand.
4272 OpInfo.CallOperandVal = 0;
4273 // It is now an indirect operand.
4274 OpInfo.isIndirect = true;
4275 }
4276
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004277 // If this constraint is for a specific register, allocate it before
4278 // anything else.
4279 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4280 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004281 }
Chris Lattner0c583402007-04-28 20:49:53 +00004282 ConstraintInfos.clear();
4283
4284
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004285 // Second pass - Loop over all of the operands, assigning virtual or physregs
4286 // to registerclass operands.
4287 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004288 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004289
4290 // C_Register operands have already been allocated, Other/Memory don't need
4291 // to be.
4292 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4293 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4294 }
4295
Chris Lattner0c583402007-04-28 20:49:53 +00004296 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
Dan Gohman475871a2008-07-27 21:46:04 +00004297 std::vector<SDValue> AsmNodeOperands;
4298 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
Chris Lattner0c583402007-04-28 20:49:53 +00004299 AsmNodeOperands.push_back(
4300 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4301
Chris Lattner2cc2f662006-02-01 01:28:23 +00004302
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004303 // Loop over all of the inputs, copying the operand values into the
4304 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004305 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004306
Chris Lattner0c583402007-04-28 20:49:53 +00004307 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4308 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4309
4310 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004311 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004312
Chris Lattner0c583402007-04-28 20:49:53 +00004313 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004314 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004315 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4316 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004317 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004318 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004319
Chris Lattner22873462006-02-27 23:45:39 +00004320 // Add information to the INLINEASM node to know about this output.
4321 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004322 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4323 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004324 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004325 break;
4326 }
4327
Chris Lattner2a600be2007-04-28 21:01:43 +00004328 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004329
Chris Lattner864635a2006-02-22 22:37:12 +00004330 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004331 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004332 if (OpInfo.AssignedRegs.Regs.empty()) {
Duncan Sandsa47c6c32008-06-17 03:24:13 +00004333 cerr << "Couldn't allocate output reg for constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004334 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004335 exit(1);
4336 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004337
Chris Lattner41f62592008-04-29 04:29:54 +00004338 // If this is an indirect operand, store through the pointer after the
4339 // asm.
4340 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004341 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004342 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004343 } else {
4344 // This is the result value of the call.
4345 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4346 // Concatenate this output onto the outputs list.
4347 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004348 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004349
4350 // Add information to the INLINEASM node to know that this register is
4351 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004352 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4353 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004354 break;
4355 }
4356 case InlineAsm::isInput: {
Dan Gohman475871a2008-07-27 21:46:04 +00004357 SDValue InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004358
Chris Lattner0c583402007-04-28 20:49:53 +00004359 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004360 // If this is required to match an output register we have already set,
4361 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004362 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004363
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004364 // Scan until we find the definition we already emitted of this operand.
4365 // When we find it, create a RegsForValue operand.
4366 unsigned CurOp = 2; // The first operand.
4367 for (; OperandNo; --OperandNo) {
4368 // Advance to the next operand.
4369 unsigned NumOps =
4370 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004371 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4372 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004373 "Skipped past definitions?");
4374 CurOp += (NumOps>>3)+1;
4375 }
4376
4377 unsigned NumOps =
4378 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004379 if ((NumOps & 7) == 2 /*REGDEF*/) {
4380 // Add NumOps>>3 registers to MatchedRegs.
4381 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004382 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004383 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4384 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004385 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4386 unsigned Reg =
4387 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4388 MatchedRegs.Regs.push_back(Reg);
4389 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004390
Chris Lattner527fae12007-02-01 01:21:12 +00004391 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004392 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004393 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4394 break;
4395 } else {
4396 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004397 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4398 // Add information to the INLINEASM node to know about this input.
4399 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4400 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4401 TLI.getPointerTy()));
4402 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4403 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004404 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004405 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004406
Chris Lattner2a600be2007-04-28 21:01:43 +00004407 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004408 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004409 "Don't know how to handle indirect other inputs yet!");
4410
Dan Gohman475871a2008-07-27 21:46:04 +00004411 std::vector<SDValue> Ops;
Chris Lattner48884cd2007-08-25 00:47:38 +00004412 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4413 Ops, DAG);
4414 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004415 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004416 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004417 exit(1);
4418 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004419
4420 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004421 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004422 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4423 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004424 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004425 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004426 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004427 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004428 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4429 "Memory operands expect pointer values");
4430
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004431 // Add information to the INLINEASM node to know about this input.
4432 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004433 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4434 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004435 AsmNodeOperands.push_back(InOperandVal);
4436 break;
4437 }
4438
Chris Lattner2a600be2007-04-28 21:01:43 +00004439 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4440 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4441 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004442 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004443 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004444
4445 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004446 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4447 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004448
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004449 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004450
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004451 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4452 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004453 break;
4454 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004455 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004456 // Add the clobbered value to the operand list, so that the register
4457 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004458 if (!OpInfo.AssignedRegs.Regs.empty())
4459 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4460 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004461 break;
4462 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004463 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004464 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004465
4466 // Finish up input operands.
4467 AsmNodeOperands[0] = Chain;
4468 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4469
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004470 Chain = DAG.getNode(ISD::INLINEASM,
4471 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004472 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004473 Flag = Chain.getValue(1);
4474
Chris Lattner6656dd12006-01-31 02:03:41 +00004475 // If this asm returns a register value, copy the result from that register
4476 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004477 if (!RetValRegs.Regs.empty()) {
Dan Gohman475871a2008-07-27 21:46:04 +00004478 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004479
4480 // If any of the results of the inline asm is a vector, it may have the
4481 // wrong width/num elts. This can happen for register classes that can
4482 // contain multiple different value types. The preg or vreg allocated may
4483 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004484 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004485 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4486 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004487 if (Val.Val->getValueType(i).isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004488 Val = DAG.getNode(ISD::BIT_CONVERT,
4489 TLI.getValueType(ResSTy->getElementType(i)), Val);
4490 }
4491 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004492 if (Val.getValueType().isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004493 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4494 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004495 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004496
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004497 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004498 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004499
Dan Gohman475871a2008-07-27 21:46:04 +00004500 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Chris Lattner6656dd12006-01-31 02:03:41 +00004501
4502 // Process indirect outputs, first output all of the flagged copies out of
4503 // physregs.
4504 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004505 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004506 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohman475871a2008-07-27 21:46:04 +00004507 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004508 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004509 }
4510
4511 // Emit the non-flagged stores from the physregs.
Dan Gohman475871a2008-07-27 21:46:04 +00004512 SmallVector<SDValue, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004513 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004514 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004515 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004516 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004517 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004518 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4519 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004520 DAG.setRoot(Chain);
4521}
4522
4523
Chris Lattner1c08c712005-01-07 07:47:53 +00004524void SelectionDAGLowering::visitMalloc(MallocInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004525 SDValue Src = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00004526
Duncan Sands83ec4b62008-06-06 12:08:01 +00004527 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004528
Duncan Sands8e4eb092008-06-08 20:54:56 +00004529 if (IntPtr.bitsLT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004530 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
Duncan Sands8e4eb092008-06-08 20:54:56 +00004531 else if (IntPtr.bitsGT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004532 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004533
4534 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004535 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004536 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004537 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004538
Reid Spencer47857812006-12-31 05:55:36 +00004539 TargetLowering::ArgListTy Args;
4540 TargetLowering::ArgListEntry Entry;
4541 Entry.Node = Src;
4542 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004543 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004544
Dan Gohman475871a2008-07-27 21:46:04 +00004545 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004546 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4547 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004548 setValue(&I, Result.first); // Pointers always fit in registers
4549 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004550}
4551
4552void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004553 TargetLowering::ArgListTy Args;
4554 TargetLowering::ArgListEntry Entry;
4555 Entry.Node = getValue(I.getOperand(0));
4556 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004557 Args.push_back(Entry);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004558 MVT IntPtr = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00004559 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004560 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4561 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004562 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4563 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004564}
4565
Evan Chengff9b3732008-01-30 18:18:23 +00004566// EmitInstrWithCustomInserter - This method should be implemented by targets
4567// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004568// instructions are special in various ways, which require special support to
4569// insert. The specified MachineInstr is created but not inserted into any
4570// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004571MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004572 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004573 cerr << "If a target marks an instruction with "
4574 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004575 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004576 abort();
4577 return 0;
4578}
4579
Chris Lattner39ae3622005-01-09 00:00:49 +00004580void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004581 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4582 getValue(I.getOperand(1)),
4583 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004584}
4585
4586void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004587 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
Nate Begemanacc398c2006-01-25 18:21:52 +00004588 getValue(I.getOperand(0)),
4589 DAG.getSrcValue(I.getOperand(0)));
4590 setValue(&I, V);
4591 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004592}
4593
4594void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004595 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4596 getValue(I.getOperand(1)),
4597 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004598}
4599
4600void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004601 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4602 getValue(I.getOperand(1)),
4603 getValue(I.getOperand(2)),
4604 DAG.getSrcValue(I.getOperand(1)),
4605 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004606}
4607
Chris Lattnerfdfded52006-04-12 16:20:43 +00004608/// TargetLowering::LowerArguments - This is the default LowerArguments
4609/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004610/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4611/// integrated into SDISel.
Dan Gohmana44b6742008-06-30 20:31:15 +00004612void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00004613 SmallVectorImpl<SDValue> &ArgValues) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004614 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
Dan Gohman475871a2008-07-27 21:46:04 +00004615 SmallVector<SDValue, 3+16> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004616 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004617 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4618 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4619
4620 // Add one result value for each formal argument.
Dan Gohmana44b6742008-06-30 20:31:15 +00004621 SmallVector<MVT, 16> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004622 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004623 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4624 I != E; ++I, ++j) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004625 SmallVector<MVT, 4> ValueVTs;
4626 ComputeValueVTs(*this, I->getType(), ValueVTs);
4627 for (unsigned Value = 0, NumValues = ValueVTs.size();
4628 Value != NumValues; ++Value) {
4629 MVT VT = ValueVTs[Value];
4630 const Type *ArgTy = VT.getTypeForMVT();
4631 ISD::ArgFlagsTy Flags;
4632 unsigned OriginalAlignment =
4633 getTargetData()->getABITypeAlignment(ArgTy);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004634
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004635 if (F.paramHasAttr(j, ParamAttr::ZExt))
4636 Flags.setZExt();
4637 if (F.paramHasAttr(j, ParamAttr::SExt))
4638 Flags.setSExt();
4639 if (F.paramHasAttr(j, ParamAttr::InReg))
4640 Flags.setInReg();
4641 if (F.paramHasAttr(j, ParamAttr::StructRet))
4642 Flags.setSRet();
4643 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4644 Flags.setByVal();
4645 const PointerType *Ty = cast<PointerType>(I->getType());
4646 const Type *ElementTy = Ty->getElementType();
4647 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4648 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4649 // For ByVal, alignment should be passed from FE. BE will guess if
4650 // this info is not there but there are cases it cannot get right.
4651 if (F.getParamAlignment(j))
4652 FrameAlign = F.getParamAlignment(j);
4653 Flags.setByValAlign(FrameAlign);
4654 Flags.setByValSize(FrameSize);
4655 }
4656 if (F.paramHasAttr(j, ParamAttr::Nest))
4657 Flags.setNest();
4658 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004659
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004660 MVT RegisterVT = getRegisterType(VT);
4661 unsigned NumRegs = getNumRegisters(VT);
4662 for (unsigned i = 0; i != NumRegs; ++i) {
4663 RetVals.push_back(RegisterVT);
4664 ISD::ArgFlagsTy MyFlags = Flags;
4665 if (NumRegs > 1 && i == 0)
4666 MyFlags.setSplit();
4667 // if it isn't first piece, alignment must be 1
4668 else if (i > 0)
4669 MyFlags.setOrigAlign(1);
4670 Ops.push_back(DAG.getArgFlags(MyFlags));
4671 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004672 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004673 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004674
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004675 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004676
4677 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004678 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004679 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004680 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004681
4682 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4683 // allows exposing the loads that may be part of the argument access to the
4684 // first DAGCombiner pass.
Dan Gohman475871a2008-07-27 21:46:04 +00004685 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004686
4687 // The number of results should match up, except that the lowered one may have
4688 // an extra flag result.
4689 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4690 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4691 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4692 && "Lowering produced unexpected number of results!");
Dan Gohman2dbc1672008-07-21 21:04:07 +00004693
4694 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
4695 if (Result != TmpRes.Val && Result->use_empty()) {
4696 HandleSDNode Dummy(DAG.getRoot());
4697 DAG.RemoveDeadNode(Result);
4698 }
4699
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004700 Result = TmpRes.Val;
4701
Dan Gohman27a70be2007-07-02 16:18:06 +00004702 unsigned NumArgRegs = Result->getNumValues() - 1;
Dan Gohman475871a2008-07-27 21:46:04 +00004703 DAG.setRoot(SDValue(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004704
4705 // Set up the return result vector.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004706 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004707 unsigned Idx = 1;
4708 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4709 ++I, ++Idx) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004710 SmallVector<MVT, 4> ValueVTs;
4711 ComputeValueVTs(*this, I->getType(), ValueVTs);
4712 for (unsigned Value = 0, NumValues = ValueVTs.size();
4713 Value != NumValues; ++Value) {
4714 MVT VT = ValueVTs[Value];
4715 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004716
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004717 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00004718 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004719 for (unsigned j = 0; j != NumParts; ++j)
Dan Gohman475871a2008-07-27 21:46:04 +00004720 Parts[j] = SDValue(Result, i++);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004721
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004722 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4723 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4724 AssertOp = ISD::AssertSext;
4725 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4726 AssertOp = ISD::AssertZext;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004727
Dan Gohmana44b6742008-06-30 20:31:15 +00004728 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4729 AssertOp));
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004730 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004731 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004732 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004733}
4734
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004735
4736/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4737/// implementation, which just inserts an ISD::CALL node, which is later custom
4738/// lowered by the target to something concrete. FIXME: When all targets are
4739/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
Dan Gohman475871a2008-07-27 21:46:04 +00004740std::pair<SDValue, SDValue>
4741TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
Duncan Sands00fee652008-02-14 17:28:50 +00004742 bool RetSExt, bool RetZExt, bool isVarArg,
4743 unsigned CallingConv, bool isTailCall,
Dan Gohman475871a2008-07-27 21:46:04 +00004744 SDValue Callee,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004745 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman475871a2008-07-27 21:46:04 +00004746 SmallVector<SDValue, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004747 Ops.push_back(Chain); // Op#0 - Chain
4748 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4749 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4750 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4751 Ops.push_back(Callee);
4752
4753 // Handle all of the outgoing arguments.
4754 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004755 SmallVector<MVT, 4> ValueVTs;
4756 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4757 for (unsigned Value = 0, NumValues = ValueVTs.size();
4758 Value != NumValues; ++Value) {
4759 MVT VT = ValueVTs[Value];
4760 const Type *ArgTy = VT.getTypeForMVT();
Dan Gohman475871a2008-07-27 21:46:04 +00004761 SDValue Op = SDValue(Args[i].Node.Val, Args[i].Node.ResNo + Value);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004762 ISD::ArgFlagsTy Flags;
4763 unsigned OriginalAlignment =
4764 getTargetData()->getABITypeAlignment(ArgTy);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004765
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004766 if (Args[i].isZExt)
4767 Flags.setZExt();
4768 if (Args[i].isSExt)
4769 Flags.setSExt();
4770 if (Args[i].isInReg)
4771 Flags.setInReg();
4772 if (Args[i].isSRet)
4773 Flags.setSRet();
4774 if (Args[i].isByVal) {
4775 Flags.setByVal();
4776 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4777 const Type *ElementTy = Ty->getElementType();
4778 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4779 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4780 // For ByVal, alignment should come from FE. BE will guess if this
4781 // info is not there but there are cases it cannot get right.
4782 if (Args[i].Alignment)
4783 FrameAlign = Args[i].Alignment;
4784 Flags.setByValAlign(FrameAlign);
4785 Flags.setByValSize(FrameSize);
4786 }
4787 if (Args[i].isNest)
4788 Flags.setNest();
4789 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004790
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004791 MVT PartVT = getRegisterType(VT);
4792 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00004793 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004794 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004795
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004796 if (Args[i].isSExt)
4797 ExtendKind = ISD::SIGN_EXTEND;
4798 else if (Args[i].isZExt)
4799 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004800
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004801 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004802
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004803 for (unsigned i = 0; i != NumParts; ++i) {
4804 // if it isn't first piece, alignment must be 1
4805 ISD::ArgFlagsTy MyFlags = Flags;
4806 if (NumParts > 1 && i == 0)
4807 MyFlags.setSplit();
4808 else if (i != 0)
4809 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004810
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004811 Ops.push_back(Parts[i]);
4812 Ops.push_back(DAG.getArgFlags(MyFlags));
4813 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004814 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004815 }
4816
Dan Gohmanef5d1942008-03-11 21:11:25 +00004817 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004818 // the potentially illegal return value types.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004819 SmallVector<MVT, 4> LoweredRetTys;
4820 SmallVector<MVT, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004821 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004822
Dan Gohman23ce5022008-04-25 18:27:55 +00004823 // Then we translate that to a list of legal types.
4824 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004825 MVT VT = RetTys[I];
4826 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004827 unsigned NumRegs = getNumRegisters(VT);
4828 for (unsigned i = 0; i != NumRegs; ++i)
4829 LoweredRetTys.push_back(RegisterVT);
4830 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004831
Dan Gohmanef5d1942008-03-11 21:11:25 +00004832 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004833
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004834 // Create the CALL node.
Dan Gohman475871a2008-07-27 21:46:04 +00004835 SDValue Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004836 DAG.getVTList(&LoweredRetTys[0],
4837 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004838 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004839 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004840
4841 // Gather up the call result into a single value.
4842 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004843 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4844
4845 if (RetSExt)
4846 AssertOp = ISD::AssertSext;
4847 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004848 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004849
Dan Gohman475871a2008-07-27 21:46:04 +00004850 SmallVector<SDValue, 4> ReturnValues;
Dan Gohmanef5d1942008-03-11 21:11:25 +00004851 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004852 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004853 MVT VT = RetTys[I];
4854 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004855 unsigned NumRegs = getNumRegisters(VT);
4856 unsigned RegNoEnd = NumRegs + RegNo;
Dan Gohman475871a2008-07-27 21:46:04 +00004857 SmallVector<SDValue, 4> Results;
Dan Gohmanef5d1942008-03-11 21:11:25 +00004858 for (; RegNo != RegNoEnd; ++RegNo)
4859 Results.push_back(Res.getValue(RegNo));
Dan Gohman475871a2008-07-27 21:46:04 +00004860 SDValue ReturnValue =
Dan Gohmanef5d1942008-03-11 21:11:25 +00004861 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4862 AssertOp);
4863 ReturnValues.push_back(ReturnValue);
4864 }
Duncan Sandsf9516202008-06-30 10:19:09 +00004865 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
4866 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004867 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004868
4869 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004870}
4871
Dan Gohman475871a2008-07-27 21:46:04 +00004872SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004873 assert(0 && "LowerOperation not implemented for this target!");
4874 abort();
Dan Gohman475871a2008-07-27 21:46:04 +00004875 return SDValue();
Chris Lattner171453a2005-01-16 07:28:41 +00004876}
4877
Nate Begeman0aed7842006-01-28 03:14:31 +00004878
Chris Lattner7041ee32005-01-11 05:56:49 +00004879//===----------------------------------------------------------------------===//
4880// SelectionDAGISel code
4881//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004882
Duncan Sands83ec4b62008-06-06 12:08:01 +00004883unsigned SelectionDAGISel::MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004884 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004885}
4886
Chris Lattner495a0b52005-08-17 06:37:43 +00004887void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004888 AU.addRequired<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004889 AU.addRequired<GCModuleInfo>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004890 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004891}
Chris Lattner1c08c712005-01-07 07:47:53 +00004892
Chris Lattner1c08c712005-01-07 07:47:53 +00004893bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004894 // Get alias analysis for load/store combining.
4895 AA = &getAnalysis<AliasAnalysis>();
4896
Chris Lattner1c08c712005-01-07 07:47:53 +00004897 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004898 if (MF.getFunction()->hasGC())
4899 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
Gordon Henriksence224772008-01-07 01:30:38 +00004900 else
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004901 GFI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004902 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004903 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004904
4905 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4906
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004907 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4908 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4909 // Mark landing pad.
4910 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004911
Dan Gohman0e5f1302008-07-07 23:02:41 +00004912 SelectAllBasicBlocks(Fn, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004913
Evan Chengad2070c2007-02-10 02:43:39 +00004914 // Add function live-ins to entry block live-in set.
4915 BasicBlock *EntryBB = &Fn.getEntryBlock();
4916 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004917 if (!RegInfo->livein_empty())
4918 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4919 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004920 BB->addLiveIn(I->first);
4921
Duncan Sandsf4070822007-06-15 19:04:19 +00004922#ifndef NDEBUG
4923 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4924 "Not all catch info was assigned to a landing pad!");
4925#endif
4926
Chris Lattner1c08c712005-01-07 07:47:53 +00004927 return true;
4928}
4929
Chris Lattner6833b062008-04-28 07:16:35 +00004930void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Dan Gohman475871a2008-07-27 21:46:04 +00004931 SDValue Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004932 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004933 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004934 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004935 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004936
Dan Gohman23ce5022008-04-25 18:27:55 +00004937 RegsForValue RFV(TLI, Reg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00004938 SDValue Chain = DAG.getEntryNode();
Dan Gohman23ce5022008-04-25 18:27:55 +00004939 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4940 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004941}
4942
Chris Lattner068a81e2005-01-17 17:15:02 +00004943void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004944LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004945 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004946 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004947 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Dan Gohman475871a2008-07-27 21:46:04 +00004948 SDValue OldRoot = SDL.DAG.getRoot();
4949 SmallVector<SDValue, 16> Args;
Dan Gohmana44b6742008-06-30 20:31:15 +00004950 TLI.LowerArguments(F, SDL.DAG, Args);
Chris Lattner068a81e2005-01-17 17:15:02 +00004951
Chris Lattnerbf209482005-10-30 19:42:35 +00004952 unsigned a = 0;
4953 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004954 AI != E; ++AI) {
4955 SmallVector<MVT, 4> ValueVTs;
4956 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4957 unsigned NumValues = ValueVTs.size();
Chris Lattnerbf209482005-10-30 19:42:35 +00004958 if (!AI->use_empty()) {
Duncan Sands4bdcb612008-07-02 17:40:58 +00004959 SDL.setValue(AI, SDL.DAG.getMergeValues(&Args[a], NumValues));
Chris Lattnerbf209482005-10-30 19:42:35 +00004960 // If this argument is live outside of the entry block, insert a copy from
4961 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004962 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4963 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004964 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004965 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004966 }
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004967 a += NumValues;
4968 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004969
Chris Lattnerbf209482005-10-30 19:42:35 +00004970 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004971 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004972 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004973}
4974
Duncan Sandsf4070822007-06-15 19:04:19 +00004975static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4976 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004977 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004978 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004979 // Apply the catch info to DestBB.
4980 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4981#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004982 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4983 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004984#endif
4985 }
4986}
4987
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004988/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4989/// whether object offset >= 0.
4990static bool
Dan Gohman475871a2008-07-27 21:46:04 +00004991IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDValue Op) {
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004992 if (!isa<FrameIndexSDNode>(Op)) return false;
4993
4994 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4995 int FrameIdx = FrameIdxNode->getIndex();
4996 return MFI->isFixedObjectIndex(FrameIdx) &&
4997 MFI->getObjectOffset(FrameIdx) >= 0;
4998}
4999
5000/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
5001/// possibly be overwritten when lowering the outgoing arguments in a tail
5002/// call. Currently the implementation of this call is very conservative and
5003/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
5004/// virtual registers would be overwritten by direct lowering.
Dan Gohman475871a2008-07-27 21:46:04 +00005005static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005006 MachineFrameInfo * MFI) {
5007 RegisterSDNode * OpReg = NULL;
5008 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
5009 (Op.getOpcode()== ISD::CopyFromReg &&
5010 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
5011 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
5012 (Op.getOpcode() == ISD::LOAD &&
5013 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
5014 (Op.getOpcode() == ISD::MERGE_VALUES &&
5015 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
5016 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
5017 getOperand(1))))
5018 return true;
5019 return false;
5020}
5021
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005022/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005023/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005024static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
5025 TargetLowering& TLI) {
5026 SDNode * Ret = NULL;
Dan Gohman475871a2008-07-27 21:46:04 +00005027 SDValue Terminator = DAG.getRoot();
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005028
5029 // Find RET node.
5030 if (Terminator.getOpcode() == ISD::RET) {
5031 Ret = Terminator.Val;
5032 }
5033
5034 // Fix tail call attribute of CALL nodes.
5035 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
Dan Gohman0e5f1302008-07-07 23:02:41 +00005036 BI = DAG.allnodes_end(); BI != BE; ) {
5037 --BI;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005038 if (BI->getOpcode() == ISD::CALL) {
Dan Gohman475871a2008-07-27 21:46:04 +00005039 SDValue OpRet(Ret, 0);
5040 SDValue OpCall(BI, 0);
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005041 bool isMarkedTailCall =
5042 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5043 // If CALL node has tail call attribute set to true and the call is not
5044 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005045 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005046 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005047 if (!isMarkedTailCall) continue;
5048 if (Ret==NULL ||
5049 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5050 // Not eligible. Mark CALL node as non tail call.
Dan Gohman475871a2008-07-27 21:46:04 +00005051 SmallVector<SDValue, 32> Ops;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005052 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005053 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5054 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005055 if (idx!=3)
5056 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005057 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005058 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5059 }
5060 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005061 } else {
5062 // Look for tail call clobbered arguments. Emit a series of
5063 // copyto/copyfrom virtual register nodes to protect them.
Dan Gohman475871a2008-07-27 21:46:04 +00005064 SmallVector<SDValue, 32> Ops;
5065 SDValue Chain = OpCall.getOperand(0), InFlag;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005066 unsigned idx=0;
5067 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5068 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Dan Gohman475871a2008-07-27 21:46:04 +00005069 SDValue Arg = *I;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005070 if (idx > 4 && (idx % 2)) {
5071 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5072 getArgFlags().isByVal();
5073 MachineFunction &MF = DAG.getMachineFunction();
5074 MachineFrameInfo *MFI = MF.getFrameInfo();
5075 if (!isByVal &&
5076 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00005077 MVT VT = Arg.getValueType();
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005078 unsigned VReg = MF.getRegInfo().
5079 createVirtualRegister(TLI.getRegClassFor(VT));
5080 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5081 InFlag = Chain.getValue(1);
5082 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5083 Chain = Arg.getValue(1);
5084 InFlag = Arg.getValue(2);
5085 }
5086 }
5087 Ops.push_back(Arg);
5088 }
5089 // Link in chain of CopyTo/CopyFromReg.
5090 Ops[0] = Chain;
5091 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005092 }
5093 }
5094 }
5095}
5096
Chris Lattner1c08c712005-01-07 07:47:53 +00005097void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
5098 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00005099 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005100 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GFI);
Dan Gohman78eca172008-08-19 22:33:34 +00005101 BB = FuncInfo.MBBMap[LLVMBB];
5102
5103 // Before doing SelectionDAG ISel, see if FastISel has been requested.
5104 // FastISel doesn't currently support entry blocks, because that
5105 // requires special handling for arguments. And it doesn't support EH
5106 // landing pads, which also require special handling.
5107 // For now, also exclude blocks with terminators that aren't
5108 // unconditional branches.
Dan Gohman3e697cf2008-08-20 00:47:54 +00005109 BasicBlock::iterator Begin = LLVMBB->begin();
Dan Gohman78eca172008-08-19 22:33:34 +00005110 if (EnableFastISel &&
5111 LLVMBB != &LLVMBB->getParent()->getEntryBlock() &&
5112 !BB->isLandingPad() &&
5113 isa<BranchInst>(LLVMBB->getTerminator()) &&
5114 cast<BranchInst>(LLVMBB->getTerminator())->isUnconditional()) {
5115 if (FastISel *F = TLI.createFastISel(BB, &FuncInfo.MF,
5116 TLI.getTargetMachine().getInstrInfo())) {
Dan Gohman3e697cf2008-08-20 00:47:54 +00005117 Begin = F->SelectInstructions(Begin, LLVMBB->end(), FuncInfo.ValueMap);
5118 if (Begin == LLVMBB->end())
Dan Gohman78eca172008-08-19 22:33:34 +00005119 // The "fast" selector selected the entire block, so we're done.
5120 return;
5121
Dan Gohman3e697cf2008-08-20 00:47:54 +00005122 if (!DisableFastISelAbort) {
5123 // The "fast" selector couldn't handle something and bailed.
5124 // For the purpose of debugging, just abort.
5125 DEBUG(Begin->dump());
5126 assert(0 && "FastISel didn't select the entire block");
5127 abort();
5128 }
Dan Gohman78eca172008-08-19 22:33:34 +00005129 }
5130 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00005131
Chris Lattnerbf209482005-10-30 19:42:35 +00005132 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00005133 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005134 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00005135
Chris Lattner1c08c712005-01-07 07:47:53 +00005136 SDL.setCurrentBasicBlock(BB);
5137
Duncan Sandsf4070822007-06-15 19:04:19 +00005138 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00005139
Dale Johannesen1532f3d2008-04-02 00:25:04 +00005140 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00005141 // Add a label to mark the beginning of the landing pad. Deletion of the
5142 // landing pad can thus be detected via the MachineModuleInfo.
5143 unsigned LabelID = MMI->addLandingPad(BB);
Dan Gohman44066042008-07-01 00:05:16 +00005144 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, DAG.getEntryNode(), LabelID));
Duncan Sandsf4070822007-06-15 19:04:19 +00005145
Evan Chenge47c3332007-06-27 18:45:32 +00005146 // Mark exception register as live in.
5147 unsigned Reg = TLI.getExceptionAddressRegister();
5148 if (Reg) BB->addLiveIn(Reg);
5149
5150 // Mark exception selector register as live in.
5151 Reg = TLI.getExceptionSelectorRegister();
5152 if (Reg) BB->addLiveIn(Reg);
5153
Duncan Sandsf4070822007-06-15 19:04:19 +00005154 // FIXME: Hack around an exception handling flaw (PR1508): the personality
5155 // function and list of typeids logically belong to the invoke (or, if you
5156 // like, the basic block containing the invoke), and need to be associated
5157 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005158 // information is provided by an intrinsic (eh.selector) that can be moved
5159 // to unexpected places by the optimizers: if the unwind edge is critical,
5160 // then breaking it can result in the intrinsics being in the successor of
5161 // the landing pad, not the landing pad itself. This results in exceptions
5162 // not being caught because no typeids are associated with the invoke.
5163 // This may not be the only way things can go wrong, but it is the only way
5164 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00005165 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5166
5167 if (Br && Br->isUnconditional()) { // Critical edge?
5168 BasicBlock::iterator I, E;
5169 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005170 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00005171 break;
5172
5173 if (I == E)
5174 // No catch info found - try to extract some from the successor.
5175 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00005176 }
5177 }
5178
Chris Lattner1c08c712005-01-07 07:47:53 +00005179 // Lower all of the non-terminator instructions.
Dan Gohman3e697cf2008-08-20 00:47:54 +00005180 for (BasicBlock::iterator I = Begin, E = --LLVMBB->end();
Chris Lattner1c08c712005-01-07 07:47:53 +00005181 I != E; ++I)
5182 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005183
Chris Lattner1c08c712005-01-07 07:47:53 +00005184 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005185 // blocks are available as virtual registers. Invoke is handled elsewhere.
Dan Gohman3e697cf2008-08-20 00:47:54 +00005186 for (BasicBlock::iterator I = Begin, E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005187 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00005188 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00005189 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005190 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00005191 }
5192
5193 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5194 // ensure constants are generated when needed. Remember the virtual registers
5195 // that need to be added to the Machine PHI nodes as input. We cannot just
5196 // directly add them, because expansion might result in multiple MBB's for one
5197 // BB. As such, the start of the BB might correspond to a different MBB than
5198 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00005199 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00005200 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00005201
5202 // Emit constants only once even if used by multiple PHI nodes.
5203 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005204
Chris Lattner8c494ab2006-10-27 23:50:33 +00005205 // Vector bool would be better, but vector<bool> is really slow.
5206 std::vector<unsigned char> SuccsHandled;
5207 if (TI->getNumSuccessors())
5208 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
5209
Dan Gohman532dc2e2007-07-09 20:59:04 +00005210 // Check successor nodes' PHI nodes that expect a constant to be available
5211 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00005212 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5213 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005214 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00005215 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005216
Chris Lattner8c494ab2006-10-27 23:50:33 +00005217 // If this terminator has multiple identical successors (common for
5218 // switches), only handle each succ once.
5219 unsigned SuccMBBNo = SuccMBB->getNumber();
5220 if (SuccsHandled[SuccMBBNo]) continue;
5221 SuccsHandled[SuccMBBNo] = true;
5222
5223 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00005224 PHINode *PN;
5225
5226 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5227 // nodes and Machine PHI nodes, but the incoming operands have not been
5228 // emitted yet.
5229 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00005230 (PN = dyn_cast<PHINode>(I)); ++I) {
5231 // Ignore dead phi's.
5232 if (PN->use_empty()) continue;
5233
5234 unsigned Reg;
5235 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00005236
Chris Lattner8c494ab2006-10-27 23:50:33 +00005237 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5238 unsigned &RegOut = ConstantsOut[C];
5239 if (RegOut == 0) {
5240 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005241 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00005242 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005243 Reg = RegOut;
5244 } else {
5245 Reg = FuncInfo.ValueMap[PHIOp];
5246 if (Reg == 0) {
5247 assert(isa<AllocaInst>(PHIOp) &&
5248 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5249 "Didn't codegen value into a register!??");
5250 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005251 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00005252 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005253 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005254
5255 // Remember that this register needs to added to the machine PHI node as
5256 // the input for this MBB.
Dan Gohman6f498b02008-08-04 23:42:46 +00005257 SmallVector<MVT, 4> ValueVTs;
5258 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5259 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5260 MVT VT = ValueVTs[vti];
5261 unsigned NumRegisters = TLI.getNumRegisters(VT);
5262 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5263 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5264 Reg += NumRegisters;
5265 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005266 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005267 }
5268 ConstantsOut.clear();
5269
5270 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005271 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00005272
Nate Begemanf15485a2006-03-27 01:32:24 +00005273 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00005274 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00005275 SwitchCases.clear();
5276 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005277 JTCases.clear();
5278 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005279 BitTestCases.clear();
5280 BitTestCases = SDL.BitTestCases;
5281
Chris Lattnera651cf62005-01-17 19:43:36 +00005282 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005283 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005284
5285 // Check whether calls in this block are real tail calls. Fix up CALL nodes
5286 // with correct tailcall attribute so that the target can rely on the tailcall
5287 // attribute indicating whether the call is really eligible for tail call
5288 // optimization.
5289 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00005290}
5291
Chris Lattneread0d882008-06-17 06:09:18 +00005292void SelectionDAGISel::ComputeLiveOutVRegInfo(SelectionDAG &DAG) {
5293 SmallPtrSet<SDNode*, 128> VisitedNodes;
5294 SmallVector<SDNode*, 128> Worklist;
5295
5296 Worklist.push_back(DAG.getRoot().Val);
5297
5298 APInt Mask;
5299 APInt KnownZero;
5300 APInt KnownOne;
5301
5302 while (!Worklist.empty()) {
5303 SDNode *N = Worklist.back();
5304 Worklist.pop_back();
5305
5306 // If we've already seen this node, ignore it.
5307 if (!VisitedNodes.insert(N))
5308 continue;
5309
5310 // Otherwise, add all chain operands to the worklist.
5311 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5312 if (N->getOperand(i).getValueType() == MVT::Other)
5313 Worklist.push_back(N->getOperand(i).Val);
5314
5315 // If this is a CopyToReg with a vreg dest, process it.
5316 if (N->getOpcode() != ISD::CopyToReg)
5317 continue;
5318
5319 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
5320 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
5321 continue;
5322
5323 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +00005324 SDValue Src = N->getOperand(2);
Chris Lattneread0d882008-06-17 06:09:18 +00005325 MVT SrcVT = Src.getValueType();
5326 if (!SrcVT.isInteger() || SrcVT.isVector())
5327 continue;
5328
5329 unsigned NumSignBits = DAG.ComputeNumSignBits(Src);
5330 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
5331 DAG.ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
5332
5333 // Only install this information if it tells us something.
5334 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
5335 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
5336 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5337 if (DestReg >= FLI.LiveOutRegInfo.size())
5338 FLI.LiveOutRegInfo.resize(DestReg+1);
5339 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
5340 LOI.NumSignBits = NumSignBits;
5341 LOI.KnownOne = NumSignBits;
5342 LOI.KnownZero = NumSignBits;
5343 }
5344 }
5345}
5346
Nate Begemanf15485a2006-03-27 01:32:24 +00005347void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman462dc7f2008-07-21 20:00:07 +00005348 std::string GroupName;
5349 if (TimePassesIsEnabled)
5350 GroupName = "Instruction Selection and Scheduling";
5351 std::string BlockName;
5352 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
5353 ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs || ViewSUnitDAGs)
5354 BlockName = DAG.getMachineFunction().getFunction()->getName() + ':' +
5355 BB->getBasicBlock()->getName();
5356
5357 DOUT << "Initial selection DAG:\n";
Dan Gohman417e11b2007-10-08 15:12:17 +00005358 DEBUG(DAG.dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005359
5360 if (ViewDAGCombine1) DAG.viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +00005361
Chris Lattneraf21d552005-10-10 16:47:10 +00005362 // Run the DAG combiner in pre-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005363 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005364 NamedRegionTimer T("DAG Combining 1", GroupName);
Evan Chengebffb662008-07-01 17:59:20 +00005365 DAG.Combine(false, *AA);
5366 } else {
5367 DAG.Combine(false, *AA);
5368 }
Nate Begeman2300f552005-09-07 00:15:36 +00005369
Dan Gohman417e11b2007-10-08 15:12:17 +00005370 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005371 DEBUG(DAG.dump());
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005372
Chris Lattner1c08c712005-01-07 07:47:53 +00005373 // Second step, hack on the DAG until it only uses operations and types that
5374 // the target supports.
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005375 if (EnableLegalizeTypes) {// Enable this some day.
Dan Gohman462dc7f2008-07-21 20:00:07 +00005376 if (ViewLegalizeTypesDAGs) DAG.viewGraph("legalize-types input for " +
5377 BlockName);
5378
5379 if (TimePassesIsEnabled) {
5380 NamedRegionTimer T("Type Legalization", GroupName);
5381 DAG.LegalizeTypes();
5382 } else {
5383 DAG.LegalizeTypes();
5384 }
5385
5386 DOUT << "Type-legalized selection DAG:\n";
5387 DEBUG(DAG.dump());
5388
Chris Lattner70587ea2008-07-10 23:37:50 +00005389 // TODO: enable a dag combine pass here.
5390 }
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005391
Dan Gohman462dc7f2008-07-21 20:00:07 +00005392 if (ViewLegalizeDAGs) DAG.viewGraph("legalize input for " + BlockName);
5393
Evan Chengebffb662008-07-01 17:59:20 +00005394 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005395 NamedRegionTimer T("DAG Legalization", GroupName);
Evan Chengebffb662008-07-01 17:59:20 +00005396 DAG.Legalize();
5397 } else {
5398 DAG.Legalize();
5399 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005400
Bill Wendling832171c2006-12-07 20:04:42 +00005401 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005402 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005403
Dan Gohman462dc7f2008-07-21 20:00:07 +00005404 if (ViewDAGCombine2) DAG.viewGraph("dag-combine2 input for " + BlockName);
5405
Chris Lattneraf21d552005-10-10 16:47:10 +00005406 // Run the DAG combiner in post-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005407 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005408 NamedRegionTimer T("DAG Combining 2", GroupName);
Evan Chengebffb662008-07-01 17:59:20 +00005409 DAG.Combine(true, *AA);
5410 } else {
5411 DAG.Combine(true, *AA);
5412 }
Nate Begeman2300f552005-09-07 00:15:36 +00005413
Dan Gohman417e11b2007-10-08 15:12:17 +00005414 DOUT << "Optimized legalized selection DAG:\n";
5415 DEBUG(DAG.dump());
5416
Dan Gohman462dc7f2008-07-21 20:00:07 +00005417 if (ViewISelDAGs) DAG.viewGraph("isel input for " + BlockName);
Chris Lattneread0d882008-06-17 06:09:18 +00005418
Dan Gohman925a7e82008-08-13 19:47:40 +00005419 if (!Fast && EnableValueProp)
Chris Lattneread0d882008-06-17 06:09:18 +00005420 ComputeLiveOutVRegInfo(DAG);
Evan Cheng552c4a82006-04-28 02:09:19 +00005421
Chris Lattnera33ef482005-03-30 01:10:47 +00005422 // Third, instruction select all of the operations to machine code, adding the
5423 // code to the MachineBasicBlock.
Evan Chengebffb662008-07-01 17:59:20 +00005424 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005425 NamedRegionTimer T("Instruction Selection", GroupName);
Evan Chengebffb662008-07-01 17:59:20 +00005426 InstructionSelect(DAG);
5427 } else {
5428 InstructionSelect(DAG);
5429 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005430
Dan Gohman462dc7f2008-07-21 20:00:07 +00005431 DOUT << "Selected selection DAG:\n";
5432 DEBUG(DAG.dump());
5433
5434 if (ViewSchedDAGs) DAG.viewGraph("scheduler input for " + BlockName);
5435
Dan Gohman5e843682008-07-14 18:19:29 +00005436 // Schedule machine code.
5437 ScheduleDAG *Scheduler;
5438 if (TimePassesIsEnabled) {
5439 NamedRegionTimer T("Instruction Scheduling", GroupName);
5440 Scheduler = Schedule(DAG);
5441 } else {
5442 Scheduler = Schedule(DAG);
5443 }
5444
Dan Gohman462dc7f2008-07-21 20:00:07 +00005445 if (ViewSUnitDAGs) Scheduler->viewGraph();
5446
Evan Chengdb8d56b2008-06-30 20:45:06 +00005447 // Emit machine code to BB. This can change 'BB' to the last block being
5448 // inserted into.
Evan Chengebffb662008-07-01 17:59:20 +00005449 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005450 NamedRegionTimer T("Instruction Creation", GroupName);
5451 BB = Scheduler->EmitSchedule();
Evan Chengebffb662008-07-01 17:59:20 +00005452 } else {
Dan Gohman5e843682008-07-14 18:19:29 +00005453 BB = Scheduler->EmitSchedule();
5454 }
5455
5456 // Free the scheduler state.
5457 if (TimePassesIsEnabled) {
5458 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
5459 delete Scheduler;
5460 } else {
5461 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +00005462 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005463
5464 // Perform target specific isel post processing.
Evan Chengebffb662008-07-01 17:59:20 +00005465 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005466 NamedRegionTimer T("Instruction Selection Post Processing", GroupName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005467 InstructionSelectPostProcessing();
Evan Chengebffb662008-07-01 17:59:20 +00005468 } else {
Dan Gohman462dc7f2008-07-21 20:00:07 +00005469 InstructionSelectPostProcessing();
Evan Chengebffb662008-07-01 17:59:20 +00005470 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005471
Bill Wendling832171c2006-12-07 20:04:42 +00005472 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005473 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005474}
Chris Lattner1c08c712005-01-07 07:47:53 +00005475
Dan Gohman0e5f1302008-07-07 23:02:41 +00005476void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF,
5477 FunctionLoweringInfo &FuncInfo) {
Dan Gohmanfed90b62008-07-28 21:51:04 +00005478 // Define NodeAllocator here so that memory allocation is reused for
Dan Gohman0e5f1302008-07-07 23:02:41 +00005479 // each basic block.
Dan Gohmanfed90b62008-07-28 21:51:04 +00005480 NodeAllocatorType NodeAllocator;
Dan Gohman0e5f1302008-07-07 23:02:41 +00005481
Evan Cheng381cb072008-08-08 07:27:28 +00005482 SimpleBBISel SISel(MF, TLI);
Evan Cheng39fd6e82008-08-07 00:43:25 +00005483 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5484 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
5485 BasicBlock *LLVMBB = &*I;
5486 PHINodesToUpdate.clear();
Evan Cheng381cb072008-08-08 07:27:28 +00005487
Dan Gohman925a7e82008-08-13 19:47:40 +00005488 if (!Fast || !SISel.SelectBasicBlock(LLVMBB, FuncInfo.MBBMap[LLVMBB]))
Evan Cheng381cb072008-08-08 07:27:28 +00005489 SelectBasicBlock(LLVMBB, MF, FuncInfo, PHINodesToUpdate, NodeAllocator);
Evan Cheng39fd6e82008-08-07 00:43:25 +00005490 FinishBasicBlock(LLVMBB, MF, FuncInfo, PHINodesToUpdate, NodeAllocator);
5491 }
Dan Gohman0e5f1302008-07-07 23:02:41 +00005492}
5493
Dan Gohmanfed90b62008-07-28 21:51:04 +00005494void
5495SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5496 FunctionLoweringInfo &FuncInfo,
Evan Cheng39fd6e82008-08-07 00:43:25 +00005497 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Dan Gohmanfed90b62008-07-28 21:51:04 +00005498 NodeAllocatorType &NodeAllocator) {
Evan Cheng39fd6e82008-08-07 00:43:25 +00005499 SelectionDAG DAG(TLI, MF, FuncInfo,
5500 getAnalysisToUpdate<MachineModuleInfo>(),
5501 NodeAllocator);
5502 CurDAG = &DAG;
Nate Begemanf15485a2006-03-27 01:32:24 +00005503
Evan Cheng39fd6e82008-08-07 00:43:25 +00005504 // First step, lower LLVM code to some DAG. This DAG may use operations and
5505 // types that are not supported by the target.
5506 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
Nate Begemanf15485a2006-03-27 01:32:24 +00005507
Evan Cheng39fd6e82008-08-07 00:43:25 +00005508 // Second step, emit the lowered DAG as machine code.
5509 CodeGenAndEmitDAG(DAG);
5510}
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005511
Evan Cheng39fd6e82008-08-07 00:43:25 +00005512void
5513SelectionDAGISel::FinishBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5514 FunctionLoweringInfo &FuncInfo,
5515 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5516 NodeAllocatorType &NodeAllocator) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005517 DOUT << "Total amount of phi nodes to update: "
5518 << PHINodesToUpdate.size() << "\n";
5519 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5520 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5521 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005522
Chris Lattnera33ef482005-03-30 01:10:47 +00005523 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005524 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005525 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005526 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5527 MachineInstr *PHI = PHINodesToUpdate[i].first;
5528 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5529 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005530 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5531 false));
5532 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005533 }
5534 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005535 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005536
5537 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5538 // Lower header first, if it wasn't already lowered
5539 if (!BitTestCases[i].Emitted) {
Chris Lattneread0d882008-06-17 06:09:18 +00005540 SelectionDAG HSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005541 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005542 NodeAllocator);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005543 CurDAG = &HSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005544 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005545 // Set the current basic block to the mbb we wish to insert the code into
5546 BB = BitTestCases[i].Parent;
5547 HSDL.setCurrentBasicBlock(BB);
5548 // Emit the code
5549 HSDL.visitBitTestHeader(BitTestCases[i]);
5550 HSDAG.setRoot(HSDL.getRoot());
5551 CodeGenAndEmitDAG(HSDAG);
5552 }
5553
5554 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
Chris Lattneread0d882008-06-17 06:09:18 +00005555 SelectionDAG BSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005556 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005557 NodeAllocator);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005558 CurDAG = &BSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005559 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005560 // Set the current basic block to the mbb we wish to insert the code into
5561 BB = BitTestCases[i].Cases[j].ThisBB;
5562 BSDL.setCurrentBasicBlock(BB);
5563 // Emit the code
5564 if (j+1 != ej)
5565 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5566 BitTestCases[i].Reg,
5567 BitTestCases[i].Cases[j]);
5568 else
5569 BSDL.visitBitTestCase(BitTestCases[i].Default,
5570 BitTestCases[i].Reg,
5571 BitTestCases[i].Cases[j]);
5572
5573
5574 BSDAG.setRoot(BSDL.getRoot());
5575 CodeGenAndEmitDAG(BSDAG);
5576 }
5577
5578 // Update PHI Nodes
5579 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5580 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5581 MachineBasicBlock *PHIBB = PHI->getParent();
5582 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5583 "This is not a machine PHI node that we are updating!");
5584 // This is "default" BB. We have two jumps to it. From "header" BB and
5585 // from last "case" BB.
5586 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005587 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5588 false));
5589 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5590 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5591 false));
5592 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5593 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005594 }
5595 // One of "cases" BB.
5596 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5597 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5598 if (cBB->succ_end() !=
5599 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005600 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5601 false));
5602 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005603 }
5604 }
5605 }
5606 }
5607
Nate Begeman9453eea2006-04-23 06:26:20 +00005608 // If the JumpTable record is filled in, then we need to emit a jump table.
5609 // Updating the PHI nodes is tricky in this case, since we need to determine
5610 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005611 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5612 // Lower header first, if it wasn't already lowered
5613 if (!JTCases[i].first.Emitted) {
Chris Lattneread0d882008-06-17 06:09:18 +00005614 SelectionDAG HSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005615 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005616 NodeAllocator);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005617 CurDAG = &HSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005618 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005619 // Set the current basic block to the mbb we wish to insert the code into
5620 BB = JTCases[i].first.HeaderBB;
5621 HSDL.setCurrentBasicBlock(BB);
5622 // Emit the code
5623 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5624 HSDAG.setRoot(HSDL.getRoot());
5625 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005626 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005627
Chris Lattneread0d882008-06-17 06:09:18 +00005628 SelectionDAG JSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005629 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005630 NodeAllocator);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005631 CurDAG = &JSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005632 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GFI);
Nate Begeman37efe672006-04-22 18:53:45 +00005633 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005634 BB = JTCases[i].second.MBB;
5635 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005636 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005637 JSDL.visitJumpTable(JTCases[i].second);
5638 JSDAG.setRoot(JSDL.getRoot());
5639 CodeGenAndEmitDAG(JSDAG);
5640
Nate Begeman37efe672006-04-22 18:53:45 +00005641 // Update PHI Nodes
5642 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5643 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5644 MachineBasicBlock *PHIBB = PHI->getParent();
5645 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5646 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005647 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005648 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005649 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5650 false));
5651 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005652 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005653 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005654 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005655 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5656 false));
5657 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005658 }
5659 }
Nate Begeman37efe672006-04-22 18:53:45 +00005660 }
5661
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005662 // If the switch block involved a branch to one of the actual successors, we
5663 // need to update PHI nodes in that block.
5664 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5665 MachineInstr *PHI = PHINodesToUpdate[i].first;
5666 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5667 "This is not a machine PHI node that we are updating!");
5668 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005669 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5670 false));
5671 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005672 }
5673 }
5674
Nate Begemanf15485a2006-03-27 01:32:24 +00005675 // If we generated any switch lowering information, build and codegen any
5676 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005677 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Chris Lattneread0d882008-06-17 06:09:18 +00005678 SelectionDAG SDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005679 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005680 NodeAllocator);
Nate Begemanf15485a2006-03-27 01:32:24 +00005681 CurDAG = &SDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005682 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GFI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005683
Nate Begemanf15485a2006-03-27 01:32:24 +00005684 // Set the current basic block to the mbb we wish to insert the code into
5685 BB = SwitchCases[i].ThisBB;
5686 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005687
Nate Begemanf15485a2006-03-27 01:32:24 +00005688 // Emit the code
5689 SDL.visitSwitchCase(SwitchCases[i]);
5690 SDAG.setRoot(SDL.getRoot());
5691 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005692
5693 // Handle any PHI nodes in successors of this chunk, as if we were coming
5694 // from the original BB before switch expansion. Note that PHI nodes can
5695 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5696 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005697 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005698 for (MachineBasicBlock::iterator Phi = BB->begin();
5699 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5700 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5701 for (unsigned pn = 0; ; ++pn) {
5702 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5703 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005704 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5705 second, false));
5706 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005707 break;
5708 }
5709 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005710 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005711
5712 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005713 if (BB == SwitchCases[i].FalseBB)
5714 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005715
5716 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005717 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005718 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005719 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005720 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005721 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005722}
Evan Chenga9c20912006-01-21 02:32:06 +00005723
Jim Laskey13ec7022006-08-01 14:21:23 +00005724
Dan Gohman5e843682008-07-14 18:19:29 +00005725/// Schedule - Pick a safe ordering for instructions for each
Evan Chenga9c20912006-01-21 02:32:06 +00005726/// target node in the graph.
Dan Gohman5e843682008-07-14 18:19:29 +00005727///
5728ScheduleDAG *SelectionDAGISel::Schedule(SelectionDAG &DAG) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005729 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005730
5731 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005732 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005733 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005734 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005735
Dan Gohman925a7e82008-08-13 19:47:40 +00005736 ScheduleDAG *Scheduler = Ctor(this, &DAG, BB, Fast);
Dan Gohman5e843682008-07-14 18:19:29 +00005737 Scheduler->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005738
Dan Gohman5e843682008-07-14 18:19:29 +00005739 return Scheduler;
Evan Chenga9c20912006-01-21 02:32:06 +00005740}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005741
Chris Lattner03fc53c2006-03-06 00:22:00 +00005742
Jim Laskey9ff542f2006-08-01 18:29:48 +00005743HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5744 return new HazardRecognizer();
5745}
5746
Chris Lattner75548062006-10-11 03:58:02 +00005747//===----------------------------------------------------------------------===//
5748// Helper functions used by the generated instruction selector.
5749//===----------------------------------------------------------------------===//
5750// Calls to these methods are generated by tblgen.
5751
5752/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5753/// the dag combiner simplified the 255, we still want to match. RHS is the
5754/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5755/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00005756bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005757 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005758 const APInt &ActualMask = RHS->getAPIntValue();
5759 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005760
5761 // If the actual mask exactly matches, success!
5762 if (ActualMask == DesiredMask)
5763 return true;
5764
5765 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005766 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005767 return false;
5768
5769 // Otherwise, the DAG Combiner may have proven that the value coming in is
5770 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005771 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005772 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005773 return true;
5774
5775 // TODO: check to see if missing bits are just not demanded.
5776
5777 // Otherwise, this pattern doesn't match.
5778 return false;
5779}
5780
5781/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5782/// the dag combiner simplified the 255, we still want to match. RHS is the
5783/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5784/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00005785bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005786 int64_t DesiredMaskS) const {
5787 const APInt &ActualMask = RHS->getAPIntValue();
5788 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005789
5790 // If the actual mask exactly matches, success!
5791 if (ActualMask == DesiredMask)
5792 return true;
5793
5794 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005795 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005796 return false;
5797
5798 // Otherwise, the DAG Combiner may have proven that the value coming in is
5799 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005800 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005801
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005802 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005803 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005804
5805 // If all the missing bits in the or are already known to be set, match!
5806 if ((NeededMask & KnownOne) == NeededMask)
5807 return true;
5808
5809 // TODO: check to see if missing bits are just not demanded.
5810
5811 // Otherwise, this pattern doesn't match.
5812 return false;
5813}
5814
Jim Laskey9ff542f2006-08-01 18:29:48 +00005815
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005816/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5817/// by tblgen. Others should not call it.
5818void SelectionDAGISel::
Dan Gohman475871a2008-07-27 21:46:04 +00005819SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, SelectionDAG &DAG) {
5820 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005821 std::swap(InOps, Ops);
5822
5823 Ops.push_back(InOps[0]); // input chain.
5824 Ops.push_back(InOps[1]); // input asm string.
5825
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005826 unsigned i = 2, e = InOps.size();
5827 if (InOps[e-1].getValueType() == MVT::Flag)
5828 --e; // Don't process a flag operand if it is here.
5829
5830 while (i != e) {
5831 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5832 if ((Flags & 7) != 4 /*MEM*/) {
5833 // Just skip over this operand, copying the operands verbatim.
5834 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5835 i += (Flags >> 3) + 1;
5836 } else {
5837 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5838 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00005839 std::vector<SDValue> SelOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005840 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005841 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005842 exit(1);
5843 }
5844
5845 // Add this to the output node.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005846 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005847 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005848 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005849 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5850 i += 2;
5851 }
5852 }
5853
5854 // Add the flag input back if present.
5855 if (e != InOps.size())
5856 Ops.push_back(InOps.back());
5857}
Devang Patel794fd752007-05-01 21:15:47 +00005858
Devang Patel19974732007-05-03 01:11:54 +00005859char SelectionDAGISel::ID = 0;