blob: 3cc815283bf655a95d1dde8aafdf756b8173046d [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"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.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"
Gordon Henriksence224772008-01-07 01:30:38 +000029#include "llvm/CodeGen/Collector.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000033#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000036#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000038#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Target/TargetFrameInfo.h"
41#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetLowering.h"
43#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000044#include "llvm/Target/TargetOptions.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000045#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000046#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000047#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattnerda8abb02005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000058static cl::opt<bool>
59ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000060 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000061#else
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000062static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000063#endif
64
Jim Laskeyeb577ba2006-08-02 12:30:23 +000065//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +000077static cl::opt<RegisterScheduler::FunctionPassCtor, false,
78 RegisterPassParser<RegisterScheduler> >
79ISHeuristic("pre-RA-sched",
80 cl::init(&createDefaultScheduler),
81 cl::desc("Instruction schedulers available (before register"
82 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +000083
Dan Gohman844731a2008-05-13 00:00:25 +000084static RegisterScheduler
85defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000087
Evan Cheng5c807602008-02-26 02:33:44 +000088namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +000089
Chris Lattnerf899fce2008-04-27 23:48:12 +000090/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
91/// MVT::ValueTypes that represent all the individual underlying
92/// non-aggregate types that comprise it.
93static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
94 SmallVectorImpl<MVT::ValueType> &ValueVTs) {
95 // Given a struct type, recursively traverse the elements.
96 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
97 for (StructType::element_iterator EI = STy->element_begin(),
98 EB = STy->element_end();
99 EI != EB; ++EI)
100 ComputeValueVTs(TLI, *EI, ValueVTs);
101 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000102 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000103 // Given an array type, recursively traverse the elements.
104 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
105 const Type *EltTy = ATy->getElementType();
106 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
107 ComputeValueVTs(TLI, EltTy, ValueVTs);
108 return;
109 }
110 // Base case: we can get an MVT::ValueType for this LLVM IR type.
111 ValueVTs.push_back(TLI.getValueType(Ty));
112}
Dan Gohman23ce5022008-04-25 18:27:55 +0000113
Chris Lattnerf899fce2008-04-27 23:48:12 +0000114namespace {
Dan Gohman0fe00902008-04-28 18:10:39 +0000115 /// RegsForValue - This struct represents the registers (physical or virtual)
116 /// that a particular set of values is assigned, and the type information about
117 /// the value. The most common situation is to represent one value at a time,
118 /// but struct or array values are handled element-wise as multiple values.
119 /// The splitting of aggregates is performed recursively, so that we never
120 /// have aggregate-typed registers. The values at this point do not necessarily
121 /// have legal types, so each value may require one or more registers of some
122 /// legal type.
123 ///
Chris Lattner95255282006-06-28 23:17:24 +0000124 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000125 /// TLI - The TargetLowering object.
Dan Gohman0fe00902008-04-28 18:10:39 +0000126 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000127 const TargetLowering *TLI;
128
Dan Gohman0fe00902008-04-28 18:10:39 +0000129 /// ValueVTs - The value types of the values, which may not be legal, and
130 /// may need be promoted or synthesized from one or more registers.
131 ///
132 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000133
Dan Gohman0fe00902008-04-28 18:10:39 +0000134 /// RegVTs - The value types of the registers. This is the same size as
135 /// ValueVTs and it records, for each value, what the type of the assigned
136 /// register or registers are. (Individual values are never synthesized
137 /// from more than one type of register.)
138 ///
139 /// With virtual registers, the contents of RegVTs is redundant with TLI's
140 /// getRegisterType member function, however when with physical registers
141 /// it is necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000142 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000143 SmallVector<MVT::ValueType, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000144
Dan Gohman0fe00902008-04-28 18:10:39 +0000145 /// Regs - This list holds the registers assigned to the values.
146 /// Each legal or promoted value requires one register, and each
147 /// expanded value requires multiple registers.
148 ///
149 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000150
Dan Gohman23ce5022008-04-25 18:27:55 +0000151 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000152
Dan Gohman23ce5022008-04-25 18:27:55 +0000153 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000154 const SmallVector<unsigned, 4> &regs,
Chris Lattner864635a2006-02-22 22:37:12 +0000155 MVT::ValueType regvt, MVT::ValueType valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000156 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000157 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000158 const SmallVector<unsigned, 4> &regs,
Dan Gohman23ce5022008-04-25 18:27:55 +0000159 const SmallVector<MVT::ValueType, 4> &regvts,
160 const SmallVector<MVT::ValueType, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000161 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000162 RegsForValue(const TargetLowering &tli,
163 unsigned Reg, const Type *Ty) : TLI(&tli) {
164 ComputeValueVTs(tli, Ty, ValueVTs);
165
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000166 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000167 MVT::ValueType ValueVT = ValueVTs[Value];
168 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
169 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
170 for (unsigned i = 0; i != NumRegs; ++i)
171 Regs.push_back(Reg + i);
172 RegVTs.push_back(RegisterVT);
173 Reg += NumRegs;
174 }
Chris Lattner864635a2006-02-22 22:37:12 +0000175 }
176
Chris Lattner41f62592008-04-29 04:29:54 +0000177 /// append - Add the specified values to this one.
178 void append(const RegsForValue &RHS) {
179 TLI = RHS.TLI;
180 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
181 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
182 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
183 }
184
185
Chris Lattner864635a2006-02-22 22:37:12 +0000186 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000187 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000188 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000189 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000190 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000191 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000192
193 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
194 /// specified value into the registers specified by this object. This uses
195 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000196 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000197 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000198 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000199
200 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
201 /// operand list. This adds the code marker and includes the number of
202 /// values added into it.
203 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000204 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000205 };
206}
Evan Cheng4ef10862006-01-23 07:01:07 +0000207
Chris Lattner1c08c712005-01-07 07:47:53 +0000208namespace llvm {
209 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000210 /// createDefaultScheduler - This creates an instruction scheduler appropriate
211 /// for the target.
212 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
213 SelectionDAG *DAG,
214 MachineBasicBlock *BB) {
215 TargetLowering &TLI = IS->getTargetLowering();
216
217 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
218 return createTDListDAGScheduler(IS, DAG, BB);
219 } else {
220 assert(TLI.getSchedulingPreference() ==
221 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
222 return createBURRListDAGScheduler(IS, DAG, BB);
223 }
224 }
225
226
227 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 /// FunctionLoweringInfo - This contains information that is global to a
229 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000230 class FunctionLoweringInfo {
231 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000232 TargetLowering &TLI;
233 Function &Fn;
234 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000235 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000236
237 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
238
239 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
240 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
241
242 /// ValueMap - Since we emit code for the function a basic block at a time,
243 /// we must remember which virtual registers hold the values for
244 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000245 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000246
247 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
248 /// the entry block. This allows the allocas to be efficiently referenced
249 /// anywhere in the function.
250 std::map<const AllocaInst*, int> StaticAllocaMap;
251
Duncan Sandsf4070822007-06-15 19:04:19 +0000252#ifndef NDEBUG
253 SmallSet<Instruction*, 8> CatchInfoLost;
254 SmallSet<Instruction*, 8> CatchInfoFound;
255#endif
256
Chris Lattner1c08c712005-01-07 07:47:53 +0000257 unsigned MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000258 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000259 }
Chris Lattner571e4342006-10-27 21:36:01 +0000260
261 /// isExportedInst - Return true if the specified value is an instruction
262 /// exported from its block.
263 bool isExportedInst(const Value *V) {
264 return ValueMap.count(V);
265 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000266
Chris Lattner3c384492006-03-16 19:51:18 +0000267 unsigned CreateRegForValue(const Value *V);
268
Chris Lattner1c08c712005-01-07 07:47:53 +0000269 unsigned InitializeRegForValue(const Value *V) {
270 unsigned &R = ValueMap[V];
271 assert(R == 0 && "Already initialized this value register!");
272 return R = CreateRegForValue(V);
273 }
274 };
275}
276
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000277/// isSelector - Return true if this instruction is a call to the
278/// eh.selector intrinsic.
279static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000280 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000281 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
282 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000283 return false;
284}
285
Chris Lattner1c08c712005-01-07 07:47:53 +0000286/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000287/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000288/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000289static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
290 if (isa<PHINode>(I)) return true;
291 BasicBlock *BB = I->getParent();
292 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000293 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000294 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000295 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000296 return true;
297 return false;
298}
299
Chris Lattnerbf209482005-10-30 19:42:35 +0000300/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000301/// entry block, return true. This includes arguments used by switches, since
302/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000303static bool isOnlyUsedInEntryBlock(Argument *A) {
304 BasicBlock *Entry = A->getParent()->begin();
305 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000306 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000307 return false; // Use not in entry block.
308 return true;
309}
310
Chris Lattner1c08c712005-01-07 07:47:53 +0000311FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000312 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000313 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000314
Chris Lattnerbf209482005-10-30 19:42:35 +0000315 // Create a vreg for each argument register that is not dead and is used
316 // outside of the entry block for the function.
317 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
318 AI != E; ++AI)
319 if (!isOnlyUsedInEntryBlock(AI))
320 InitializeRegForValue(AI);
321
Chris Lattner1c08c712005-01-07 07:47:53 +0000322 // Initialize the mapping of values to registers. This is only set up for
323 // instruction values that are used outside of the block that defines
324 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000325 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000326 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
327 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000328 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000329 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000330 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000331 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000332 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000333 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000334
Reid Spencerb83eb642006-10-20 07:07:24 +0000335 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000336 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000337 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000338 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000339 }
340
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000341 for (; BB != EB; ++BB)
342 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000343 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
344 if (!isa<AllocaInst>(I) ||
345 !StaticAllocaMap.count(cast<AllocaInst>(I)))
346 InitializeRegForValue(I);
347
348 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
349 // also creates the initial PHI MachineInstrs, though none of the input
350 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000351 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000352 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
353 MBBMap[BB] = MBB;
354 MF.getBasicBlockList().push_back(MBB);
355
356 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
357 // appropriate.
358 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000359 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
360 if (PN->use_empty()) continue;
361
362 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000363 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000364 unsigned PHIReg = ValueMap[PN];
365 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000366 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000367 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000368 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000369 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000370 }
371}
372
Chris Lattner3c384492006-03-16 19:51:18 +0000373/// CreateRegForValue - Allocate the appropriate number of virtual registers of
374/// the correctly promoted or expanded types. Assign these registers
375/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000376///
377/// In the case that the given value has struct or array type, this function
378/// will assign registers for each member or element.
379///
Chris Lattner3c384492006-03-16 19:51:18 +0000380unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000381 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000382 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000383
Dan Gohman23ce5022008-04-25 18:27:55 +0000384 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000385 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000386 MVT::ValueType ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000387 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000388
Chris Lattnerb606dba2008-04-28 06:44:42 +0000389 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000390 for (unsigned i = 0; i != NumRegs; ++i) {
391 unsigned R = MakeReg(RegisterVT);
392 if (!FirstReg) FirstReg = R;
393 }
394 }
395 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000396}
Chris Lattner1c08c712005-01-07 07:47:53 +0000397
398//===----------------------------------------------------------------------===//
399/// SelectionDAGLowering - This is the common target-independent lowering
400/// implementation that is parameterized by a TargetLowering object.
401/// Also, targets can overload any lowering method.
402///
403namespace llvm {
404class SelectionDAGLowering {
405 MachineBasicBlock *CurMBB;
406
Chris Lattner0da331f2007-02-04 01:31:47 +0000407 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000408
Chris Lattnerd3948112005-01-17 22:19:26 +0000409 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
410 /// them up and then emit token factor nodes when possible. This allows us to
411 /// get simple disambiguation between loads without worrying about alias
412 /// analysis.
413 std::vector<SDOperand> PendingLoads;
414
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000415 /// PendingExports - CopyToReg nodes that copy values to virtual registers
416 /// for export to other blocks need to be emitted before any terminator
417 /// instruction, but they have no other ordering requirements. We bunch them
418 /// up and the emit a single tokenfactor for them just before terminator
419 /// instructions.
420 std::vector<SDOperand> PendingExports;
421
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000422 /// Case - A struct to record the Value for a switch case, and the
423 /// case's target basic block.
424 struct Case {
425 Constant* Low;
426 Constant* High;
427 MachineBasicBlock* BB;
428
429 Case() : Low(0), High(0), BB(0) { }
430 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
431 Low(low), High(high), BB(bb) { }
432 uint64_t size() const {
433 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
434 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
435 return (rHigh - rLow + 1ULL);
436 }
437 };
438
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000439 struct CaseBits {
440 uint64_t Mask;
441 MachineBasicBlock* BB;
442 unsigned Bits;
443
444 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
445 Mask(mask), BB(bb), Bits(bits) { }
446 };
447
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000448 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000449 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000450 typedef CaseVector::iterator CaseItr;
451 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000452
453 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
454 /// of conditional branches.
455 struct CaseRec {
456 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
457 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
458
459 /// CaseBB - The MBB in which to emit the compare and branch
460 MachineBasicBlock *CaseBB;
461 /// LT, GE - If nonzero, we know the current case value must be less-than or
462 /// greater-than-or-equal-to these Constants.
463 Constant *LT;
464 Constant *GE;
465 /// Range - A pair of iterators representing the range of case values to be
466 /// processed at this point in the binary search tree.
467 CaseRange Range;
468 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000469
470 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000471
472 /// The comparison function for sorting the switch case values in the vector.
473 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000474 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000475 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000476 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
477 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
478 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
479 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000480 }
481 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000482
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000483 struct CaseBitsCmp {
484 bool operator () (const CaseBits& C1, const CaseBits& C2) {
485 return C1.Bits > C2.Bits;
486 }
487 };
488
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000489 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000490
Chris Lattner1c08c712005-01-07 07:47:53 +0000491public:
492 // TLI - This is information that describes the available target features we
493 // need for lowering. This indicates when operations are unavailable,
494 // implemented with a libcall, etc.
495 TargetLowering &TLI;
496 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000497 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000498 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000499
Nate Begemanf15485a2006-03-27 01:32:24 +0000500 /// SwitchCases - Vector of CaseBlock structures used to communicate
501 /// SwitchInst code generation information.
502 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000503 /// JTCases - Vector of JumpTable structures used to communicate
504 /// SwitchInst code generation information.
505 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000506 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000507
Chris Lattner1c08c712005-01-07 07:47:53 +0000508 /// FuncInfo - Information about the function as a whole.
509 ///
510 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000511
512 /// GCI - Garbage collection metadata for the function.
513 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000514
515 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000516 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000517 FunctionLoweringInfo &funcinfo,
518 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000519 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000520 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000521 }
522
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000523 /// getRoot - Return the current virtual root of the Selection DAG,
524 /// flushing any PendingLoad items. This must be done before emitting
525 /// a store or any other node that may need to be ordered after any
526 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000527 ///
528 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000529 if (PendingLoads.empty())
530 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000531
Chris Lattnerd3948112005-01-17 22:19:26 +0000532 if (PendingLoads.size() == 1) {
533 SDOperand Root = PendingLoads[0];
534 DAG.setRoot(Root);
535 PendingLoads.clear();
536 return Root;
537 }
538
539 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000540 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
541 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000542 PendingLoads.clear();
543 DAG.setRoot(Root);
544 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000545 }
546
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000547 /// getControlRoot - Similar to getRoot, but instead of flushing all the
548 /// PendingLoad items, flush all the PendingExports items. It is necessary
549 /// to do this before emitting a terminator instruction.
550 ///
551 SDOperand getControlRoot() {
552 SDOperand Root = DAG.getRoot();
553
554 if (PendingExports.empty())
555 return Root;
556
557 // Turn all of the CopyToReg chains into one factored node.
558 if (Root.getOpcode() != ISD::EntryToken) {
559 unsigned i = 0, e = PendingExports.size();
560 for (; i != e; ++i) {
561 assert(PendingExports[i].Val->getNumOperands() > 1);
562 if (PendingExports[i].Val->getOperand(0) == Root)
563 break; // Don't add the root if we already indirectly depend on it.
564 }
565
566 if (i == e)
567 PendingExports.push_back(Root);
568 }
569
570 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
571 &PendingExports[0],
572 PendingExports.size());
573 PendingExports.clear();
574 DAG.setRoot(Root);
575 return Root;
576 }
577
578 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000579
Chris Lattner1c08c712005-01-07 07:47:53 +0000580 void visit(Instruction &I) { visit(I.getOpcode(), I); }
581
582 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000583 // Note: this doesn't use InstVisitor, because it has to work with
584 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000585 switch (Opcode) {
586 default: assert(0 && "Unknown instruction type encountered!");
587 abort();
588 // Build the switch statement using the Instruction.def file.
589#define HANDLE_INST(NUM, OPCODE, CLASS) \
590 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
591#include "llvm/Instruction.def"
592 }
593 }
594
595 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
596
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000597 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000598 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000599 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000600
Chris Lattner199862b2006-03-16 19:57:50 +0000601 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000602
Chris Lattner0da331f2007-02-04 01:31:47 +0000603 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000604 SDOperand &N = NodeMap[V];
605 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000606 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000607 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000608
Evan Cheng5c807602008-02-26 02:33:44 +0000609 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000610 std::set<unsigned> &OutputRegs,
611 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000612
Chris Lattner571e4342006-10-27 21:36:01 +0000613 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
614 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
615 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000616 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000617 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000618 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000619 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000620
Chris Lattner1c08c712005-01-07 07:47:53 +0000621 // Terminator instructions.
622 void visitRet(ReturnInst &I);
623 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000624 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000625 void visitUnreachable(UnreachableInst &I) { /* noop */ }
626
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000627 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000628 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000629 CaseRecVector& WorkList,
630 Value* SV,
631 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000632 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000633 CaseRecVector& WorkList,
634 Value* SV,
635 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000636 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000637 CaseRecVector& WorkList,
638 Value* SV,
639 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000640 bool handleBitTestsSwitchCase(CaseRec& CR,
641 CaseRecVector& WorkList,
642 Value* SV,
643 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000644 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000645 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
646 void visitBitTestCase(MachineBasicBlock* NextMBB,
647 unsigned Reg,
648 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000649 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000650 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
651 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000652
Chris Lattner1c08c712005-01-07 07:47:53 +0000653 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000654 void visitInvoke(InvokeInst &I);
655 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000656
Dan Gohman7f321562007-06-25 16:23:39 +0000657 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000658 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000659 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000660 if (I.getType()->isFPOrFPVector())
661 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000662 else
Dan Gohman7f321562007-06-25 16:23:39 +0000663 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000664 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000665 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000666 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000667 if (I.getType()->isFPOrFPVector())
668 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000669 else
Dan Gohman7f321562007-06-25 16:23:39 +0000670 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000671 }
Dan Gohman7f321562007-06-25 16:23:39 +0000672 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
673 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
674 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
675 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
676 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
677 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
678 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
679 void visitOr (User &I) { visitBinary(I, ISD::OR); }
680 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000681 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000682 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
683 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000684 void visitICmp(User &I);
685 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000686 void visitVICmp(User &I);
687 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000688 // Visit the conversion instructions
689 void visitTrunc(User &I);
690 void visitZExt(User &I);
691 void visitSExt(User &I);
692 void visitFPTrunc(User &I);
693 void visitFPExt(User &I);
694 void visitFPToUI(User &I);
695 void visitFPToSI(User &I);
696 void visitUIToFP(User &I);
697 void visitSIToFP(User &I);
698 void visitPtrToInt(User &I);
699 void visitIntToPtr(User &I);
700 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000701
Chris Lattner2bbd8102006-03-29 00:11:43 +0000702 void visitExtractElement(User &I);
703 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000704 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000705
Chris Lattner1c08c712005-01-07 07:47:53 +0000706 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000707 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000708
709 void visitMalloc(MallocInst &I);
710 void visitFree(FreeInst &I);
711 void visitAlloca(AllocaInst &I);
712 void visitLoad(LoadInst &I);
713 void visitStore(StoreInst &I);
714 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
715 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000716 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000717 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000718 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000719
Chris Lattner1c08c712005-01-07 07:47:53 +0000720 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000721 void visitVAArg(VAArgInst &I);
722 void visitVAEnd(CallInst &I);
723 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000724
Dan Gohmanef5d1942008-03-11 21:11:25 +0000725 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000726
Chris Lattner1c08c712005-01-07 07:47:53 +0000727 void visitUserOp1(Instruction &I) {
728 assert(0 && "UserOp1 should not exist at instruction selection time!");
729 abort();
730 }
731 void visitUserOp2(Instruction &I) {
732 assert(0 && "UserOp2 should not exist at instruction selection time!");
733 abort();
734 }
Mon P Wang63307c32008-05-05 19:05:59 +0000735
736private:
737 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
738
Chris Lattner1c08c712005-01-07 07:47:53 +0000739};
740} // end namespace llvm
741
Dan Gohman6183f782007-07-05 20:12:34 +0000742
Duncan Sandsb988bac2008-02-11 20:58:28 +0000743/// getCopyFromParts - Create a value that contains the specified legal parts
744/// combined into the value they represent. If the parts combine to a type
745/// larger then ValueVT then AssertOp can be used to specify whether the extra
746/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000747/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000748static SDOperand getCopyFromParts(SelectionDAG &DAG,
749 const SDOperand *Parts,
750 unsigned NumParts,
751 MVT::ValueType PartVT,
752 MVT::ValueType ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000753 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000754 assert(NumParts > 0 && "No parts to assemble!");
755 TargetLowering &TLI = DAG.getTargetLoweringInfo();
756 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000757
Duncan Sands014e04a2008-02-12 20:46:31 +0000758 if (NumParts > 1) {
759 // Assemble the value from multiple parts.
760 if (!MVT::isVector(ValueVT)) {
761 unsigned PartBits = MVT::getSizeInBits(PartVT);
762 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000763
Duncan Sands014e04a2008-02-12 20:46:31 +0000764 // Assemble the power of 2 part.
765 unsigned RoundParts = NumParts & (NumParts - 1) ?
766 1 << Log2_32(NumParts) : NumParts;
767 unsigned RoundBits = PartBits * RoundParts;
768 MVT::ValueType RoundVT = RoundBits == ValueBits ?
769 ValueVT : MVT::getIntegerType(RoundBits);
770 SDOperand Lo, Hi;
771
772 if (RoundParts > 2) {
773 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
774 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
775 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
776 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000777 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000778 Lo = Parts[0];
779 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000780 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000781 if (TLI.isBigEndian())
782 std::swap(Lo, Hi);
783 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
784
785 if (RoundParts < NumParts) {
786 // Assemble the trailing non-power-of-2 part.
787 unsigned OddParts = NumParts - RoundParts;
788 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
789 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
790
791 // Combine the round and odd parts.
792 Lo = Val;
793 if (TLI.isBigEndian())
794 std::swap(Lo, Hi);
795 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
796 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
797 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
798 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
799 TLI.getShiftAmountTy()));
800 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
801 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
802 }
803 } else {
804 // Handle a multi-element vector.
805 MVT::ValueType IntermediateVT, RegisterVT;
806 unsigned NumIntermediates;
807 unsigned NumRegs =
808 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
809 RegisterVT);
Evan Cheng50871242008-05-14 20:07:51 +0000810 NumRegs; // Silence a compiler warning.
Duncan Sands014e04a2008-02-12 20:46:31 +0000811 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
812 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
813 assert(RegisterVT == Parts[0].getValueType() &&
814 "Part type doesn't match part!");
815
816 // Assemble the parts into intermediate operands.
817 SmallVector<SDOperand, 8> Ops(NumIntermediates);
818 if (NumIntermediates == NumParts) {
819 // If the register was not expanded, truncate or copy the value,
820 // as appropriate.
821 for (unsigned i = 0; i != NumParts; ++i)
822 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
823 PartVT, IntermediateVT);
824 } else if (NumParts > 0) {
825 // If the intermediate type was expanded, build the intermediate operands
826 // from the parts.
827 assert(NumParts % NumIntermediates == 0 &&
828 "Must expand into a divisible number of parts!");
829 unsigned Factor = NumParts / NumIntermediates;
830 for (unsigned i = 0; i != NumIntermediates; ++i)
831 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
832 PartVT, IntermediateVT);
833 }
834
835 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
836 // operands.
837 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
838 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
839 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000840 }
Dan Gohman6183f782007-07-05 20:12:34 +0000841 }
842
Duncan Sands014e04a2008-02-12 20:46:31 +0000843 // There is now one part, held in Val. Correct it to match ValueVT.
844 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000845
Duncan Sands014e04a2008-02-12 20:46:31 +0000846 if (PartVT == ValueVT)
847 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000848
Duncan Sands014e04a2008-02-12 20:46:31 +0000849 if (MVT::isVector(PartVT)) {
850 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
851 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000852 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000853
854 if (MVT::isVector(ValueVT)) {
855 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
856 MVT::getVectorNumElements(ValueVT) == 1 &&
857 "Only trivial scalar-to-vector conversions should get here!");
858 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
859 }
860
861 if (MVT::isInteger(PartVT) &&
862 MVT::isInteger(ValueVT)) {
863 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
864 // For a truncate, see if we have any information to
865 // indicate whether the truncated bits will always be
866 // zero or sign-extension.
867 if (AssertOp != ISD::DELETED_NODE)
868 Val = DAG.getNode(AssertOp, PartVT, Val,
869 DAG.getValueType(ValueVT));
870 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
871 } else {
872 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
873 }
874 }
875
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000876 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
877 if (ValueVT < Val.getValueType())
Chris Lattner4468c1f2008-03-09 09:38:46 +0000878 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000879 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000880 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000881 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
882 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000883
884 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
885 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
886
887 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000888 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000889}
890
Duncan Sandsb988bac2008-02-11 20:58:28 +0000891/// getCopyToParts - Create a series of nodes that contain the specified value
892/// split into legal parts. If the parts contain more bits than Val, then, for
893/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000894static void getCopyToParts(SelectionDAG &DAG,
895 SDOperand Val,
896 SDOperand *Parts,
897 unsigned NumParts,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000898 MVT::ValueType PartVT,
899 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000900 TargetLowering &TLI = DAG.getTargetLoweringInfo();
901 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohman6183f782007-07-05 20:12:34 +0000902 MVT::ValueType ValueVT = Val.getValueType();
Duncan Sands014e04a2008-02-12 20:46:31 +0000903 unsigned PartBits = MVT::getSizeInBits(PartVT);
904 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000905
Duncan Sands014e04a2008-02-12 20:46:31 +0000906 if (!NumParts)
907 return;
908
909 if (!MVT::isVector(ValueVT)) {
910 if (PartVT == ValueVT) {
911 assert(NumParts == 1 && "No-op copy with multiple parts!");
912 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000913 return;
914 }
915
Duncan Sands014e04a2008-02-12 20:46:31 +0000916 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
917 // If the parts cover more bits than the value has, promote the value.
918 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
919 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000920 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000921 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
922 ValueVT = MVT::getIntegerType(NumParts * PartBits);
923 Val = DAG.getNode(ExtendKind, ValueVT, Val);
924 } else {
925 assert(0 && "Unknown mismatch!");
926 }
927 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
928 // Different types of the same size.
929 assert(NumParts == 1 && PartVT != ValueVT);
930 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
931 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
932 // If the parts cover less bits than value has, truncate the value.
933 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
934 ValueVT = MVT::getIntegerType(NumParts * PartBits);
935 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000936 } else {
937 assert(0 && "Unknown mismatch!");
938 }
939 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000940
941 // The value may have changed - recompute ValueVT.
942 ValueVT = Val.getValueType();
943 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
944 "Failed to tile the value with PartVT!");
945
946 if (NumParts == 1) {
947 assert(PartVT == ValueVT && "Type conversion failed!");
948 Parts[0] = Val;
949 return;
950 }
951
952 // Expand the value into multiple parts.
953 if (NumParts & (NumParts - 1)) {
954 // The number of parts is not a power of 2. Split off and copy the tail.
955 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
956 "Do not know what to expand to!");
957 unsigned RoundParts = 1 << Log2_32(NumParts);
958 unsigned RoundBits = RoundParts * PartBits;
959 unsigned OddParts = NumParts - RoundParts;
960 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
961 DAG.getConstant(RoundBits,
962 TLI.getShiftAmountTy()));
963 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
964 if (TLI.isBigEndian())
965 // The odd parts were reversed by getCopyToParts - unreverse them.
966 std::reverse(Parts + RoundParts, Parts + NumParts);
967 NumParts = RoundParts;
968 ValueVT = MVT::getIntegerType(NumParts * PartBits);
969 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
970 }
971
972 // The number of parts is a power of 2. Repeatedly bisect the value using
973 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +0000974 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
975 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
976 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000977 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
978 for (unsigned i = 0; i < NumParts; i += StepSize) {
979 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands25eb0432008-03-12 20:30:08 +0000980 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
981 SDOperand &Part0 = Parts[i];
982 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +0000983
Duncan Sands25eb0432008-03-12 20:30:08 +0000984 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
985 DAG.getConstant(1, PtrVT));
986 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
987 DAG.getConstant(0, PtrVT));
988
989 if (ThisBits == PartBits && ThisVT != PartVT) {
990 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
991 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
992 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000993 }
994 }
995
996 if (TLI.isBigEndian())
997 std::reverse(Parts, Parts + NumParts);
998
999 return;
1000 }
1001
1002 // Vector ValueVT.
1003 if (NumParts == 1) {
1004 if (PartVT != ValueVT) {
1005 if (MVT::isVector(PartVT)) {
1006 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1007 } else {
1008 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
1009 MVT::getVectorNumElements(ValueVT) == 1 &&
1010 "Only trivial vector-to-scalar conversions should get here!");
1011 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1012 DAG.getConstant(0, PtrVT));
1013 }
1014 }
1015
Dan Gohman6183f782007-07-05 20:12:34 +00001016 Parts[0] = Val;
1017 return;
1018 }
1019
1020 // Handle a multi-element vector.
1021 MVT::ValueType IntermediateVT, RegisterVT;
1022 unsigned NumIntermediates;
1023 unsigned NumRegs =
1024 DAG.getTargetLoweringInfo()
1025 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1026 RegisterVT);
Evan Cheng50871242008-05-14 20:07:51 +00001027 NumRegs; // Silence a compiler warning.
Dan Gohman6183f782007-07-05 20:12:34 +00001028 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1029
1030 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1031 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1032
1033 // Split the vector into intermediate operands.
1034 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1035 for (unsigned i = 0; i != NumIntermediates; ++i)
1036 if (MVT::isVector(IntermediateVT))
1037 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1038 IntermediateVT, Val,
1039 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001040 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001041 else
1042 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1043 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001044 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001045
1046 // Split the intermediate operands into legal parts.
1047 if (NumParts == NumIntermediates) {
1048 // If the register was not expanded, promote or copy the value,
1049 // as appropriate.
1050 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001051 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001052 } else if (NumParts > 0) {
1053 // If the intermediate type was expanded, split each the value into
1054 // legal parts.
1055 assert(NumParts % NumIntermediates == 0 &&
1056 "Must expand into a divisible number of parts!");
1057 unsigned Factor = NumParts / NumIntermediates;
1058 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001059 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001060 }
1061}
1062
1063
Chris Lattner199862b2006-03-16 19:57:50 +00001064SDOperand SelectionDAGLowering::getValue(const Value *V) {
1065 SDOperand &N = NodeMap[V];
1066 if (N.Val) return N;
1067
Chris Lattner199862b2006-03-16 19:57:50 +00001068 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Chris Lattner6833b062008-04-28 07:16:35 +00001069 MVT::ValueType VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001070
1071 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1072 return N = DAG.getConstant(CI->getValue(), VT);
1073
1074 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001075 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001076
1077 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001078 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001079
1080 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1081 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1082
Chris Lattner6833b062008-04-28 07:16:35 +00001083 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1084 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001085
1086 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1087 visit(CE->getOpcode(), *CE);
1088 SDOperand N1 = NodeMap[V];
1089 assert(N1.Val && "visit didn't populate the ValueMap!");
1090 return N1;
1091 }
1092
Chris Lattner6833b062008-04-28 07:16:35 +00001093 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001094 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001095
Chris Lattner6833b062008-04-28 07:16:35 +00001096 // Now that we know the number and type of the elements, get that number of
1097 // elements into the Ops array based on what kind of constant it is.
1098 SmallVector<SDOperand, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001099 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1100 for (unsigned i = 0; i != NumElements; ++i)
1101 Ops.push_back(getValue(CP->getOperand(i)));
1102 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001103 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1104 "Unknown vector constant!");
1105 MVT::ValueType EltVT = TLI.getValueType(VecTy->getElementType());
1106
Chris Lattnerb606dba2008-04-28 06:44:42 +00001107 SDOperand Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001108 if (isa<UndefValue>(C))
1109 Op = DAG.getNode(ISD::UNDEF, EltVT);
1110 else if (MVT::isFloatingPoint(EltVT))
1111 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001112 else
Chris Lattner6833b062008-04-28 07:16:35 +00001113 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001114 Ops.assign(NumElements, Op);
1115 }
1116
1117 // Create a BUILD_VECTOR node.
1118 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001119 }
1120
Chris Lattnerb606dba2008-04-28 06:44:42 +00001121 // If this is a static alloca, generate it as the frameindex instead of
1122 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001123 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1124 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001125 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001126 if (SI != FuncInfo.StaticAllocaMap.end())
1127 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1128 }
1129
Chris Lattner251db182007-02-25 18:40:32 +00001130 unsigned InReg = FuncInfo.ValueMap[V];
1131 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001132
Chris Lattner6833b062008-04-28 07:16:35 +00001133 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001134 SDOperand Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001135 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001136}
1137
1138
Chris Lattner1c08c712005-01-07 07:47:53 +00001139void SelectionDAGLowering::visitRet(ReturnInst &I) {
1140 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001141 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001142 return;
1143 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001144
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001145 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001146 NewValues.push_back(getControlRoot());
1147 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001148 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001149 MVT::ValueType VT = RetOp.getValueType();
1150
Evan Cheng8e7d0562006-05-26 23:09:09 +00001151 // FIXME: C calling convention requires the return type to be promoted to
1152 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sandsb988bac2008-02-11 20:58:28 +00001153 if (MVT::isInteger(VT)) {
1154 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1155 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1156 VT = MinVT;
1157 }
1158
1159 unsigned NumParts = TLI.getNumRegisters(VT);
1160 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1161 SmallVector<SDOperand, 4> Parts(NumParts);
1162 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1163
1164 const Function *F = I.getParent()->getParent();
1165 if (F->paramHasAttr(0, ParamAttr::SExt))
1166 ExtendKind = ISD::SIGN_EXTEND;
1167 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1168 ExtendKind = ISD::ZERO_EXTEND;
1169
1170 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1171
1172 for (unsigned i = 0; i < NumParts; ++i) {
1173 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001174 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001175 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001176 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001177 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1178 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001179}
1180
Chris Lattner571e4342006-10-27 21:36:01 +00001181/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1182/// the current basic block, add it to ValueMap now so that we'll get a
1183/// CopyTo/FromReg.
1184void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1185 // No need to export constants.
1186 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1187
1188 // Already exported?
1189 if (FuncInfo.isExportedInst(V)) return;
1190
1191 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001192 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001193}
1194
Chris Lattner8c494ab2006-10-27 23:50:33 +00001195bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1196 const BasicBlock *FromBB) {
1197 // The operands of the setcc have to be in this block. We don't know
1198 // how to export them from some other block.
1199 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1200 // Can export from current BB.
1201 if (VI->getParent() == FromBB)
1202 return true;
1203
1204 // Is already exported, noop.
1205 return FuncInfo.isExportedInst(V);
1206 }
1207
1208 // If this is an argument, we can export it if the BB is the entry block or
1209 // if it is already exported.
1210 if (isa<Argument>(V)) {
1211 if (FromBB == &FromBB->getParent()->getEntryBlock())
1212 return true;
1213
1214 // Otherwise, can only export this if it is already exported.
1215 return FuncInfo.isExportedInst(V);
1216 }
1217
1218 // Otherwise, constants can always be exported.
1219 return true;
1220}
1221
Chris Lattner6a586c82006-10-29 21:01:20 +00001222static bool InBlock(const Value *V, const BasicBlock *BB) {
1223 if (const Instruction *I = dyn_cast<Instruction>(V))
1224 return I->getParent() == BB;
1225 return true;
1226}
1227
Chris Lattner571e4342006-10-27 21:36:01 +00001228/// FindMergedConditions - If Cond is an expression like
1229void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1230 MachineBasicBlock *TBB,
1231 MachineBasicBlock *FBB,
1232 MachineBasicBlock *CurBB,
1233 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001234 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001235 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001236
Reid Spencere4d87aa2006-12-23 06:05:41 +00001237 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1238 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001239 BOp->getParent() != CurBB->getBasicBlock() ||
1240 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1241 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001242 const BasicBlock *BB = CurBB->getBasicBlock();
1243
Reid Spencere4d87aa2006-12-23 06:05:41 +00001244 // If the leaf of the tree is a comparison, merge the condition into
1245 // the caseblock.
1246 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1247 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001248 // how to export them from some other block. If this is the first block
1249 // of the sequence, no exporting is needed.
1250 (CurBB == CurMBB ||
1251 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1252 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001253 BOp = cast<Instruction>(Cond);
1254 ISD::CondCode Condition;
1255 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1256 switch (IC->getPredicate()) {
1257 default: assert(0 && "Unknown icmp predicate opcode!");
1258 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1259 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1260 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1261 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1262 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1263 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1264 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1265 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1266 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1267 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1268 }
1269 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1270 ISD::CondCode FPC, FOC;
1271 switch (FC->getPredicate()) {
1272 default: assert(0 && "Unknown fcmp predicate opcode!");
1273 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1274 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1275 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1276 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1277 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1278 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1279 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001280 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1281 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001282 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1283 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1284 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1285 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1286 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1287 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1288 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1289 }
1290 if (FiniteOnlyFPMath())
1291 Condition = FOC;
1292 else
1293 Condition = FPC;
1294 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001295 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001296 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001297 }
1298
Chris Lattner571e4342006-10-27 21:36:01 +00001299 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001300 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001301 SwitchCases.push_back(CB);
1302 return;
1303 }
1304
1305 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001306 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001307 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001308 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001309 return;
1310 }
1311
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001312
1313 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001314 MachineFunction::iterator BBI = CurBB;
1315 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1316 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1317
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001318 if (Opc == Instruction::Or) {
1319 // Codegen X | Y as:
1320 // jmp_if_X TBB
1321 // jmp TmpBB
1322 // TmpBB:
1323 // jmp_if_Y TBB
1324 // jmp FBB
1325 //
Chris Lattner571e4342006-10-27 21:36:01 +00001326
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001327 // Emit the LHS condition.
1328 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1329
1330 // Emit the RHS condition into TmpBB.
1331 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1332 } else {
1333 assert(Opc == Instruction::And && "Unknown merge op!");
1334 // Codegen X & Y as:
1335 // jmp_if_X TmpBB
1336 // jmp FBB
1337 // TmpBB:
1338 // jmp_if_Y TBB
1339 // jmp FBB
1340 //
1341 // This requires creation of TmpBB after CurBB.
1342
1343 // Emit the LHS condition.
1344 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1345
1346 // Emit the RHS condition into TmpBB.
1347 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1348 }
Chris Lattner571e4342006-10-27 21:36:01 +00001349}
1350
Chris Lattnerdf19f272006-10-31 22:37:42 +00001351/// If the set of cases should be emitted as a series of branches, return true.
1352/// If we should emit this as a bunch of and/or'd together conditions, return
1353/// false.
1354static bool
1355ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1356 if (Cases.size() != 2) return true;
1357
Chris Lattner0ccb5002006-10-31 23:06:00 +00001358 // If this is two comparisons of the same values or'd or and'd together, they
1359 // will get folded into a single comparison, so don't emit two blocks.
1360 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1361 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1362 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1363 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1364 return false;
1365 }
1366
Chris Lattnerdf19f272006-10-31 22:37:42 +00001367 return true;
1368}
1369
Chris Lattner1c08c712005-01-07 07:47:53 +00001370void SelectionDAGLowering::visitBr(BranchInst &I) {
1371 // Update machine-CFG edges.
1372 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001373
1374 // Figure out which block is immediately after the current one.
1375 MachineBasicBlock *NextBlock = 0;
1376 MachineFunction::iterator BBI = CurMBB;
1377 if (++BBI != CurMBB->getParent()->end())
1378 NextBlock = BBI;
1379
1380 if (I.isUnconditional()) {
1381 // If this is not a fall-through branch, emit the branch.
1382 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001383 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001384 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001385
Chris Lattner57ab6592006-10-24 17:57:59 +00001386 // Update machine-CFG edges.
1387 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner57ab6592006-10-24 17:57:59 +00001388 return;
1389 }
1390
1391 // If this condition is one of the special cases we handle, do special stuff
1392 // now.
1393 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001394 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001395
1396 // If this is a series of conditions that are or'd or and'd together, emit
1397 // this as a sequence of branches instead of setcc's with and/or operations.
1398 // For example, instead of something like:
1399 // cmp A, B
1400 // C = seteq
1401 // cmp D, E
1402 // F = setle
1403 // or C, F
1404 // jnz foo
1405 // Emit:
1406 // cmp A, B
1407 // je foo
1408 // cmp D, E
1409 // jle foo
1410 //
1411 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1412 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001413 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001414 BOp->getOpcode() == Instruction::Or)) {
1415 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001416 // If the compares in later blocks need to use values not currently
1417 // exported from this block, export them now. This block should always
1418 // be the first entry.
1419 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1420
Chris Lattnerdf19f272006-10-31 22:37:42 +00001421 // Allow some cases to be rejected.
1422 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001423 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1424 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1425 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1426 }
1427
1428 // Emit the branch for this block.
1429 visitSwitchCase(SwitchCases[0]);
1430 SwitchCases.erase(SwitchCases.begin());
1431 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001432 }
1433
Chris Lattner0ccb5002006-10-31 23:06:00 +00001434 // Okay, we decided not to do this, remove any inserted MBB's and clear
1435 // SwitchCases.
1436 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1437 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1438
Chris Lattnerdf19f272006-10-31 22:37:42 +00001439 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001440 }
1441 }
Chris Lattner24525952006-10-24 18:07:37 +00001442
1443 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001444 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001445 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001446 // Use visitSwitchCase to actually insert the fast branch sequence for this
1447 // cond branch.
1448 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001449}
1450
Nate Begemanf15485a2006-03-27 01:32:24 +00001451/// visitSwitchCase - Emits the necessary code to represent a single node in
1452/// the binary search tree resulting from lowering a switch instruction.
1453void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001454 SDOperand Cond;
1455 SDOperand CondLHS = getValue(CB.CmpLHS);
1456
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001457 // Build the setcc now.
1458 if (CB.CmpMHS == NULL) {
1459 // Fold "(X == true)" to X and "(X == false)" to !X to
1460 // handle common cases produced by branch lowering.
1461 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1462 Cond = CondLHS;
1463 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1464 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1465 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1466 } else
1467 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1468 } else {
1469 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001470
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001471 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1472 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1473
1474 SDOperand CmpOp = getValue(CB.CmpMHS);
1475 MVT::ValueType VT = CmpOp.getValueType();
1476
1477 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1478 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1479 } else {
1480 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1481 Cond = DAG.getSetCC(MVT::i1, SUB,
1482 DAG.getConstant(High-Low, VT), ISD::SETULE);
1483 }
1484
1485 }
1486
Nate Begemanf15485a2006-03-27 01:32:24 +00001487 // Set NextBlock to be the MBB immediately after the current one, if any.
1488 // This is used to avoid emitting unnecessary branches to the next block.
1489 MachineBasicBlock *NextBlock = 0;
1490 MachineFunction::iterator BBI = CurMBB;
1491 if (++BBI != CurMBB->getParent()->end())
1492 NextBlock = BBI;
1493
1494 // If the lhs block is the next block, invert the condition so that we can
1495 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001496 if (CB.TrueBB == NextBlock) {
1497 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001498 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1499 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1500 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001501 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001502 DAG.getBasicBlock(CB.TrueBB));
1503 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001504 DAG.setRoot(BrCond);
1505 else
1506 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001507 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001508 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001509 CurMBB->addSuccessor(CB.TrueBB);
1510 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001511}
1512
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001513/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001514void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001515 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001516 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001517 MVT::ValueType PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001518 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001519 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1520 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1521 Table, Index));
1522 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001523}
1524
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001525/// visitJumpTableHeader - This function emits necessary code to produce index
1526/// in the JumpTable from switch case.
1527void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1528 SelectionDAGISel::JumpTableHeader &JTH) {
1529 // Subtract the lowest switch case value from the value being switched on
1530 // and conditional branch to default mbb if the result is greater than the
1531 // difference between smallest and largest cases.
1532 SDOperand SwitchOp = getValue(JTH.SValue);
1533 MVT::ValueType VT = SwitchOp.getValueType();
1534 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1535 DAG.getConstant(JTH.First, VT));
1536
1537 // The SDNode we just created, which holds the value being switched on
1538 // minus the the smallest case value, needs to be copied to a virtual
1539 // register so it can be used as an index into the jump table in a
1540 // subsequent basic block. This value may be smaller or larger than the
1541 // target's pointer type, and therefore require extension or truncating.
Dan Gohman7f321562007-06-25 16:23:39 +00001542 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001543 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1544 else
1545 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1546
1547 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001548 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001549 JT.Reg = JumpTableReg;
1550
1551 // Emit the range check for the jump table, and branch to the default
1552 // block for the switch statement if the value being switched on exceeds
1553 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001554 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001555 DAG.getConstant(JTH.Last-JTH.First,VT),
1556 ISD::SETUGT);
1557
1558 // Set NextBlock to be the MBB immediately after the current one, if any.
1559 // This is used to avoid emitting unnecessary branches to the next block.
1560 MachineBasicBlock *NextBlock = 0;
1561 MachineFunction::iterator BBI = CurMBB;
1562 if (++BBI != CurMBB->getParent()->end())
1563 NextBlock = BBI;
1564
1565 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1566 DAG.getBasicBlock(JT.Default));
1567
1568 if (JT.MBB == NextBlock)
1569 DAG.setRoot(BrCond);
1570 else
1571 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001572 DAG.getBasicBlock(JT.MBB)));
1573
1574 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001575}
1576
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001577/// visitBitTestHeader - This function emits necessary code to produce value
1578/// suitable for "bit tests"
1579void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1580 // Subtract the minimum value
1581 SDOperand SwitchOp = getValue(B.SValue);
1582 MVT::ValueType VT = SwitchOp.getValueType();
1583 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1584 DAG.getConstant(B.First, VT));
1585
1586 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001587 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001588 DAG.getConstant(B.Range, VT),
1589 ISD::SETUGT);
1590
1591 SDOperand ShiftOp;
Dan Gohman7f321562007-06-25 16:23:39 +00001592 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001593 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1594 else
1595 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1596
1597 // Make desired shift
1598 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1599 DAG.getConstant(1, TLI.getPointerTy()),
1600 ShiftOp);
1601
1602 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001603 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001604 B.Reg = SwitchReg;
1605
1606 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1607 DAG.getBasicBlock(B.Default));
1608
1609 // Set NextBlock to be the MBB immediately after the current one, if any.
1610 // This is used to avoid emitting unnecessary branches to the next block.
1611 MachineBasicBlock *NextBlock = 0;
1612 MachineFunction::iterator BBI = CurMBB;
1613 if (++BBI != CurMBB->getParent()->end())
1614 NextBlock = BBI;
1615
1616 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1617 if (MBB == NextBlock)
1618 DAG.setRoot(BrRange);
1619 else
1620 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1621 DAG.getBasicBlock(MBB)));
1622
1623 CurMBB->addSuccessor(B.Default);
1624 CurMBB->addSuccessor(MBB);
1625
1626 return;
1627}
1628
1629/// visitBitTestCase - this function produces one "bit test"
1630void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1631 unsigned Reg,
1632 SelectionDAGISel::BitTestCase &B) {
1633 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001634 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001635
1636 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1637 SwitchVal,
1638 DAG.getConstant(B.Mask,
1639 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001640 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001641 DAG.getConstant(0, TLI.getPointerTy()),
1642 ISD::SETNE);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001643 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001644 AndCmp, DAG.getBasicBlock(B.TargetBB));
1645
1646 // Set NextBlock to be the MBB immediately after the current one, if any.
1647 // This is used to avoid emitting unnecessary branches to the next block.
1648 MachineBasicBlock *NextBlock = 0;
1649 MachineFunction::iterator BBI = CurMBB;
1650 if (++BBI != CurMBB->getParent()->end())
1651 NextBlock = BBI;
1652
1653 if (NextMBB == NextBlock)
1654 DAG.setRoot(BrAnd);
1655 else
1656 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1657 DAG.getBasicBlock(NextMBB)));
1658
1659 CurMBB->addSuccessor(B.TargetBB);
1660 CurMBB->addSuccessor(NextMBB);
1661
1662 return;
1663}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001664
Jim Laskeyb180aa12007-02-21 22:53:45 +00001665void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1666 // Retrieve successors.
1667 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001668 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001669
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001670 if (isa<InlineAsm>(I.getCalledValue()))
1671 visitInlineAsm(&I);
1672 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001673 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001674
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001675 // If the value of the invoke is used outside of its defining block, make it
1676 // available as a virtual register.
1677 if (!I.use_empty()) {
1678 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1679 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001680 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001681 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001682
1683 // Drop into normal successor.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001684 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001685 DAG.getBasicBlock(Return)));
1686
1687 // Update successor info
1688 CurMBB->addSuccessor(Return);
1689 CurMBB->addSuccessor(LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001690}
1691
1692void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1693}
1694
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001695/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001696/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001697bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001698 CaseRecVector& WorkList,
1699 Value* SV,
1700 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001701 Case& BackCase = *(CR.Range.second-1);
1702
1703 // Size is the number of Cases represented by this range.
1704 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001705 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001706 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001707
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001708 // Get the MachineFunction which holds the current MBB. This is used when
1709 // inserting any additional MBBs necessary to represent the switch.
1710 MachineFunction *CurMF = CurMBB->getParent();
1711
1712 // Figure out which block is immediately after the current one.
1713 MachineBasicBlock *NextBlock = 0;
1714 MachineFunction::iterator BBI = CR.CaseBB;
1715
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001716 if (++BBI != CurMBB->getParent()->end())
1717 NextBlock = BBI;
1718
1719 // TODO: If any two of the cases has the same destination, and if one value
1720 // is the same as the other, but has one bit unset that the other has set,
1721 // use bit manipulation to do two compares at once. For example:
1722 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1723
1724 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001725 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001726 // The last case block won't fall through into 'NextBlock' if we emit the
1727 // branches in this order. See if rearranging a case value would help.
1728 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001729 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001730 std::swap(*I, BackCase);
1731 break;
1732 }
1733 }
1734 }
1735
1736 // Create a CaseBlock record representing a conditional branch to
1737 // the Case's target mbb if the value being switched on SV is equal
1738 // to C.
1739 MachineBasicBlock *CurBlock = CR.CaseBB;
1740 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1741 MachineBasicBlock *FallThrough;
1742 if (I != E-1) {
1743 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1744 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1745 } else {
1746 // If the last case doesn't match, go to the default block.
1747 FallThrough = Default;
1748 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001749
1750 Value *RHS, *LHS, *MHS;
1751 ISD::CondCode CC;
1752 if (I->High == I->Low) {
1753 // This is just small small case range :) containing exactly 1 case
1754 CC = ISD::SETEQ;
1755 LHS = SV; RHS = I->High; MHS = NULL;
1756 } else {
1757 CC = ISD::SETLE;
1758 LHS = I->Low; MHS = SV; RHS = I->High;
1759 }
1760 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1761 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001762
1763 // If emitting the first comparison, just call visitSwitchCase to emit the
1764 // code into the current block. Otherwise, push the CaseBlock onto the
1765 // vector to be later processed by SDISel, and insert the node's MBB
1766 // before the next MBB.
1767 if (CurBlock == CurMBB)
1768 visitSwitchCase(CB);
1769 else
1770 SwitchCases.push_back(CB);
1771
1772 CurBlock = FallThrough;
1773 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001774
1775 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001776}
1777
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001778static inline bool areJTsAllowed(const TargetLowering &TLI) {
1779 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1780 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1781}
1782
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001783/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001784bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001785 CaseRecVector& WorkList,
1786 Value* SV,
1787 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001788 Case& FrontCase = *CR.Range.first;
1789 Case& BackCase = *(CR.Range.second-1);
1790
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001791 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1792 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1793
1794 uint64_t TSize = 0;
1795 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1796 I!=E; ++I)
1797 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001798
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001799 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001800 return false;
1801
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001802 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1803 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001804 return false;
1805
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001806 DOUT << "Lowering jump table\n"
1807 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001808 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001809
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001810 // Get the MachineFunction which holds the current MBB. This is used when
1811 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001812 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001813
1814 // Figure out which block is immediately after the current one.
1815 MachineBasicBlock *NextBlock = 0;
1816 MachineFunction::iterator BBI = CR.CaseBB;
1817
1818 if (++BBI != CurMBB->getParent()->end())
1819 NextBlock = BBI;
1820
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001821 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1822
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001823 // Create a new basic block to hold the code for loading the address
1824 // of the jump table, and jumping to it. Update successor information;
1825 // we will either branch to the default case for the switch, or the jump
1826 // table.
1827 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1828 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1829 CR.CaseBB->addSuccessor(Default);
1830 CR.CaseBB->addSuccessor(JumpTableBB);
1831
1832 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001833 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001834 // a case statement, push the case's BB onto the vector, otherwise, push
1835 // the default BB.
1836 std::vector<MachineBasicBlock*> DestBBs;
1837 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001838 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1839 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1840 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1841
1842 if ((Low <= TEI) && (TEI <= High)) {
1843 DestBBs.push_back(I->BB);
1844 if (TEI==High)
1845 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001846 } else {
1847 DestBBs.push_back(Default);
1848 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001849 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001850
1851 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001852 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001853 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1854 E = DestBBs.end(); I != E; ++I) {
1855 if (!SuccsHandled[(*I)->getNumber()]) {
1856 SuccsHandled[(*I)->getNumber()] = true;
1857 JumpTableBB->addSuccessor(*I);
1858 }
1859 }
1860
1861 // Create a jump table index for this jump table, or return an existing
1862 // one.
1863 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1864
1865 // Set the jump table information so that we can codegen it as a second
1866 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001867 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001868 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1869 (CR.CaseBB == CurMBB));
1870 if (CR.CaseBB == CurMBB)
1871 visitJumpTableHeader(JT, JTH);
1872
1873 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001874
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001875 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001876}
1877
1878/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1879/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001880bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001881 CaseRecVector& WorkList,
1882 Value* SV,
1883 MachineBasicBlock* Default) {
1884 // Get the MachineFunction which holds the current MBB. This is used when
1885 // inserting any additional MBBs necessary to represent the switch.
1886 MachineFunction *CurMF = CurMBB->getParent();
1887
1888 // Figure out which block is immediately after the current one.
1889 MachineBasicBlock *NextBlock = 0;
1890 MachineFunction::iterator BBI = CR.CaseBB;
1891
1892 if (++BBI != CurMBB->getParent()->end())
1893 NextBlock = BBI;
1894
1895 Case& FrontCase = *CR.Range.first;
1896 Case& BackCase = *(CR.Range.second-1);
1897 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1898
1899 // Size is the number of Cases represented by this range.
1900 unsigned Size = CR.Range.second - CR.Range.first;
1901
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001902 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1903 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001904 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001905 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001906
1907 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1908 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001909 uint64_t TSize = 0;
1910 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1911 I!=E; ++I)
1912 TSize += I->size();
1913
1914 uint64_t LSize = FrontCase.size();
1915 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001916 DOUT << "Selecting best pivot: \n"
1917 << "First: " << First << ", Last: " << Last <<"\n"
1918 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001919 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001920 J!=E; ++I, ++J) {
1921 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1922 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001923 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001924 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1925 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001926 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001927 // Should always split in some non-trivial place
1928 DOUT <<"=>Step\n"
1929 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1930 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1931 << "Metric: " << Metric << "\n";
1932 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001933 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001934 FMetric = Metric;
1935 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001936 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001937
1938 LSize += J->size();
1939 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001940 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001941 if (areJTsAllowed(TLI)) {
1942 // If our case is dense we *really* should handle it earlier!
1943 assert((FMetric > 0) && "Should handle dense range earlier!");
1944 } else {
1945 Pivot = CR.Range.first + Size/2;
1946 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001947
1948 CaseRange LHSR(CR.Range.first, Pivot);
1949 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001950 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001951 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1952
1953 // We know that we branch to the LHS if the Value being switched on is
1954 // less than the Pivot value, C. We use this to optimize our binary
1955 // tree a bit, by recognizing that if SV is greater than or equal to the
1956 // LHS's Case Value, and that Case Value is exactly one less than the
1957 // Pivot's Value, then we can branch directly to the LHS's Target,
1958 // rather than creating a leaf node for it.
1959 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001960 LHSR.first->High == CR.GE &&
1961 cast<ConstantInt>(C)->getSExtValue() ==
1962 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1963 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001964 } else {
1965 TrueBB = new MachineBasicBlock(LLVMBB);
1966 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1967 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1968 }
1969
1970 // Similar to the optimization above, if the Value being switched on is
1971 // known to be less than the Constant CR.LT, and the current Case Value
1972 // is CR.LT - 1, then we can branch directly to the target block for
1973 // the current Case Value, rather than emitting a RHS leaf node for it.
1974 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001975 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1976 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1977 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001978 } else {
1979 FalseBB = new MachineBasicBlock(LLVMBB);
1980 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1981 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1982 }
1983
1984 // Create a CaseBlock record representing a conditional branch to
1985 // the LHS node if the value being switched on SV is less than C.
1986 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001987 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1988 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001989
1990 if (CR.CaseBB == CurMBB)
1991 visitSwitchCase(CB);
1992 else
1993 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001994
1995 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001996}
1997
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001998/// handleBitTestsSwitchCase - if current case range has few destination and
1999/// range span less, than machine word bitwidth, encode case range into series
2000/// of masks and emit bit tests with these masks.
2001bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2002 CaseRecVector& WorkList,
2003 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002004 MachineBasicBlock* Default){
Dan Gohmanb55757e2007-05-18 17:52:13 +00002005 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002006
2007 Case& FrontCase = *CR.Range.first;
2008 Case& BackCase = *(CR.Range.second-1);
2009
2010 // Get the MachineFunction which holds the current MBB. This is used when
2011 // inserting any additional MBBs necessary to represent the switch.
2012 MachineFunction *CurMF = CurMBB->getParent();
2013
2014 unsigned numCmps = 0;
2015 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2016 I!=E; ++I) {
2017 // Single case counts one, case range - two.
2018 if (I->Low == I->High)
2019 numCmps +=1;
2020 else
2021 numCmps +=2;
2022 }
2023
2024 // Count unique destinations
2025 SmallSet<MachineBasicBlock*, 4> Dests;
2026 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2027 Dests.insert(I->BB);
2028 if (Dests.size() > 3)
2029 // Don't bother the code below, if there are too much unique destinations
2030 return false;
2031 }
2032 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2033 << "Total number of comparisons: " << numCmps << "\n";
2034
2035 // Compute span of values.
2036 Constant* minValue = FrontCase.Low;
2037 Constant* maxValue = BackCase.High;
2038 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2039 cast<ConstantInt>(minValue)->getSExtValue();
2040 DOUT << "Compare range: " << range << "\n"
2041 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2042 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2043
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002044 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002045 (!(Dests.size() == 1 && numCmps >= 3) &&
2046 !(Dests.size() == 2 && numCmps >= 5) &&
2047 !(Dests.size() >= 3 && numCmps >= 6)))
2048 return false;
2049
2050 DOUT << "Emitting bit tests\n";
2051 int64_t lowBound = 0;
2052
2053 // Optimize the case where all the case values fit in a
2054 // word without having to subtract minValue. In this case,
2055 // we can optimize away the subtraction.
2056 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002057 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002058 range = cast<ConstantInt>(maxValue)->getSExtValue();
2059 } else {
2060 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2061 }
2062
2063 CaseBitsVector CasesBits;
2064 unsigned i, count = 0;
2065
2066 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2067 MachineBasicBlock* Dest = I->BB;
2068 for (i = 0; i < count; ++i)
2069 if (Dest == CasesBits[i].BB)
2070 break;
2071
2072 if (i == count) {
2073 assert((count < 3) && "Too much destinations to test!");
2074 CasesBits.push_back(CaseBits(0, Dest, 0));
2075 count++;
2076 }
2077
2078 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2079 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2080
2081 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002082 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002083 CasesBits[i].Bits++;
2084 }
2085
2086 }
2087 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2088
2089 SelectionDAGISel::BitTestInfo BTC;
2090
2091 // Figure out which block is immediately after the current one.
2092 MachineFunction::iterator BBI = CR.CaseBB;
2093 ++BBI;
2094
2095 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2096
2097 DOUT << "Cases:\n";
2098 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2099 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2100 << ", BB: " << CasesBits[i].BB << "\n";
2101
2102 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2103 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2104 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2105 CaseBB,
2106 CasesBits[i].BB));
2107 }
2108
2109 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002110 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002111 CR.CaseBB, Default, BTC);
2112
2113 if (CR.CaseBB == CurMBB)
2114 visitBitTestHeader(BTB);
2115
2116 BitTestCases.push_back(BTB);
2117
2118 return true;
2119}
2120
2121
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002122/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002123unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2124 const SwitchInst& SI) {
2125 unsigned numCmps = 0;
2126
2127 // Start with "simple" cases
2128 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2129 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2130 Cases.push_back(Case(SI.getSuccessorValue(i),
2131 SI.getSuccessorValue(i),
2132 SMBB));
2133 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002134 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002135
2136 // Merge case into clusters
2137 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002138 // Must recompute end() each iteration because it may be
2139 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002140 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002141 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2142 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2143 MachineBasicBlock* nextBB = J->BB;
2144 MachineBasicBlock* currentBB = I->BB;
2145
2146 // If the two neighboring cases go to the same destination, merge them
2147 // into a single case.
2148 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2149 I->High = J->High;
2150 J = Cases.erase(J);
2151 } else {
2152 I = J++;
2153 }
2154 }
2155
2156 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2157 if (I->Low != I->High)
2158 // A range counts double, since it requires two compares.
2159 ++numCmps;
2160 }
2161
2162 return numCmps;
2163}
2164
2165void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002166 // Figure out which block is immediately after the current one.
2167 MachineBasicBlock *NextBlock = 0;
2168 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002169
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002170 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002171
Nate Begemanf15485a2006-03-27 01:32:24 +00002172 // If there is only the default destination, branch to it if it is not the
2173 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002174 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002175 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002176
Nate Begemanf15485a2006-03-27 01:32:24 +00002177 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002178 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002179 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002180 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002181
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002182 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002183 return;
2184 }
2185
2186 // If there are any non-default case statements, create a vector of Cases
2187 // representing each one, and sort the vector so that we can efficiently
2188 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002189 CaseVector Cases;
2190 unsigned numCmps = Clusterify(Cases, SI);
2191 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2192 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002193
Nate Begemanf15485a2006-03-27 01:32:24 +00002194 // Get the Value to be switched on and default basic blocks, which will be
2195 // inserted into CaseBlock records, representing basic blocks in the binary
2196 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002197 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002198
Nate Begemanf15485a2006-03-27 01:32:24 +00002199 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002200 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002201 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2202
2203 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002204 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002205 CaseRec CR = WorkList.back();
2206 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002207
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002208 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2209 continue;
2210
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002211 // If the range has few cases (two or less) emit a series of specific
2212 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002213 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2214 continue;
2215
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002216 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002217 // target supports indirect branches, then emit a jump table rather than
2218 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002219 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2220 continue;
2221
2222 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2223 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2224 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002225 }
2226}
2227
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002228
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002229void SelectionDAGLowering::visitSub(User &I) {
2230 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002231 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002232 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002233 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2234 const VectorType *DestTy = cast<VectorType>(I.getType());
2235 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002236 if (ElTy->isFloatingPoint()) {
2237 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002238 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002239 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2240 if (CV == CNZ) {
2241 SDOperand Op2 = getValue(I.getOperand(1));
2242 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2243 return;
2244 }
Dan Gohman7f321562007-06-25 16:23:39 +00002245 }
2246 }
2247 }
2248 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002249 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002250 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002251 SDOperand Op2 = getValue(I.getOperand(1));
2252 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2253 return;
2254 }
Dan Gohman7f321562007-06-25 16:23:39 +00002255 }
2256
2257 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002258}
2259
Dan Gohman7f321562007-06-25 16:23:39 +00002260void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002261 SDOperand Op1 = getValue(I.getOperand(0));
2262 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002263
2264 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002265}
2266
Nate Begemane21ea612005-11-18 07:42:56 +00002267void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2268 SDOperand Op1 = getValue(I.getOperand(0));
2269 SDOperand Op2 = getValue(I.getOperand(1));
2270
Dan Gohman7f321562007-06-25 16:23:39 +00002271 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2272 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002273 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2274 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2275 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002276
Chris Lattner1c08c712005-01-07 07:47:53 +00002277 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2278}
2279
Reid Spencer45fb3f32006-11-20 01:22:35 +00002280void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002281 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2282 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2283 predicate = IC->getPredicate();
2284 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2285 predicate = ICmpInst::Predicate(IC->getPredicate());
2286 SDOperand Op1 = getValue(I.getOperand(0));
2287 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002288 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002289 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002290 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2291 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2292 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2293 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2294 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2295 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2296 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2297 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2298 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2299 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2300 default:
2301 assert(!"Invalid ICmp predicate value");
2302 Opcode = ISD::SETEQ;
2303 break;
2304 }
2305 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2306}
2307
2308void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002309 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2310 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2311 predicate = FC->getPredicate();
2312 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2313 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002314 SDOperand Op1 = getValue(I.getOperand(0));
2315 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002316 ISD::CondCode Condition, FOC, FPC;
2317 switch (predicate) {
2318 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2319 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2320 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2321 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2322 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2323 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2324 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002325 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2326 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002327 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2328 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2329 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2330 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2331 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2332 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2333 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2334 default:
2335 assert(!"Invalid FCmp predicate value");
2336 FOC = FPC = ISD::SETFALSE;
2337 break;
2338 }
2339 if (FiniteOnlyFPMath())
2340 Condition = FOC;
2341 else
2342 Condition = FPC;
2343 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002344}
2345
Nate Begemanb43e9c12008-05-12 19:40:03 +00002346void SelectionDAGLowering::visitVICmp(User &I) {
2347 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2348 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2349 predicate = IC->getPredicate();
2350 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2351 predicate = ICmpInst::Predicate(IC->getPredicate());
2352 SDOperand Op1 = getValue(I.getOperand(0));
2353 SDOperand Op2 = getValue(I.getOperand(1));
2354 ISD::CondCode Opcode;
2355 switch (predicate) {
2356 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2357 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2358 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2359 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2360 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2361 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2362 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2363 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2364 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2365 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2366 default:
2367 assert(!"Invalid ICmp predicate value");
2368 Opcode = ISD::SETEQ;
2369 break;
2370 }
2371 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2372}
2373
2374void SelectionDAGLowering::visitVFCmp(User &I) {
2375 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2376 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2377 predicate = FC->getPredicate();
2378 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2379 predicate = FCmpInst::Predicate(FC->getPredicate());
2380 SDOperand Op1 = getValue(I.getOperand(0));
2381 SDOperand Op2 = getValue(I.getOperand(1));
2382 ISD::CondCode Condition, FOC, FPC;
2383 switch (predicate) {
2384 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2385 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2386 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2387 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2388 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2389 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2390 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2391 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2392 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2393 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2394 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2395 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2396 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2397 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2398 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2399 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2400 default:
2401 assert(!"Invalid VFCmp predicate value");
2402 FOC = FPC = ISD::SETFALSE;
2403 break;
2404 }
2405 if (FiniteOnlyFPMath())
2406 Condition = FOC;
2407 else
2408 Condition = FPC;
2409
2410 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2411
2412 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2413}
2414
Chris Lattner1c08c712005-01-07 07:47:53 +00002415void SelectionDAGLowering::visitSelect(User &I) {
2416 SDOperand Cond = getValue(I.getOperand(0));
2417 SDOperand TrueVal = getValue(I.getOperand(1));
2418 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002419 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2420 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002421}
2422
Reid Spencer3da59db2006-11-27 01:05:10 +00002423
2424void SelectionDAGLowering::visitTrunc(User &I) {
2425 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2426 SDOperand N = getValue(I.getOperand(0));
2427 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2428 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2429}
2430
2431void SelectionDAGLowering::visitZExt(User &I) {
2432 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2433 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2434 SDOperand N = getValue(I.getOperand(0));
2435 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2436 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2437}
2438
2439void SelectionDAGLowering::visitSExt(User &I) {
2440 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2441 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2442 SDOperand N = getValue(I.getOperand(0));
2443 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2444 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2445}
2446
2447void SelectionDAGLowering::visitFPTrunc(User &I) {
2448 // FPTrunc is never a no-op cast, no need to check
2449 SDOperand N = getValue(I.getOperand(0));
2450 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002451 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002452}
2453
2454void SelectionDAGLowering::visitFPExt(User &I){
2455 // FPTrunc is never a no-op cast, no need to check
2456 SDOperand N = getValue(I.getOperand(0));
2457 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2458 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2459}
2460
2461void SelectionDAGLowering::visitFPToUI(User &I) {
2462 // FPToUI is never a no-op cast, no need to check
2463 SDOperand N = getValue(I.getOperand(0));
2464 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2465 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2466}
2467
2468void SelectionDAGLowering::visitFPToSI(User &I) {
2469 // FPToSI is never a no-op cast, no need to check
2470 SDOperand N = getValue(I.getOperand(0));
2471 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2472 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2473}
2474
2475void SelectionDAGLowering::visitUIToFP(User &I) {
2476 // UIToFP is never a no-op cast, no need to check
2477 SDOperand N = getValue(I.getOperand(0));
2478 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2479 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2480}
2481
2482void SelectionDAGLowering::visitSIToFP(User &I){
2483 // UIToFP is never a no-op cast, no need to check
2484 SDOperand N = getValue(I.getOperand(0));
2485 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2486 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2487}
2488
2489void SelectionDAGLowering::visitPtrToInt(User &I) {
2490 // What to do depends on the size of the integer and the size of the pointer.
2491 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002492 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002493 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002494 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002495 SDOperand Result;
2496 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2497 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2498 else
2499 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2500 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2501 setValue(&I, Result);
2502}
Chris Lattner1c08c712005-01-07 07:47:53 +00002503
Reid Spencer3da59db2006-11-27 01:05:10 +00002504void SelectionDAGLowering::visitIntToPtr(User &I) {
2505 // What to do depends on the size of the integer and the size of the pointer.
2506 // We can either truncate, zero extend, or no-op, accordingly.
2507 SDOperand N = getValue(I.getOperand(0));
2508 MVT::ValueType SrcVT = N.getValueType();
2509 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2510 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2511 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2512 else
2513 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2514 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2515}
2516
2517void SelectionDAGLowering::visitBitCast(User &I) {
2518 SDOperand N = getValue(I.getOperand(0));
2519 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002520
2521 // BitCast assures us that source and destination are the same size so this
2522 // is either a BIT_CONVERT or a no-op.
2523 if (DestVT != N.getValueType())
2524 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2525 else
2526 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002527}
2528
Chris Lattner2bbd8102006-03-29 00:11:43 +00002529void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002530 SDOperand InVec = getValue(I.getOperand(0));
2531 SDOperand InVal = getValue(I.getOperand(1));
2532 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2533 getValue(I.getOperand(2)));
2534
Dan Gohman7f321562007-06-25 16:23:39 +00002535 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2536 TLI.getValueType(I.getType()),
2537 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002538}
2539
Chris Lattner2bbd8102006-03-29 00:11:43 +00002540void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002541 SDOperand InVec = getValue(I.getOperand(0));
2542 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2543 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002544 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002545 TLI.getValueType(I.getType()), InVec, InIdx));
2546}
Chris Lattnerc7029802006-03-18 01:44:44 +00002547
Chris Lattner3e104b12006-04-08 04:15:24 +00002548void SelectionDAGLowering::visitShuffleVector(User &I) {
2549 SDOperand V1 = getValue(I.getOperand(0));
2550 SDOperand V2 = getValue(I.getOperand(1));
2551 SDOperand Mask = getValue(I.getOperand(2));
2552
Dan Gohman7f321562007-06-25 16:23:39 +00002553 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2554 TLI.getValueType(I.getType()),
2555 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002556}
2557
2558
Chris Lattner1c08c712005-01-07 07:47:53 +00002559void SelectionDAGLowering::visitGetElementPtr(User &I) {
2560 SDOperand N = getValue(I.getOperand(0));
2561 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002562
2563 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2564 OI != E; ++OI) {
2565 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002566 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002567 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002568 if (Field) {
2569 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002570 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002571 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002572 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002573 }
2574 Ty = StTy->getElementType(Field);
2575 } else {
2576 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002577
Chris Lattner7c0104b2005-11-09 04:45:33 +00002578 // If this is a constant subscript, handle it quickly.
2579 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002580 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002581 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002582 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002583 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2584 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002585 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002586 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002587
2588 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002589 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002590 SDOperand IdxN = getValue(Idx);
2591
2592 // If the index is smaller or larger than intptr_t, truncate or extend
2593 // it.
2594 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002595 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002596 } else if (IdxN.getValueType() > N.getValueType())
2597 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2598
2599 // If this is a multiply by a power of two, turn it into a shl
2600 // immediately. This is a very common case.
2601 if (isPowerOf2_64(ElementSize)) {
2602 unsigned Amt = Log2_64(ElementSize);
2603 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002604 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002605 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2606 continue;
2607 }
2608
Chris Lattner0bd48932008-01-17 07:00:52 +00002609 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002610 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2611 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002612 }
2613 }
2614 setValue(&I, N);
2615}
2616
2617void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2618 // If this is a fixed sized alloca in the entry block of the function,
2619 // allocate it statically on the stack.
2620 if (FuncInfo.StaticAllocaMap.count(&I))
2621 return; // getValue will auto-populate this.
2622
2623 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002624 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002625 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002626 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002627 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002628
2629 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002630 MVT::ValueType IntPtr = TLI.getPointerTy();
2631 if (IntPtr < AllocSize.getValueType())
2632 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2633 else if (IntPtr > AllocSize.getValueType())
2634 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002635
Chris Lattner68cd65e2005-01-22 23:04:37 +00002636 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002637 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002638
Evan Cheng45157792007-08-16 23:46:29 +00002639 // Handle alignment. If the requested alignment is less than or equal to
2640 // the stack alignment, ignore it. If the size is greater than or equal to
2641 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002642 unsigned StackAlign =
2643 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002644 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002645 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002646
2647 // Round the size of the allocation up to the stack alignment size
2648 // by add SA-1 to the size.
2649 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002650 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002651 // Mask out the low bits for alignment purposes.
2652 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002653 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002654
Chris Lattner0bd48932008-01-17 07:00:52 +00002655 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002656 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2657 MVT::Other);
2658 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002659 setValue(&I, DSA);
2660 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002661
2662 // Inform the Frame Information that we have just allocated a variable-sized
2663 // object.
2664 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2665}
2666
Chris Lattner1c08c712005-01-07 07:47:53 +00002667void SelectionDAGLowering::visitLoad(LoadInst &I) {
2668 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002669
Chris Lattnerd3948112005-01-17 22:19:26 +00002670 SDOperand Root;
2671 if (I.isVolatile())
2672 Root = getRoot();
2673 else {
2674 // Do not serialize non-volatile loads against each other.
2675 Root = DAG.getRoot();
2676 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002677
Evan Cheng466685d2006-10-09 20:57:25 +00002678 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002679 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002680}
2681
2682SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002683 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002684 bool isVolatile,
2685 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002686 SDOperand L =
2687 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2688 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002689
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002690 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002691 DAG.setRoot(L.getValue(1));
2692 else
2693 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002694
2695 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002696}
2697
2698
2699void SelectionDAGLowering::visitStore(StoreInst &I) {
2700 Value *SrcV = I.getOperand(0);
2701 SDOperand Src = getValue(SrcV);
2702 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002703 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002704 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002705}
2706
Chris Lattner0eade312006-03-24 02:22:33 +00002707/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2708/// node.
2709void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2710 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002711 bool HasChain = !I.doesNotAccessMemory();
2712 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2713
Chris Lattner0eade312006-03-24 02:22:33 +00002714 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002715 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002716 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2717 if (OnlyLoad) {
2718 // We don't need to serialize loads against other loads.
2719 Ops.push_back(DAG.getRoot());
2720 } else {
2721 Ops.push_back(getRoot());
2722 }
2723 }
Chris Lattner0eade312006-03-24 02:22:33 +00002724
2725 // Add the intrinsic ID as an integer operand.
2726 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2727
2728 // Add all operands of the call to the operand list.
2729 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2730 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002731 assert(TLI.isTypeLegal(Op.getValueType()) &&
2732 "Intrinsic uses a non-legal type?");
2733 Ops.push_back(Op);
2734 }
2735
2736 std::vector<MVT::ValueType> VTs;
2737 if (I.getType() != Type::VoidTy) {
2738 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00002739 if (MVT::isVector(VT)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002740 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002741 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2742
2743 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2744 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2745 }
2746
2747 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2748 VTs.push_back(VT);
2749 }
2750 if (HasChain)
2751 VTs.push_back(MVT::Other);
2752
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002753 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2754
Chris Lattner0eade312006-03-24 02:22:33 +00002755 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002756 SDOperand Result;
2757 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002758 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2759 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002760 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002761 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2762 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002763 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002764 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2765 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002766
Chris Lattnere58a7802006-04-02 03:41:14 +00002767 if (HasChain) {
2768 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2769 if (OnlyLoad)
2770 PendingLoads.push_back(Chain);
2771 else
2772 DAG.setRoot(Chain);
2773 }
Chris Lattner0eade312006-03-24 02:22:33 +00002774 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002775 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohman7f321562007-06-25 16:23:39 +00002776 MVT::ValueType VT = TLI.getValueType(PTy);
2777 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002778 }
2779 setValue(&I, Result);
2780 }
2781}
2782
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002783/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002784static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00002785 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002786 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00002787 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002788 "TypeInfo must be a global variable or NULL");
2789 return GV;
2790}
2791
Duncan Sandsf4070822007-06-15 19:04:19 +00002792/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002793/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002794static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2795 MachineBasicBlock *MBB) {
2796 // Inform the MachineModuleInfo of the personality for this landing pad.
2797 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2798 assert(CE->getOpcode() == Instruction::BitCast &&
2799 isa<Function>(CE->getOperand(0)) &&
2800 "Personality should be a function");
2801 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2802
2803 // Gather all the type infos for this landing pad and pass them along to
2804 // MachineModuleInfo.
2805 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002806 unsigned N = I.getNumOperands();
2807
2808 for (unsigned i = N - 1; i > 2; --i) {
2809 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2810 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002811 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002812 assert (FirstCatch <= N && "Invalid filter length");
2813
2814 if (FirstCatch < N) {
2815 TyInfo.reserve(N - FirstCatch);
2816 for (unsigned j = FirstCatch; j < N; ++j)
2817 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2818 MMI->addCatchTypeInfo(MBB, TyInfo);
2819 TyInfo.clear();
2820 }
2821
Duncan Sands6590b042007-08-27 15:47:50 +00002822 if (!FilterLength) {
2823 // Cleanup.
2824 MMI->addCleanup(MBB);
2825 } else {
2826 // Filter.
2827 TyInfo.reserve(FilterLength - 1);
2828 for (unsigned j = i + 1; j < FirstCatch; ++j)
2829 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2830 MMI->addFilterTypeInfo(MBB, TyInfo);
2831 TyInfo.clear();
2832 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002833
2834 N = i;
2835 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002836 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002837
2838 if (N > 3) {
2839 TyInfo.reserve(N - 3);
2840 for (unsigned j = 3; j < N; ++j)
2841 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002842 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002843 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002844}
2845
Mon P Wang63307c32008-05-05 19:05:59 +00002846
2847/// Inlined utility function to implement binary input atomic intrinsics for
2848// visitIntrinsicCall: I is a call instruction
2849// Op is the associated NodeType for I
2850const char *
2851SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2852 SDOperand Root = getRoot();
2853 SDOperand O2 = getValue(I.getOperand(2));
2854 SDOperand L = DAG.getAtomic(Op, Root,
2855 getValue(I.getOperand(1)),
2856 O2, O2.getValueType());
2857 setValue(&I, L);
2858 DAG.setRoot(L.getValue(1));
2859 return 0;
2860}
2861
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002862/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2863/// we want to emit this as a call to a named external function, return the name
2864/// otherwise lower it and return null.
2865const char *
2866SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2867 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002868 default:
2869 // By default, turn this into a target intrinsic node.
2870 visitTargetIntrinsic(I, Intrinsic);
2871 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002872 case Intrinsic::vastart: visitVAStart(I); return 0;
2873 case Intrinsic::vaend: visitVAEnd(I); return 0;
2874 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002875 case Intrinsic::returnaddress:
2876 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2877 getValue(I.getOperand(1))));
2878 return 0;
2879 case Intrinsic::frameaddress:
2880 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2881 getValue(I.getOperand(1))));
2882 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002883 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002884 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002885 break;
2886 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002887 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002888 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002889 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002890 case Intrinsic::memcpy_i64: {
2891 SDOperand Op1 = getValue(I.getOperand(1));
2892 SDOperand Op2 = getValue(I.getOperand(2));
2893 SDOperand Op3 = getValue(I.getOperand(3));
2894 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2895 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2896 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002897 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002898 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002899 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002900 case Intrinsic::memset_i64: {
2901 SDOperand Op1 = getValue(I.getOperand(1));
2902 SDOperand Op2 = getValue(I.getOperand(2));
2903 SDOperand Op3 = getValue(I.getOperand(3));
2904 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2905 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2906 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002907 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002908 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002909 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002910 case Intrinsic::memmove_i64: {
2911 SDOperand Op1 = getValue(I.getOperand(1));
2912 SDOperand Op2 = getValue(I.getOperand(2));
2913 SDOperand Op3 = getValue(I.getOperand(3));
2914 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2915
2916 // If the source and destination are known to not be aliases, we can
2917 // lower memmove as memcpy.
2918 uint64_t Size = -1ULL;
2919 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2920 Size = C->getValue();
2921 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2922 AliasAnalysis::NoAlias) {
2923 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2924 I.getOperand(1), 0, I.getOperand(2), 0));
2925 return 0;
2926 }
2927
2928 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2929 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002930 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002931 }
Chris Lattner86cb6432005-12-13 17:40:33 +00002932 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002933 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002934 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002935 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002936 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002937
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002938 Ops[0] = getRoot();
2939 Ops[1] = getValue(SPI.getLineValue());
2940 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002941
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002942 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002943 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002944 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2945
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002946 Ops[3] = DAG.getString(CompileUnit->getFileName());
2947 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002948
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002949 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002950 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002951
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002952 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002953 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002954 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002955 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002956 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002957 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2958 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002959 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00002960 DAG.getConstant(LabelID, MVT::i32),
2961 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002962 }
2963
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002964 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002965 }
2966 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002967 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002968 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002969 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2970 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00002971 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2972 DAG.getConstant(LabelID, MVT::i32),
2973 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002974 }
2975
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002976 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002977 }
2978 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002979 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002980 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002981 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002982 Value *SP = FSI.getSubprogram();
2983 if (SP && MMI->Verify(SP)) {
2984 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2985 // what (most?) gdb expects.
2986 DebugInfoDesc *DD = MMI->getDescFor(SP);
2987 assert(DD && "Not a debug information descriptor");
2988 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2989 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2990 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2991 CompileUnit->getFileName());
2992 // Record the source line but does create a label. It will be emitted
2993 // at asm emission time.
2994 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00002995 }
2996
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002997 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002998 }
2999 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003000 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003001 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003002 Value *Variable = DI.getVariable();
3003 if (MMI && Variable && MMI->Verify(Variable))
3004 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3005 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003006 return 0;
3007 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003008
Jim Laskeyb180aa12007-02-21 22:53:45 +00003009 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003010 if (!CurMBB->isLandingPad()) {
3011 // FIXME: Mark exception register as live in. Hack for PR1508.
3012 unsigned Reg = TLI.getExceptionAddressRegister();
3013 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003014 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003015 // Insert the EXCEPTIONADDR instruction.
3016 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3017 SDOperand Ops[1];
3018 Ops[0] = DAG.getRoot();
3019 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3020 setValue(&I, Op);
3021 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003022 return 0;
3023 }
3024
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003025 case Intrinsic::eh_selector_i32:
3026 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003027 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003028 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3029 MVT::i32 : MVT::i64);
3030
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003031 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003032 if (CurMBB->isLandingPad())
3033 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003034 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003035#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003036 FuncInfo.CatchInfoLost.insert(&I);
3037#endif
Duncan Sands90291952007-07-06 09:18:59 +00003038 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3039 unsigned Reg = TLI.getExceptionSelectorRegister();
3040 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003041 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003042
3043 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003044 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00003045 SDOperand Ops[2];
3046 Ops[0] = getValue(I.getOperand(1));
3047 Ops[1] = getRoot();
3048 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3049 setValue(&I, Op);
3050 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003051 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003052 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003053 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003054
3055 return 0;
3056 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003057
3058 case Intrinsic::eh_typeid_for_i32:
3059 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003060 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003061 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3062 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003063
Jim Laskey735b6f82007-02-22 15:38:06 +00003064 if (MMI) {
3065 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003066 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003067
Jim Laskey735b6f82007-02-22 15:38:06 +00003068 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003069 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003070 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003071 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003072 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003073 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003074
3075 return 0;
3076 }
3077
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003078 case Intrinsic::eh_return: {
3079 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3080
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003081 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003082 MMI->setCallsEHReturn(true);
3083 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3084 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003085 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003086 getValue(I.getOperand(1)),
3087 getValue(I.getOperand(2))));
3088 } else {
3089 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3090 }
3091
3092 return 0;
3093 }
3094
3095 case Intrinsic::eh_unwind_init: {
3096 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3097 MMI->setCallsUnwindInit(true);
3098 }
3099
3100 return 0;
3101 }
3102
3103 case Intrinsic::eh_dwarf_cfa: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003104 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3105 SDOperand CfaArg;
3106 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3107 CfaArg = DAG.getNode(ISD::TRUNCATE,
3108 TLI.getPointerTy(), getValue(I.getOperand(1)));
3109 else
3110 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3111 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003112
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003113 SDOperand Offset = DAG.getNode(ISD::ADD,
3114 TLI.getPointerTy(),
3115 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3116 TLI.getPointerTy()),
3117 CfaArg);
3118 setValue(&I, DAG.getNode(ISD::ADD,
3119 TLI.getPointerTy(),
3120 DAG.getNode(ISD::FRAMEADDR,
3121 TLI.getPointerTy(),
3122 DAG.getConstant(0,
3123 TLI.getPointerTy())),
3124 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003125 return 0;
3126 }
3127
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003128 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003129 setValue(&I, DAG.getNode(ISD::FSQRT,
3130 getValue(I.getOperand(1)).getValueType(),
3131 getValue(I.getOperand(1))));
3132 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003133 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003134 setValue(&I, DAG.getNode(ISD::FPOWI,
3135 getValue(I.getOperand(1)).getValueType(),
3136 getValue(I.getOperand(1)),
3137 getValue(I.getOperand(2))));
3138 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003139 case Intrinsic::sin:
3140 setValue(&I, DAG.getNode(ISD::FSIN,
3141 getValue(I.getOperand(1)).getValueType(),
3142 getValue(I.getOperand(1))));
3143 return 0;
3144 case Intrinsic::cos:
3145 setValue(&I, DAG.getNode(ISD::FCOS,
3146 getValue(I.getOperand(1)).getValueType(),
3147 getValue(I.getOperand(1))));
3148 return 0;
3149 case Intrinsic::pow:
3150 setValue(&I, DAG.getNode(ISD::FPOW,
3151 getValue(I.getOperand(1)).getValueType(),
3152 getValue(I.getOperand(1)),
3153 getValue(I.getOperand(2))));
3154 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003155 case Intrinsic::pcmarker: {
3156 SDOperand Tmp = getValue(I.getOperand(1));
3157 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3158 return 0;
3159 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003160 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003161 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003162 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3163 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3164 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003165 setValue(&I, Tmp);
3166 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003167 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003168 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003169 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003170 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003171 assert(0 && "part_select intrinsic not implemented");
3172 abort();
3173 }
3174 case Intrinsic::part_set: {
3175 // Currently not implemented: just abort
3176 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003177 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003178 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003179 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003180 setValue(&I, DAG.getNode(ISD::BSWAP,
3181 getValue(I.getOperand(1)).getValueType(),
3182 getValue(I.getOperand(1))));
3183 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003184 case Intrinsic::cttz: {
3185 SDOperand Arg = getValue(I.getOperand(1));
3186 MVT::ValueType Ty = Arg.getValueType();
3187 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003188 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003189 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003190 }
3191 case Intrinsic::ctlz: {
3192 SDOperand Arg = getValue(I.getOperand(1));
3193 MVT::ValueType Ty = Arg.getValueType();
3194 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003195 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003196 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003197 }
3198 case Intrinsic::ctpop: {
3199 SDOperand Arg = getValue(I.getOperand(1));
3200 MVT::ValueType Ty = Arg.getValueType();
3201 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003202 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003203 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003204 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003205 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003206 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003207 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3208 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003209 setValue(&I, Tmp);
3210 DAG.setRoot(Tmp.getValue(1));
3211 return 0;
3212 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003213 case Intrinsic::stackrestore: {
3214 SDOperand Tmp = getValue(I.getOperand(1));
3215 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003216 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003217 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003218 case Intrinsic::var_annotation:
3219 // Discard annotate attributes
3220 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003221
Duncan Sands36397f52007-07-27 12:58:54 +00003222 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003223 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003224
3225 SDOperand Ops[6];
3226 Ops[0] = getRoot();
3227 Ops[1] = getValue(I.getOperand(1));
3228 Ops[2] = getValue(I.getOperand(2));
3229 Ops[3] = getValue(I.getOperand(3));
3230 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3231 Ops[5] = DAG.getSrcValue(F);
3232
Duncan Sandsf7331b32007-09-11 14:10:23 +00003233 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3234 DAG.getNodeValueTypes(TLI.getPointerTy(),
3235 MVT::Other), 2,
3236 Ops, 6);
3237
3238 setValue(&I, Tmp);
3239 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003240 return 0;
3241 }
Gordon Henriksence224772008-01-07 01:30:38 +00003242
3243 case Intrinsic::gcroot:
3244 if (GCI) {
3245 Value *Alloca = I.getOperand(1);
3246 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3247
3248 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3249 GCI->addStackRoot(FI->getIndex(), TypeMap);
3250 }
3251 return 0;
3252
3253 case Intrinsic::gcread:
3254 case Intrinsic::gcwrite:
3255 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3256 return 0;
3257
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003258 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003259 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003260 return 0;
3261 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003262
3263 case Intrinsic::trap: {
3264 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3265 return 0;
3266 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003267 case Intrinsic::prefetch: {
3268 SDOperand Ops[4];
3269 Ops[0] = getRoot();
3270 Ops[1] = getValue(I.getOperand(1));
3271 Ops[2] = getValue(I.getOperand(2));
3272 Ops[3] = getValue(I.getOperand(3));
3273 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3274 return 0;
3275 }
3276
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003277 case Intrinsic::memory_barrier: {
3278 SDOperand Ops[6];
3279 Ops[0] = getRoot();
3280 for (int x = 1; x < 6; ++x)
3281 Ops[x] = getValue(I.getOperand(x));
3282
3283 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3284 return 0;
3285 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003286 case Intrinsic::atomic_lcs: {
3287 SDOperand Root = getRoot();
3288 SDOperand O3 = getValue(I.getOperand(3));
3289 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3290 getValue(I.getOperand(1)),
3291 getValue(I.getOperand(2)),
3292 O3, O3.getValueType());
3293 setValue(&I, L);
3294 DAG.setRoot(L.getValue(1));
3295 return 0;
3296 }
Mon P Wang63307c32008-05-05 19:05:59 +00003297 case Intrinsic::atomic_las:
3298 return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3299 case Intrinsic::atomic_lss:
3300 return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3301 case Intrinsic::atomic_load_and:
3302 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3303 case Intrinsic::atomic_load_or:
3304 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3305 case Intrinsic::atomic_load_xor:
3306 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3307 case Intrinsic::atomic_load_min:
3308 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3309 case Intrinsic::atomic_load_max:
3310 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3311 case Intrinsic::atomic_load_umin:
3312 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3313 case Intrinsic::atomic_load_umax:
3314 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3315 case Intrinsic::atomic_swap:
3316 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003317 }
3318}
3319
3320
Duncan Sands6f74b482007-12-19 09:48:52 +00003321void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003322 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003323 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003324 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003325 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003326 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3327 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003328
Jim Laskey735b6f82007-02-22 15:38:06 +00003329 TargetLowering::ArgListTy Args;
3330 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003331 Args.reserve(CS.arg_size());
3332 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3333 i != e; ++i) {
3334 SDOperand ArgNode = getValue(*i);
3335 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003336
Duncan Sands6f74b482007-12-19 09:48:52 +00003337 unsigned attrInd = i - CS.arg_begin() + 1;
3338 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3339 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3340 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3341 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3342 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3343 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003344 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003345 Args.push_back(Entry);
3346 }
3347
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003348 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003349 // Insert a label before the invoke call to mark the try range. This can be
3350 // used to detect deletion of the invoke via the MachineModuleInfo.
3351 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003352 // Both PendingLoads and PendingExports must be flushed here;
3353 // this call might not return.
3354 (void)getRoot();
3355 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003356 DAG.getConstant(BeginLabel, MVT::i32),
3357 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003358 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003359
Jim Laskey735b6f82007-02-22 15:38:06 +00003360 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003361 TLI.LowerCallTo(getRoot(), CS.getType(),
3362 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003363 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003364 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003365 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003366 if (CS.getType() != Type::VoidTy)
3367 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003368 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003369
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003370 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003371 // Insert a label at the end of the invoke call to mark the try range. This
3372 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3373 EndLabel = MMI->NextLabelID();
3374 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003375 DAG.getConstant(EndLabel, MVT::i32),
3376 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003377
Duncan Sands6f74b482007-12-19 09:48:52 +00003378 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003379 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3380 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003381}
3382
3383
Chris Lattner1c08c712005-01-07 07:47:53 +00003384void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003385 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003386 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003387 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003388 if (unsigned IID = F->getIntrinsicID()) {
3389 RenameFn = visitIntrinsicCall(I, IID);
3390 if (!RenameFn)
3391 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003392 }
3393 }
3394
3395 // Check for well-known libc/libm calls. If the function is internal, it
3396 // can't be a library call.
3397 unsigned NameLen = F->getNameLen();
3398 if (!F->hasInternalLinkage() && NameLen) {
3399 const char *NameStr = F->getNameStart();
3400 if (NameStr[0] == 'c' &&
3401 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3402 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3403 if (I.getNumOperands() == 3 && // Basic sanity checks.
3404 I.getOperand(1)->getType()->isFloatingPoint() &&
3405 I.getType() == I.getOperand(1)->getType() &&
3406 I.getType() == I.getOperand(2)->getType()) {
3407 SDOperand LHS = getValue(I.getOperand(1));
3408 SDOperand RHS = getValue(I.getOperand(2));
3409 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3410 LHS, RHS));
3411 return;
3412 }
3413 } else if (NameStr[0] == 'f' &&
3414 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003415 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3416 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003417 if (I.getNumOperands() == 2 && // Basic sanity checks.
3418 I.getOperand(1)->getType()->isFloatingPoint() &&
3419 I.getType() == I.getOperand(1)->getType()) {
3420 SDOperand Tmp = getValue(I.getOperand(1));
3421 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3422 return;
3423 }
3424 } else if (NameStr[0] == 's' &&
3425 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003426 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3427 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003428 if (I.getNumOperands() == 2 && // Basic sanity checks.
3429 I.getOperand(1)->getType()->isFloatingPoint() &&
3430 I.getType() == I.getOperand(1)->getType()) {
3431 SDOperand Tmp = getValue(I.getOperand(1));
3432 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3433 return;
3434 }
3435 } else if (NameStr[0] == 'c' &&
3436 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003437 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3438 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003439 if (I.getNumOperands() == 2 && // Basic sanity checks.
3440 I.getOperand(1)->getType()->isFloatingPoint() &&
3441 I.getType() == I.getOperand(1)->getType()) {
3442 SDOperand Tmp = getValue(I.getOperand(1));
3443 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3444 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003445 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003446 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003447 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003448 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003449 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003450 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003451 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003452
Chris Lattner64e14b12005-01-08 22:48:57 +00003453 SDOperand Callee;
3454 if (!RenameFn)
3455 Callee = getValue(I.getOperand(0));
3456 else
3457 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003458
Duncan Sands6f74b482007-12-19 09:48:52 +00003459 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003460}
3461
Jim Laskey735b6f82007-02-22 15:38:06 +00003462
Dan Gohmanef5d1942008-03-11 21:11:25 +00003463void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003464 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003465 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3466 setValue(&I, Undef);
Chris Lattner6833b062008-04-28 07:16:35 +00003467 return;
Dan Gohman3dc34f62008-04-23 20:21:29 +00003468 }
Chris Lattner6833b062008-04-28 07:16:35 +00003469
3470 // To add support for individual return values with aggregate types,
3471 // we'd need a way to take a getresult index and determine which
3472 // values of the Call SDNode are associated with it.
3473 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3474 "Individual return values must not be aggregates!");
3475
3476 SDOperand Call = getValue(I.getOperand(0));
3477 setValue(&I, SDOperand(Call.Val, I.getIndex()));
Dan Gohmanef5d1942008-03-11 21:11:25 +00003478}
3479
3480
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003481/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3482/// this value and returns the result as a ValueVT value. This uses
3483/// Chain/Flag as the input and updates them for the output Chain/Flag.
3484/// If the Flag pointer is NULL, no flag is used.
3485SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner6833b062008-04-28 07:16:35 +00003486 SDOperand &Chain,
3487 SDOperand *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003488 // Assemble the legal parts into the final values.
3489 SmallVector<SDOperand, 4> Values(ValueVTs.size());
Chris Lattner6833b062008-04-28 07:16:35 +00003490 SmallVector<SDOperand, 8> Parts;
3491 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003492 // Copy the legal parts from the registers.
3493 MVT::ValueType ValueVT = ValueVTs[Value];
3494 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3495 MVT::ValueType RegisterVT = RegVTs[Value];
3496
Chris Lattner6833b062008-04-28 07:16:35 +00003497 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003498 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003499 SDOperand P;
3500 if (Flag == 0)
3501 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3502 else {
3503 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003504 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003505 }
3506 Chain = P.getValue(1);
Dan Gohman23ce5022008-04-25 18:27:55 +00003507 Parts[Part+i] = P;
3508 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003509
Dan Gohman23ce5022008-04-25 18:27:55 +00003510 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3511 ValueVT);
3512 Part += NumRegs;
3513 }
Chris Lattner6833b062008-04-28 07:16:35 +00003514
3515 if (ValueVTs.size() == 1)
3516 return Values[0];
3517
Dan Gohman23ce5022008-04-25 18:27:55 +00003518 return DAG.getNode(ISD::MERGE_VALUES,
3519 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3520 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003521}
3522
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003523/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3524/// specified value into the registers specified by this object. This uses
3525/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003526/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003527void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003528 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003529 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003530 unsigned NumRegs = Regs.size();
3531 SmallVector<SDOperand, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003532 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003533 MVT::ValueType ValueVT = ValueVTs[Value];
3534 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3535 MVT::ValueType RegisterVT = RegVTs[Value];
3536
3537 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3538 &Parts[Part], NumParts, RegisterVT);
3539 Part += NumParts;
3540 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003541
3542 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003543 SmallVector<SDOperand, 8> Chains(NumRegs);
3544 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003545 SDOperand Part;
3546 if (Flag == 0)
3547 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3548 else {
3549 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003550 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003551 }
3552 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003553 }
Chris Lattner6833b062008-04-28 07:16:35 +00003554
Evan Cheng33bf38a2008-04-28 22:07:13 +00003555 if (NumRegs == 1 || Flag)
3556 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3557 // flagged to it. That is the CopyToReg nodes and the user are considered
3558 // a single scheduling unit. If we create a TokenFactor and return it as
3559 // chain, then the TokenFactor is both a predecessor (operand) of the
3560 // user as well as a successor (the TF operands are flagged to the user).
3561 // c1, f1 = CopyToReg
3562 // c2, f2 = CopyToReg
3563 // c3 = TokenFactor c1, c2
3564 // ...
3565 // = op c3, ..., f2
3566 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003567 else
3568 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003569}
Chris Lattner864635a2006-02-22 22:37:12 +00003570
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003571/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3572/// operand list. This adds the code marker and includes the number of
3573/// values added into it.
3574void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003575 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00003576 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3577 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003578 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3579 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Dan Gohman23ce5022008-04-25 18:27:55 +00003580 MVT::ValueType RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003581 for (unsigned i = 0; i != NumRegs; ++i)
3582 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003583 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003584}
Chris Lattner864635a2006-02-22 22:37:12 +00003585
3586/// isAllocatableRegister - If the specified register is safe to allocate,
3587/// i.e. it isn't a stack pointer or some other special register, return the
3588/// register class for the register. Otherwise, return null.
3589static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003590isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003591 const TargetLowering &TLI,
3592 const TargetRegisterInfo *TRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003593 MVT::ValueType FoundVT = MVT::Other;
3594 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003595 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3596 E = TRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003597 MVT::ValueType ThisVT = MVT::Other;
3598
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003599 const TargetRegisterClass *RC = *RCI;
3600 // If none of the the value types for this register class are valid, we
3601 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003602 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3603 I != E; ++I) {
3604 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003605 // If we have already found this register in a different register class,
3606 // choose the one with the largest VT specified. For example, on
3607 // PowerPC, we favor f64 register classes over f32.
3608 if (FoundVT == MVT::Other ||
3609 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3610 ThisVT = *I;
3611 break;
3612 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003613 }
3614 }
3615
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003616 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003617
Chris Lattner864635a2006-02-22 22:37:12 +00003618 // NOTE: This isn't ideal. In particular, this might allocate the
3619 // frame pointer in functions that need it (due to them not being taken
3620 // out of allocation, because a variable sized allocation hasn't been seen
3621 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003622 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3623 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003624 if (*I == Reg) {
3625 // We found a matching register class. Keep looking at others in case
3626 // we find one with larger registers that this physreg is also in.
3627 FoundRC = RC;
3628 FoundVT = ThisVT;
3629 break;
3630 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003631 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003632 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003633}
3634
Chris Lattner4e4b5762006-02-01 18:59:47 +00003635
Chris Lattner0c583402007-04-28 20:49:53 +00003636namespace {
3637/// AsmOperandInfo - This contains information for each constraint that we are
3638/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003639struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3640 /// CallOperand - If this is the result output operand or a clobber
3641 /// this is null, otherwise it is the incoming operand to the CallInst.
3642 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003643 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003644
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003645 /// AssignedRegs - If this is a register or register class operand, this
3646 /// contains the set of register corresponding to the operand.
3647 RegsForValue AssignedRegs;
3648
Dan Gohman23ce5022008-04-25 18:27:55 +00003649 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003650 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003651 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003652
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003653 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3654 /// busy in OutputRegs/InputRegs.
3655 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3656 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003657 std::set<unsigned> &InputRegs,
3658 const TargetRegisterInfo &TRI) const {
3659 if (isOutReg) {
3660 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3661 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3662 }
3663 if (isInReg) {
3664 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3665 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3666 }
3667 }
3668
3669private:
3670 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3671 /// specified set.
3672 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3673 const TargetRegisterInfo &TRI) {
3674 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3675 Regs.insert(Reg);
3676 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3677 for (; *Aliases; ++Aliases)
3678 Regs.insert(*Aliases);
3679 }
Chris Lattner0c583402007-04-28 20:49:53 +00003680};
3681} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003682
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003683
Chris Lattner0fe71e92008-02-21 19:43:13 +00003684/// GetRegistersForValue - Assign registers (virtual or physical) for the
3685/// specified operand. We prefer to assign virtual registers, to allow the
3686/// register allocator handle the assignment process. However, if the asm uses
3687/// features that we can't model on machineinstrs, we have SDISel do the
3688/// allocation. This produces generally horrible, but correct, code.
3689///
3690/// OpInfo describes the operand.
3691/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3692/// or any explicitly clobbered registers.
3693/// Input and OutputRegs are the set of already allocated physical registers.
3694///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003695void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003696GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003697 std::set<unsigned> &OutputRegs,
3698 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003699 // Compute whether this value requires an input register, an output register,
3700 // or both.
3701 bool isOutReg = false;
3702 bool isInReg = false;
3703 switch (OpInfo.Type) {
3704 case InlineAsm::isOutput:
3705 isOutReg = true;
3706
3707 // If this is an early-clobber output, or if there is an input
3708 // constraint that matches this, we need to reserve the input register
3709 // so no other inputs allocate to it.
3710 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3711 break;
3712 case InlineAsm::isInput:
3713 isInReg = true;
3714 isOutReg = false;
3715 break;
3716 case InlineAsm::isClobber:
3717 isOutReg = true;
3718 isInReg = true;
3719 break;
3720 }
3721
3722
3723 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003724 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003725
3726 // If this is a constraint for a single physreg, or a constraint for a
3727 // register class, find it.
3728 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3729 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3730 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003731
3732 unsigned NumRegs = 1;
3733 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003734 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003735 MVT::ValueType RegVT;
3736 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3737
Chris Lattnerbf996f12007-04-30 17:29:31 +00003738
3739 // If this is a constraint for a specific physical register, like {r17},
3740 // assign it now.
3741 if (PhysReg.first) {
3742 if (OpInfo.ConstraintVT == MVT::Other)
3743 ValueVT = *PhysReg.second->vt_begin();
3744
3745 // Get the actual register value type. This is important, because the user
3746 // may have asked for (e.g.) the AX register in i32 type. We need to
3747 // remember that AX is actually i16 to get the right extension.
3748 RegVT = *PhysReg.second->vt_begin();
3749
3750 // This is a explicit reference to a physical register.
3751 Regs.push_back(PhysReg.first);
3752
3753 // If this is an expanded reference, add the rest of the regs to Regs.
3754 if (NumRegs != 1) {
3755 TargetRegisterClass::iterator I = PhysReg.second->begin();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003756 for (; *I != PhysReg.first; ++I)
Evan Cheng50871242008-05-14 20:07:51 +00003757 assert(I != PhysReg.second->end() && "Didn't find reg!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00003758
3759 // Already added the first reg.
3760 --NumRegs; ++I;
3761 for (; NumRegs; --NumRegs, ++I) {
Evan Cheng50871242008-05-14 20:07:51 +00003762 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00003763 Regs.push_back(*I);
3764 }
3765 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003766 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003767 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3768 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003769 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003770 }
3771
3772 // Otherwise, if this was a reference to an LLVM register class, create vregs
3773 // for this reference.
3774 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003775 const TargetRegisterClass *RC = PhysReg.second;
3776 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003777 // If this is an early clobber or tied register, our regalloc doesn't know
3778 // how to maintain the constraint. If it isn't, go ahead and create vreg
3779 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003780 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3781 // If there is some other early clobber and this is an input register,
3782 // then we are forced to pre-allocate the input reg so it doesn't
3783 // conflict with the earlyclobber.
3784 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003785 RegVT = *PhysReg.second->vt_begin();
3786
3787 if (OpInfo.ConstraintVT == MVT::Other)
3788 ValueVT = RegVT;
3789
3790 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00003791 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003792 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00003793 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00003794
Dan Gohman23ce5022008-04-25 18:27:55 +00003795 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003796 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003797 }
3798
3799 // Otherwise, we can't allocate it. Let the code below figure out how to
3800 // maintain these constraints.
3801 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3802
3803 } else {
3804 // This is a reference to a register class that doesn't directly correspond
3805 // to an LLVM register class. Allocate NumRegs consecutive, available,
3806 // registers from the class.
3807 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3808 OpInfo.ConstraintVT);
3809 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003810
Dan Gohman6f0d0242008-02-10 18:45:23 +00003811 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003812 unsigned NumAllocated = 0;
3813 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3814 unsigned Reg = RegClassRegs[i];
3815 // See if this register is available.
3816 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3817 (isInReg && InputRegs.count(Reg))) { // Already used.
3818 // Make sure we find consecutive registers.
3819 NumAllocated = 0;
3820 continue;
3821 }
3822
3823 // Check to see if this register is allocatable (i.e. don't give out the
3824 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003825 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00003826 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003827 if (!RC) { // Couldn't allocate this register.
3828 // Reset NumAllocated to make sure we return consecutive registers.
3829 NumAllocated = 0;
3830 continue;
3831 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003832 }
3833
3834 // Okay, this register is good, we can use it.
3835 ++NumAllocated;
3836
3837 // If we allocated enough consecutive registers, succeed.
3838 if (NumAllocated == NumRegs) {
3839 unsigned RegStart = (i-NumAllocated)+1;
3840 unsigned RegEnd = i+1;
3841 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003842 for (unsigned i = RegStart; i != RegEnd; ++i)
3843 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003844
Dan Gohman23ce5022008-04-25 18:27:55 +00003845 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003846 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003847 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003848 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003849 }
3850 }
3851
3852 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00003853}
3854
3855
Chris Lattnerce7518c2006-01-26 22:24:51 +00003856/// visitInlineAsm - Handle a call to an InlineAsm object.
3857///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003858void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3859 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003860
Chris Lattner0c583402007-04-28 20:49:53 +00003861 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00003862 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003863
3864 SDOperand Chain = getRoot();
3865 SDOperand Flag;
3866
Chris Lattner4e4b5762006-02-01 18:59:47 +00003867 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003868
Chris Lattner0c583402007-04-28 20:49:53 +00003869 // Do a prepass over the constraints, canonicalizing them, and building up the
3870 // ConstraintOperands list.
3871 std::vector<InlineAsm::ConstraintInfo>
3872 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003873
3874 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3875 // constraint. If so, we can't let the register allocator allocate any input
3876 // registers, because it will not know to avoid the earlyclobbered output reg.
3877 bool SawEarlyClobber = false;
3878
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003879 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00003880 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00003881 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003882 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3883 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00003884
Chris Lattner0c583402007-04-28 20:49:53 +00003885 MVT::ValueType OpVT = MVT::Other;
3886
3887 // Compute the value type for each operand.
3888 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003889 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00003890 // Indirect outputs just consume an argument.
3891 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003892 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00003893 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003894 }
Chris Lattneracf8b012008-04-27 23:44:28 +00003895 // The return value of the call is this value. As such, there is no
3896 // corresponding argument.
3897 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3898 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3899 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3900 } else {
3901 assert(ResNo == 0 && "Asm only has one result!");
3902 OpVT = TLI.getValueType(CS.getType());
3903 }
3904 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003905 break;
3906 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003907 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003908 break;
3909 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003910 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003911 break;
3912 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003913
Chris Lattner0c583402007-04-28 20:49:53 +00003914 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003915 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00003916 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00003917 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3918 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003919 else {
3920 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3921 const Type *OpTy = OpInfo.CallOperandVal->getType();
3922 // If this is an indirect operand, the operand is a pointer to the
3923 // accessed type.
3924 if (OpInfo.isIndirect)
3925 OpTy = cast<PointerType>(OpTy)->getElementType();
3926
3927 // If OpTy is not a first-class value, it may be a struct/union that we
3928 // can tile with integers.
3929 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3930 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3931 switch (BitSize) {
3932 default: break;
3933 case 1:
3934 case 8:
3935 case 16:
3936 case 32:
3937 case 64:
3938 OpTy = IntegerType::get(BitSize);
3939 break;
3940 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003941 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003942
3943 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003944 }
3945 }
3946
3947 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003948
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003949 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00003950 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00003951
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003952 // Keep track of whether we see an earlyclobber.
3953 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003954
Chris Lattner0fe71e92008-02-21 19:43:13 +00003955 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00003956 if (!SawEarlyClobber &&
3957 OpInfo.Type == InlineAsm::isClobber &&
3958 OpInfo.ConstraintType == TargetLowering::C_Register) {
3959 // Note that we want to ignore things that we don't trick here, like
3960 // dirflag, fpsr, flags, etc.
3961 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3962 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3963 OpInfo.ConstraintVT);
3964 if (PhysReg.first || PhysReg.second) {
3965 // This is a register we know of.
3966 SawEarlyClobber = true;
3967 }
3968 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00003969
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003970 // If this is a memory input, and if the operand is not indirect, do what we
3971 // need to to provide an address for the memory input.
3972 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3973 !OpInfo.isIndirect) {
3974 assert(OpInfo.Type == InlineAsm::isInput &&
3975 "Can only indirectify direct input operands!");
3976
3977 // Memory operands really want the address of the value. If we don't have
3978 // an indirect input, put it in the constpool if we can, otherwise spill
3979 // it to a stack slot.
3980
3981 // If the operand is a float, integer, or vector constant, spill to a
3982 // constant pool entry to get its address.
3983 Value *OpVal = OpInfo.CallOperandVal;
3984 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3985 isa<ConstantVector>(OpVal)) {
3986 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3987 TLI.getPointerTy());
3988 } else {
3989 // Otherwise, create a stack slot and emit a store to it before the
3990 // asm.
3991 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00003992 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003993 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3994 MachineFunction &MF = DAG.getMachineFunction();
3995 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3996 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3997 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3998 OpInfo.CallOperand = StackSlot;
3999 }
4000
4001 // There is no longer a Value* corresponding to this operand.
4002 OpInfo.CallOperandVal = 0;
4003 // It is now an indirect operand.
4004 OpInfo.isIndirect = true;
4005 }
4006
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004007 // If this constraint is for a specific register, allocate it before
4008 // anything else.
4009 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4010 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004011 }
Chris Lattner0c583402007-04-28 20:49:53 +00004012 ConstraintInfos.clear();
4013
4014
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004015 // Second pass - Loop over all of the operands, assigning virtual or physregs
4016 // to registerclass operands.
4017 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004018 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004019
4020 // C_Register operands have already been allocated, Other/Memory don't need
4021 // to be.
4022 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4023 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4024 }
4025
Chris Lattner0c583402007-04-28 20:49:53 +00004026 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4027 std::vector<SDOperand> AsmNodeOperands;
4028 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
4029 AsmNodeOperands.push_back(
4030 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4031
Chris Lattner2cc2f662006-02-01 01:28:23 +00004032
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004033 // Loop over all of the inputs, copying the operand values into the
4034 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004035 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004036
Chris Lattner0c583402007-04-28 20:49:53 +00004037 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4038 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4039
4040 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004041 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004042
Chris Lattner0c583402007-04-28 20:49:53 +00004043 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004044 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004045 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4046 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004047 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004048 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004049
Chris Lattner22873462006-02-27 23:45:39 +00004050 // Add information to the INLINEASM node to know about this output.
4051 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004052 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4053 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004054 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004055 break;
4056 }
4057
Chris Lattner2a600be2007-04-28 21:01:43 +00004058 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004059
Chris Lattner864635a2006-02-22 22:37:12 +00004060 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004061 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004062 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004063 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004064 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004065 exit(1);
4066 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004067
Chris Lattner41f62592008-04-29 04:29:54 +00004068 // If this is an indirect operand, store through the pointer after the
4069 // asm.
4070 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004071 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004072 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004073 } else {
4074 // This is the result value of the call.
4075 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4076 // Concatenate this output onto the outputs list.
4077 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004078 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004079
4080 // Add information to the INLINEASM node to know that this register is
4081 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004082 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4083 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004084 break;
4085 }
4086 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00004087 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004088
Chris Lattner0c583402007-04-28 20:49:53 +00004089 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004090 // If this is required to match an output register we have already set,
4091 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004092 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004093
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004094 // Scan until we find the definition we already emitted of this operand.
4095 // When we find it, create a RegsForValue operand.
4096 unsigned CurOp = 2; // The first operand.
4097 for (; OperandNo; --OperandNo) {
4098 // Advance to the next operand.
4099 unsigned NumOps =
4100 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004101 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4102 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004103 "Skipped past definitions?");
4104 CurOp += (NumOps>>3)+1;
4105 }
4106
4107 unsigned NumOps =
4108 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004109 if ((NumOps & 7) == 2 /*REGDEF*/) {
4110 // Add NumOps>>3 registers to MatchedRegs.
4111 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004112 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004113 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4114 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004115 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4116 unsigned Reg =
4117 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4118 MatchedRegs.Regs.push_back(Reg);
4119 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004120
Chris Lattner527fae12007-02-01 01:21:12 +00004121 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004122 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004123 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4124 break;
4125 } else {
4126 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004127 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4128 // Add information to the INLINEASM node to know about this input.
4129 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4130 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4131 TLI.getPointerTy()));
4132 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4133 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004134 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004135 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004136
Chris Lattner2a600be2007-04-28 21:01:43 +00004137 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004138 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004139 "Don't know how to handle indirect other inputs yet!");
4140
Chris Lattner48884cd2007-08-25 00:47:38 +00004141 std::vector<SDOperand> Ops;
4142 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4143 Ops, DAG);
4144 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004145 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004146 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004147 exit(1);
4148 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004149
4150 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004151 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004152 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4153 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004154 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004155 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004156 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004157 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004158 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4159 "Memory operands expect pointer values");
4160
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004161 // Add information to the INLINEASM node to know about this input.
4162 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004163 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4164 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004165 AsmNodeOperands.push_back(InOperandVal);
4166 break;
4167 }
4168
Chris Lattner2a600be2007-04-28 21:01:43 +00004169 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4170 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4171 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004172 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004173 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004174
4175 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004176 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4177 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004178
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004179 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004180
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004181 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4182 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004183 break;
4184 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004185 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004186 // Add the clobbered value to the operand list, so that the register
4187 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004188 if (!OpInfo.AssignedRegs.Regs.empty())
4189 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4190 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004191 break;
4192 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004193 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004194 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004195
4196 // Finish up input operands.
4197 AsmNodeOperands[0] = Chain;
4198 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4199
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004200 Chain = DAG.getNode(ISD::INLINEASM,
4201 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004202 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004203 Flag = Chain.getValue(1);
4204
Chris Lattner6656dd12006-01-31 02:03:41 +00004205 // If this asm returns a register value, copy the result from that register
4206 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004207 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004208 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004209
4210 // If any of the results of the inline asm is a vector, it may have the
4211 // wrong width/num elts. This can happen for register classes that can
4212 // contain multiple different value types. The preg or vreg allocated may
4213 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004214 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004215 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4216 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4217 if (MVT::isVector(Val.Val->getValueType(i)))
4218 Val = DAG.getNode(ISD::BIT_CONVERT,
4219 TLI.getValueType(ResSTy->getElementType(i)), Val);
4220 }
4221 } else {
4222 if (MVT::isVector(Val.getValueType()))
4223 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4224 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004225 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004226
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004227 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004228 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004229
Chris Lattner6656dd12006-01-31 02:03:41 +00004230 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4231
4232 // Process indirect outputs, first output all of the flagged copies out of
4233 // physregs.
4234 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004235 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004236 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004237 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004238 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004239 }
4240
4241 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004242 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004243 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004244 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004245 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004246 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004247 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004248 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4249 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004250 DAG.setRoot(Chain);
4251}
4252
4253
Chris Lattner1c08c712005-01-07 07:47:53 +00004254void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4255 SDOperand Src = getValue(I.getOperand(0));
4256
4257 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004258
4259 if (IntPtr < Src.getValueType())
4260 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4261 else if (IntPtr > Src.getValueType())
4262 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004263
4264 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004265 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004266 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004267 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004268
Reid Spencer47857812006-12-31 05:55:36 +00004269 TargetLowering::ArgListTy Args;
4270 TargetLowering::ArgListEntry Entry;
4271 Entry.Node = Src;
4272 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004273 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004274
4275 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004276 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4277 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004278 setValue(&I, Result.first); // Pointers always fit in registers
4279 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004280}
4281
4282void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004283 TargetLowering::ArgListTy Args;
4284 TargetLowering::ArgListEntry Entry;
4285 Entry.Node = getValue(I.getOperand(0));
4286 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004287 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00004288 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004289 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004290 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4291 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004292 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4293 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004294}
4295
Evan Chengff9b3732008-01-30 18:18:23 +00004296// EmitInstrWithCustomInserter - This method should be implemented by targets
4297// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004298// instructions are special in various ways, which require special support to
4299// insert. The specified MachineInstr is created but not inserted into any
4300// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004301MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004302 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004303 cerr << "If a target marks an instruction with "
4304 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004305 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004306 abort();
4307 return 0;
4308}
4309
Chris Lattner39ae3622005-01-09 00:00:49 +00004310void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004311 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4312 getValue(I.getOperand(1)),
4313 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004314}
4315
4316void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004317 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4318 getValue(I.getOperand(0)),
4319 DAG.getSrcValue(I.getOperand(0)));
4320 setValue(&I, V);
4321 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004322}
4323
4324void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004325 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4326 getValue(I.getOperand(1)),
4327 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004328}
4329
4330void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004331 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4332 getValue(I.getOperand(1)),
4333 getValue(I.getOperand(2)),
4334 DAG.getSrcValue(I.getOperand(1)),
4335 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004336}
4337
Chris Lattnerfdfded52006-04-12 16:20:43 +00004338/// TargetLowering::LowerArguments - This is the default LowerArguments
4339/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004340/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4341/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004342std::vector<SDOperand>
4343TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4344 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4345 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004346 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004347 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4348 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4349
4350 // Add one result value for each formal argument.
4351 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004352 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004353 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4354 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004355 MVT::ValueType VT = getValueType(I->getType());
Duncan Sands276dcbd2008-03-21 09:14:45 +00004356 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004357 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004358 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004359
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004360 if (F.paramHasAttr(j, ParamAttr::ZExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004361 Flags.setZExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004362 if (F.paramHasAttr(j, ParamAttr::SExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004363 Flags.setSExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004364 if (F.paramHasAttr(j, ParamAttr::InReg))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004365 Flags.setInReg();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004366 if (F.paramHasAttr(j, ParamAttr::StructRet))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004367 Flags.setSRet();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004368 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004369 Flags.setByVal();
Rafael Espindola594d37e2007-08-10 14:44:42 +00004370 const PointerType *Ty = cast<PointerType>(I->getType());
Duncan Sandsa41d7192008-01-13 21:19:59 +00004371 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004372 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004373 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004374 // For ByVal, alignment should be passed from FE. BE will guess if
4375 // this info is not there but there are cases it cannot get right.
4376 if (F.getParamAlignment(j))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004377 FrameAlign = F.getParamAlignment(j);
4378 Flags.setByValAlign(FrameAlign);
4379 Flags.setByValSize(FrameSize);
Rafael Espindola594d37e2007-08-10 14:44:42 +00004380 }
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004381 if (F.paramHasAttr(j, ParamAttr::Nest))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004382 Flags.setNest();
4383 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004384
4385 MVT::ValueType RegisterVT = getRegisterType(VT);
4386 unsigned NumRegs = getNumRegisters(VT);
4387 for (unsigned i = 0; i != NumRegs; ++i) {
4388 RetVals.push_back(RegisterVT);
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004389 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004390 if (NumRegs > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004391 MyFlags.setSplit();
Duncan Sandsb988bac2008-02-11 20:58:28 +00004392 // if it isn't first piece, alignment must be 1
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004393 else if (i > 0)
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004394 MyFlags.setOrigAlign(1);
4395 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004396 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004397 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004398
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004399 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004400
4401 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004402 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004403 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004404 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004405
4406 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4407 // allows exposing the loads that may be part of the argument access to the
4408 // first DAGCombiner pass.
4409 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4410
4411 // The number of results should match up, except that the lowered one may have
4412 // an extra flag result.
4413 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4414 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4415 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4416 && "Lowering produced unexpected number of results!");
4417 Result = TmpRes.Val;
4418
Dan Gohman27a70be2007-07-02 16:18:06 +00004419 unsigned NumArgRegs = Result->getNumValues() - 1;
4420 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004421
4422 // Set up the return result vector.
4423 Ops.clear();
4424 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004425 unsigned Idx = 1;
4426 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4427 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004428 MVT::ValueType VT = getValueType(I->getType());
Duncan Sandsb988bac2008-02-11 20:58:28 +00004429 MVT::ValueType PartVT = getRegisterType(VT);
4430
4431 unsigned NumParts = getNumRegisters(VT);
4432 SmallVector<SDOperand, 4> Parts(NumParts);
4433 for (unsigned j = 0; j != NumParts; ++j)
4434 Parts[j] = SDOperand(Result, i++);
4435
4436 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4437 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4438 AssertOp = ISD::AssertSext;
4439 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4440 AssertOp = ISD::AssertZext;
4441
4442 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
Chris Lattner4468c1f2008-03-09 09:38:46 +00004443 AssertOp));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004444 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004445 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004446 return Ops;
4447}
4448
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004449
4450/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4451/// implementation, which just inserts an ISD::CALL node, which is later custom
4452/// lowered by the target to something concrete. FIXME: When all targets are
4453/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4454std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004455TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4456 bool RetSExt, bool RetZExt, bool isVarArg,
4457 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004458 SDOperand Callee,
4459 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004460 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004461 Ops.push_back(Chain); // Op#0 - Chain
4462 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4463 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4464 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4465 Ops.push_back(Callee);
4466
4467 // Handle all of the outgoing arguments.
4468 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00004469 MVT::ValueType VT = getValueType(Args[i].Ty);
4470 SDOperand Op = Args[i].Node;
Duncan Sands276dcbd2008-03-21 09:14:45 +00004471 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004472 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004473 getTargetData()->getABITypeAlignment(Args[i].Ty);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004474
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004475 if (Args[i].isZExt)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004476 Flags.setZExt();
4477 if (Args[i].isSExt)
4478 Flags.setSExt();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004479 if (Args[i].isInReg)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004480 Flags.setInReg();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004481 if (Args[i].isSRet)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004482 Flags.setSRet();
Rafael Espindola21485be2007-08-20 15:18:24 +00004483 if (Args[i].isByVal) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004484 Flags.setByVal();
Rafael Espindola21485be2007-08-20 15:18:24 +00004485 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004486 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004487 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004488 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004489 // For ByVal, alignment should come from FE. BE will guess if this
4490 // info is not there but there are cases it cannot get right.
4491 if (Args[i].Alignment)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004492 FrameAlign = Args[i].Alignment;
4493 Flags.setByValAlign(FrameAlign);
4494 Flags.setByValSize(FrameSize);
Rafael Espindola21485be2007-08-20 15:18:24 +00004495 }
Duncan Sands36397f52007-07-27 12:58:54 +00004496 if (Args[i].isNest)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004497 Flags.setNest();
4498 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004499
Duncan Sandsb988bac2008-02-11 20:58:28 +00004500 MVT::ValueType PartVT = getRegisterType(VT);
4501 unsigned NumParts = getNumRegisters(VT);
4502 SmallVector<SDOperand, 4> Parts(NumParts);
4503 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4504
4505 if (Args[i].isSExt)
4506 ExtendKind = ISD::SIGN_EXTEND;
4507 else if (Args[i].isZExt)
4508 ExtendKind = ISD::ZERO_EXTEND;
4509
4510 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4511
4512 for (unsigned i = 0; i != NumParts; ++i) {
4513 // if it isn't first piece, alignment must be 1
Duncan Sands276dcbd2008-03-21 09:14:45 +00004514 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004515 if (NumParts > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004516 MyFlags.setSplit();
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004517 else if (i != 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004518 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004519
4520 Ops.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004521 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohman27a70be2007-07-02 16:18:06 +00004522 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004523 }
4524
Dan Gohmanef5d1942008-03-11 21:11:25 +00004525 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004526 // the potentially illegal return value types.
Dan Gohmanef5d1942008-03-11 21:11:25 +00004527 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4528 SmallVector<MVT::ValueType, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004529 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004530
Dan Gohman23ce5022008-04-25 18:27:55 +00004531 // Then we translate that to a list of legal types.
4532 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4533 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004534 MVT::ValueType RegisterVT = getRegisterType(VT);
4535 unsigned NumRegs = getNumRegisters(VT);
4536 for (unsigned i = 0; i != NumRegs; ++i)
4537 LoweredRetTys.push_back(RegisterVT);
4538 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004539
Dan Gohmanef5d1942008-03-11 21:11:25 +00004540 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004541
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004542 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004543 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004544 DAG.getVTList(&LoweredRetTys[0],
4545 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004546 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004547 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004548
4549 // Gather up the call result into a single value.
4550 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004551 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4552
4553 if (RetSExt)
4554 AssertOp = ISD::AssertSext;
4555 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004556 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004557
Dan Gohmanef5d1942008-03-11 21:11:25 +00004558 SmallVector<SDOperand, 4> ReturnValues;
4559 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004560 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4561 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004562 MVT::ValueType RegisterVT = getRegisterType(VT);
4563 unsigned NumRegs = getNumRegisters(VT);
4564 unsigned RegNoEnd = NumRegs + RegNo;
4565 SmallVector<SDOperand, 4> Results;
4566 for (; RegNo != RegNoEnd; ++RegNo)
4567 Results.push_back(Res.getValue(RegNo));
4568 SDOperand ReturnValue =
4569 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4570 AssertOp);
4571 ReturnValues.push_back(ReturnValue);
4572 }
4573 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4574 DAG.getNode(ISD::MERGE_VALUES,
4575 DAG.getVTList(&RetTys[0], RetTys.size()),
4576 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004577 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004578
4579 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004580}
4581
Chris Lattner50381b62005-05-14 05:50:48 +00004582SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004583 assert(0 && "LowerOperation not implemented for this target!");
4584 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004585 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004586}
4587
Nate Begeman0aed7842006-01-28 03:14:31 +00004588SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4589 SelectionDAG &DAG) {
4590 assert(0 && "CustomPromoteOperation not implemented for this target!");
4591 abort();
4592 return SDOperand();
4593}
4594
Chris Lattner7041ee32005-01-11 05:56:49 +00004595//===----------------------------------------------------------------------===//
4596// SelectionDAGISel code
4597//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004598
4599unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004600 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004601}
4602
Chris Lattner495a0b52005-08-17 06:37:43 +00004603void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004604 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004605 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004606 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004607}
Chris Lattner1c08c712005-01-07 07:47:53 +00004608
Chris Lattner1c08c712005-01-07 07:47:53 +00004609bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004610 // Get alias analysis for load/store combining.
4611 AA = &getAnalysis<AliasAnalysis>();
4612
Chris Lattner1c08c712005-01-07 07:47:53 +00004613 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004614 if (MF.getFunction()->hasCollector())
4615 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4616 else
4617 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004618 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004619 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004620
4621 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4622
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004623 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4624 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4625 // Mark landing pad.
4626 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004627
4628 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004629 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004630
Evan Chengad2070c2007-02-10 02:43:39 +00004631 // Add function live-ins to entry block live-in set.
4632 BasicBlock *EntryBB = &Fn.getEntryBlock();
4633 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004634 if (!RegInfo->livein_empty())
4635 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4636 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004637 BB->addLiveIn(I->first);
4638
Duncan Sandsf4070822007-06-15 19:04:19 +00004639#ifndef NDEBUG
4640 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4641 "Not all catch info was assigned to a landing pad!");
4642#endif
4643
Chris Lattner1c08c712005-01-07 07:47:53 +00004644 return true;
4645}
4646
Chris Lattner6833b062008-04-28 07:16:35 +00004647void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004648 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004649 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004650 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004651 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004652 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004653
Dan Gohman23ce5022008-04-25 18:27:55 +00004654 RegsForValue RFV(TLI, Reg, V->getType());
4655 SDOperand Chain = DAG.getEntryNode();
4656 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4657 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004658}
4659
Chris Lattner068a81e2005-01-17 17:15:02 +00004660void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004661LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004662 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004663 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004664 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004665 SDOperand OldRoot = SDL.DAG.getRoot();
4666 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004667
Chris Lattnerbf209482005-10-30 19:42:35 +00004668 unsigned a = 0;
4669 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4670 AI != E; ++AI, ++a)
4671 if (!AI->use_empty()) {
4672 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004673
Chris Lattnerbf209482005-10-30 19:42:35 +00004674 // If this argument is live outside of the entry block, insert a copy from
4675 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004676 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4677 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004678 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004679 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004680 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004681
Chris Lattnerbf209482005-10-30 19:42:35 +00004682 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004683 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004684 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004685}
4686
Duncan Sandsf4070822007-06-15 19:04:19 +00004687static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4688 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004689 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004690 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004691 // Apply the catch info to DestBB.
4692 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4693#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004694 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4695 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004696#endif
4697 }
4698}
4699
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004700/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4701/// whether object offset >= 0.
4702static bool
4703IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4704 if (!isa<FrameIndexSDNode>(Op)) return false;
4705
4706 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4707 int FrameIdx = FrameIdxNode->getIndex();
4708 return MFI->isFixedObjectIndex(FrameIdx) &&
4709 MFI->getObjectOffset(FrameIdx) >= 0;
4710}
4711
4712/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4713/// possibly be overwritten when lowering the outgoing arguments in a tail
4714/// call. Currently the implementation of this call is very conservative and
4715/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4716/// virtual registers would be overwritten by direct lowering.
4717static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4718 MachineFrameInfo * MFI) {
4719 RegisterSDNode * OpReg = NULL;
4720 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4721 (Op.getOpcode()== ISD::CopyFromReg &&
4722 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4723 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4724 (Op.getOpcode() == ISD::LOAD &&
4725 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4726 (Op.getOpcode() == ISD::MERGE_VALUES &&
4727 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4728 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4729 getOperand(1))))
4730 return true;
4731 return false;
4732}
4733
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004734/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004735/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004736static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4737 TargetLowering& TLI) {
4738 SDNode * Ret = NULL;
4739 SDOperand Terminator = DAG.getRoot();
4740
4741 // Find RET node.
4742 if (Terminator.getOpcode() == ISD::RET) {
4743 Ret = Terminator.Val;
4744 }
4745
4746 // Fix tail call attribute of CALL nodes.
4747 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4748 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4749 if (BI->getOpcode() == ISD::CALL) {
4750 SDOperand OpRet(Ret, 0);
4751 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4752 bool isMarkedTailCall =
4753 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4754 // If CALL node has tail call attribute set to true and the call is not
4755 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004756 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004757 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004758 if (!isMarkedTailCall) continue;
4759 if (Ret==NULL ||
4760 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
4761 // Not eligible. Mark CALL node as non tail call.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004762 SmallVector<SDOperand, 32> Ops;
4763 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004764 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4765 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004766 if (idx!=3)
4767 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004768 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004769 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4770 }
4771 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004772 } else {
4773 // Look for tail call clobbered arguments. Emit a series of
4774 // copyto/copyfrom virtual register nodes to protect them.
4775 SmallVector<SDOperand, 32> Ops;
4776 SDOperand Chain = OpCall.getOperand(0), InFlag;
4777 unsigned idx=0;
4778 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
4779 E = OpCall.Val->op_end(); I != E; I++, idx++) {
4780 SDOperand Arg = *I;
4781 if (idx > 4 && (idx % 2)) {
4782 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
4783 getArgFlags().isByVal();
4784 MachineFunction &MF = DAG.getMachineFunction();
4785 MachineFrameInfo *MFI = MF.getFrameInfo();
4786 if (!isByVal &&
4787 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
4788 MVT::ValueType VT = Arg.getValueType();
4789 unsigned VReg = MF.getRegInfo().
4790 createVirtualRegister(TLI.getRegClassFor(VT));
4791 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
4792 InFlag = Chain.getValue(1);
4793 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
4794 Chain = Arg.getValue(1);
4795 InFlag = Arg.getValue(2);
4796 }
4797 }
4798 Ops.push_back(Arg);
4799 }
4800 // Link in chain of CopyTo/CopyFromReg.
4801 Ops[0] = Chain;
4802 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004803 }
4804 }
4805 }
4806}
4807
Chris Lattner1c08c712005-01-07 07:47:53 +00004808void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4809 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004810 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00004811 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004812
Chris Lattnerbf209482005-10-30 19:42:35 +00004813 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004814 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004815 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00004816
4817 BB = FuncInfo.MBBMap[LLVMBB];
4818 SDL.setCurrentBasicBlock(BB);
4819
Duncan Sandsf4070822007-06-15 19:04:19 +00004820 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004821
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004822 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004823 // Add a label to mark the beginning of the landing pad. Deletion of the
4824 // landing pad can thus be detected via the MachineModuleInfo.
4825 unsigned LabelID = MMI->addLandingPad(BB);
4826 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00004827 DAG.getConstant(LabelID, MVT::i32),
4828 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00004829
Evan Chenge47c3332007-06-27 18:45:32 +00004830 // Mark exception register as live in.
4831 unsigned Reg = TLI.getExceptionAddressRegister();
4832 if (Reg) BB->addLiveIn(Reg);
4833
4834 // Mark exception selector register as live in.
4835 Reg = TLI.getExceptionSelectorRegister();
4836 if (Reg) BB->addLiveIn(Reg);
4837
Duncan Sandsf4070822007-06-15 19:04:19 +00004838 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4839 // function and list of typeids logically belong to the invoke (or, if you
4840 // like, the basic block containing the invoke), and need to be associated
4841 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004842 // information is provided by an intrinsic (eh.selector) that can be moved
4843 // to unexpected places by the optimizers: if the unwind edge is critical,
4844 // then breaking it can result in the intrinsics being in the successor of
4845 // the landing pad, not the landing pad itself. This results in exceptions
4846 // not being caught because no typeids are associated with the invoke.
4847 // This may not be the only way things can go wrong, but it is the only way
4848 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004849 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4850
4851 if (Br && Br->isUnconditional()) { // Critical edge?
4852 BasicBlock::iterator I, E;
4853 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004854 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004855 break;
4856
4857 if (I == E)
4858 // No catch info found - try to extract some from the successor.
4859 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004860 }
4861 }
4862
Chris Lattner1c08c712005-01-07 07:47:53 +00004863 // Lower all of the non-terminator instructions.
4864 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4865 I != E; ++I)
4866 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004867
Chris Lattner1c08c712005-01-07 07:47:53 +00004868 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004869 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004870 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004871 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004872 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004873 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004874 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004875 }
4876
4877 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4878 // ensure constants are generated when needed. Remember the virtual registers
4879 // that need to be added to the Machine PHI nodes as input. We cannot just
4880 // directly add them, because expansion might result in multiple MBB's for one
4881 // BB. As such, the start of the BB might correspond to a different MBB than
4882 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004883 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004884 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004885
4886 // Emit constants only once even if used by multiple PHI nodes.
4887 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004888
Chris Lattner8c494ab2006-10-27 23:50:33 +00004889 // Vector bool would be better, but vector<bool> is really slow.
4890 std::vector<unsigned char> SuccsHandled;
4891 if (TI->getNumSuccessors())
4892 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4893
Dan Gohman532dc2e2007-07-09 20:59:04 +00004894 // Check successor nodes' PHI nodes that expect a constant to be available
4895 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004896 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4897 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004898 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004899 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004900
Chris Lattner8c494ab2006-10-27 23:50:33 +00004901 // If this terminator has multiple identical successors (common for
4902 // switches), only handle each succ once.
4903 unsigned SuccMBBNo = SuccMBB->getNumber();
4904 if (SuccsHandled[SuccMBBNo]) continue;
4905 SuccsHandled[SuccMBBNo] = true;
4906
4907 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004908 PHINode *PN;
4909
4910 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4911 // nodes and Machine PHI nodes, but the incoming operands have not been
4912 // emitted yet.
4913 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004914 (PN = dyn_cast<PHINode>(I)); ++I) {
4915 // Ignore dead phi's.
4916 if (PN->use_empty()) continue;
4917
4918 unsigned Reg;
4919 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004920
Chris Lattner8c494ab2006-10-27 23:50:33 +00004921 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4922 unsigned &RegOut = ConstantsOut[C];
4923 if (RegOut == 0) {
4924 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004925 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00004926 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004927 Reg = RegOut;
4928 } else {
4929 Reg = FuncInfo.ValueMap[PHIOp];
4930 if (Reg == 0) {
4931 assert(isa<AllocaInst>(PHIOp) &&
4932 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4933 "Didn't codegen value into a register!??");
4934 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004935 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00004936 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004937 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004938
4939 // Remember that this register needs to added to the machine PHI node as
4940 // the input for this MBB.
4941 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004942 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004943 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004944 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4945 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004946 }
4947 ConstantsOut.clear();
4948
4949 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004950 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004951
Nate Begemanf15485a2006-03-27 01:32:24 +00004952 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004953 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004954 SwitchCases.clear();
4955 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004956 JTCases.clear();
4957 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004958 BitTestCases.clear();
4959 BitTestCases = SDL.BitTestCases;
4960
Chris Lattnera651cf62005-01-17 19:43:36 +00004961 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004962 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004963
4964 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4965 // with correct tailcall attribute so that the target can rely on the tailcall
4966 // attribute indicating whether the call is really eligible for tail call
4967 // optimization.
4968 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00004969}
4970
Nate Begemanf15485a2006-03-27 01:32:24 +00004971void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00004972 DOUT << "Lowered selection DAG:\n";
4973 DEBUG(DAG.dump());
4974
Chris Lattneraf21d552005-10-10 16:47:10 +00004975 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004976 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004977
Dan Gohman417e11b2007-10-08 15:12:17 +00004978 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004979 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004980
Chris Lattner1c08c712005-01-07 07:47:53 +00004981 // Second step, hack on the DAG until it only uses operations and types that
4982 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00004983#if 0 // Enable this some day.
4984 DAG.LegalizeTypes();
4985 // Someday even later, enable a dag combine pass here.
4986#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00004987 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004988
Bill Wendling832171c2006-12-07 20:04:42 +00004989 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004990 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004991
Chris Lattneraf21d552005-10-10 16:47:10 +00004992 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004993 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004994
Dan Gohman417e11b2007-10-08 15:12:17 +00004995 DOUT << "Optimized legalized selection DAG:\n";
4996 DEBUG(DAG.dump());
4997
Evan Chenga9c20912006-01-21 02:32:06 +00004998 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004999
Chris Lattnera33ef482005-03-30 01:10:47 +00005000 // Third, instruction select all of the operations to machine code, adding the
5001 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00005002 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00005003
Bill Wendling832171c2006-12-07 20:04:42 +00005004 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005005 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005006}
Chris Lattner1c08c712005-01-07 07:47:53 +00005007
Nate Begemanf15485a2006-03-27 01:32:24 +00005008void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5009 FunctionLoweringInfo &FuncInfo) {
5010 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5011 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005012 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005013 CurDAG = &DAG;
5014
5015 // First step, lower LLVM code to some DAG. This DAG may use operations and
5016 // types that are not supported by the target.
5017 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5018
5019 // Second step, emit the lowered DAG as machine code.
5020 CodeGenAndEmitDAG(DAG);
5021 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005022
5023 DOUT << "Total amount of phi nodes to update: "
5024 << PHINodesToUpdate.size() << "\n";
5025 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5026 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5027 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005028
Chris Lattnera33ef482005-03-30 01:10:47 +00005029 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005030 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005031 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005032 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5033 MachineInstr *PHI = PHINodesToUpdate[i].first;
5034 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5035 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005036 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5037 false));
5038 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005039 }
5040 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005041 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005042
5043 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5044 // Lower header first, if it wasn't already lowered
5045 if (!BitTestCases[i].Emitted) {
5046 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5047 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005048 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005049 // Set the current basic block to the mbb we wish to insert the code into
5050 BB = BitTestCases[i].Parent;
5051 HSDL.setCurrentBasicBlock(BB);
5052 // Emit the code
5053 HSDL.visitBitTestHeader(BitTestCases[i]);
5054 HSDAG.setRoot(HSDL.getRoot());
5055 CodeGenAndEmitDAG(HSDAG);
5056 }
5057
5058 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5059 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5060 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005061 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005062 // Set the current basic block to the mbb we wish to insert the code into
5063 BB = BitTestCases[i].Cases[j].ThisBB;
5064 BSDL.setCurrentBasicBlock(BB);
5065 // Emit the code
5066 if (j+1 != ej)
5067 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5068 BitTestCases[i].Reg,
5069 BitTestCases[i].Cases[j]);
5070 else
5071 BSDL.visitBitTestCase(BitTestCases[i].Default,
5072 BitTestCases[i].Reg,
5073 BitTestCases[i].Cases[j]);
5074
5075
5076 BSDAG.setRoot(BSDL.getRoot());
5077 CodeGenAndEmitDAG(BSDAG);
5078 }
5079
5080 // Update PHI Nodes
5081 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5082 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5083 MachineBasicBlock *PHIBB = PHI->getParent();
5084 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5085 "This is not a machine PHI node that we are updating!");
5086 // This is "default" BB. We have two jumps to it. From "header" BB and
5087 // from last "case" BB.
5088 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005089 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5090 false));
5091 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5092 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5093 false));
5094 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5095 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005096 }
5097 // One of "cases" BB.
5098 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5099 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5100 if (cBB->succ_end() !=
5101 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005102 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5103 false));
5104 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005105 }
5106 }
5107 }
5108 }
5109
Nate Begeman9453eea2006-04-23 06:26:20 +00005110 // If the JumpTable record is filled in, then we need to emit a jump table.
5111 // Updating the PHI nodes is tricky in this case, since we need to determine
5112 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005113 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5114 // Lower header first, if it wasn't already lowered
5115 if (!JTCases[i].first.Emitted) {
5116 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5117 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005118 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005119 // Set the current basic block to the mbb we wish to insert the code into
5120 BB = JTCases[i].first.HeaderBB;
5121 HSDL.setCurrentBasicBlock(BB);
5122 // Emit the code
5123 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5124 HSDAG.setRoot(HSDL.getRoot());
5125 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005126 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005127
5128 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5129 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005130 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00005131 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005132 BB = JTCases[i].second.MBB;
5133 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005134 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005135 JSDL.visitJumpTable(JTCases[i].second);
5136 JSDAG.setRoot(JSDL.getRoot());
5137 CodeGenAndEmitDAG(JSDAG);
5138
Nate Begeman37efe672006-04-22 18:53:45 +00005139 // Update PHI Nodes
5140 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5141 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5142 MachineBasicBlock *PHIBB = PHI->getParent();
5143 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5144 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005145 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005146 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005147 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5148 false));
5149 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005150 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005151 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005152 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005153 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5154 false));
5155 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005156 }
5157 }
Nate Begeman37efe672006-04-22 18:53:45 +00005158 }
5159
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005160 // If the switch block involved a branch to one of the actual successors, we
5161 // need to update PHI nodes in that block.
5162 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5163 MachineInstr *PHI = PHINodesToUpdate[i].first;
5164 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5165 "This is not a machine PHI node that we are updating!");
5166 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005167 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5168 false));
5169 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005170 }
5171 }
5172
Nate Begemanf15485a2006-03-27 01:32:24 +00005173 // If we generated any switch lowering information, build and codegen any
5174 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005175 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005176 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005177 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005178 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005179
Nate Begemanf15485a2006-03-27 01:32:24 +00005180 // Set the current basic block to the mbb we wish to insert the code into
5181 BB = SwitchCases[i].ThisBB;
5182 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005183
Nate Begemanf15485a2006-03-27 01:32:24 +00005184 // Emit the code
5185 SDL.visitSwitchCase(SwitchCases[i]);
5186 SDAG.setRoot(SDL.getRoot());
5187 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005188
5189 // Handle any PHI nodes in successors of this chunk, as if we were coming
5190 // from the original BB before switch expansion. Note that PHI nodes can
5191 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5192 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005193 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005194 for (MachineBasicBlock::iterator Phi = BB->begin();
5195 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5196 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5197 for (unsigned pn = 0; ; ++pn) {
5198 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5199 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005200 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5201 second, false));
5202 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005203 break;
5204 }
5205 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005206 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005207
5208 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005209 if (BB == SwitchCases[i].FalseBB)
5210 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005211
5212 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005213 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005214 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005215 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005216 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005217 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005218}
Evan Chenga9c20912006-01-21 02:32:06 +00005219
Jim Laskey13ec7022006-08-01 14:21:23 +00005220
Evan Chenga9c20912006-01-21 02:32:06 +00005221//===----------------------------------------------------------------------===//
5222/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5223/// target node in the graph.
5224void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5225 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005226
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005227 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005228
5229 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005230 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005231 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005232 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005233
Jim Laskey9ff542f2006-08-01 18:29:48 +00005234 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005235 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005236
5237 if (ViewSUnitDAGs) SL->viewGraph();
5238
Evan Chengcccf1232006-02-04 06:49:00 +00005239 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005240}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005241
Chris Lattner03fc53c2006-03-06 00:22:00 +00005242
Jim Laskey9ff542f2006-08-01 18:29:48 +00005243HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5244 return new HazardRecognizer();
5245}
5246
Chris Lattner75548062006-10-11 03:58:02 +00005247//===----------------------------------------------------------------------===//
5248// Helper functions used by the generated instruction selector.
5249//===----------------------------------------------------------------------===//
5250// Calls to these methods are generated by tblgen.
5251
5252/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5253/// the dag combiner simplified the 255, we still want to match. RHS is the
5254/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5255/// specified in the .td file (e.g. 255).
5256bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005257 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005258 const APInt &ActualMask = RHS->getAPIntValue();
5259 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005260
5261 // If the actual mask exactly matches, success!
5262 if (ActualMask == DesiredMask)
5263 return true;
5264
5265 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005266 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005267 return false;
5268
5269 // Otherwise, the DAG Combiner may have proven that the value coming in is
5270 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005271 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005272 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005273 return true;
5274
5275 // TODO: check to see if missing bits are just not demanded.
5276
5277 // Otherwise, this pattern doesn't match.
5278 return false;
5279}
5280
5281/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5282/// the dag combiner simplified the 255, we still want to match. RHS is the
5283/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5284/// specified in the .td file (e.g. 255).
5285bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005286 int64_t DesiredMaskS) const {
5287 const APInt &ActualMask = RHS->getAPIntValue();
5288 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005289
5290 // If the actual mask exactly matches, success!
5291 if (ActualMask == DesiredMask)
5292 return true;
5293
5294 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005295 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005296 return false;
5297
5298 // Otherwise, the DAG Combiner may have proven that the value coming in is
5299 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005300 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005301
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005302 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005303 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005304
5305 // If all the missing bits in the or are already known to be set, match!
5306 if ((NeededMask & KnownOne) == NeededMask)
5307 return true;
5308
5309 // TODO: check to see if missing bits are just not demanded.
5310
5311 // Otherwise, this pattern doesn't match.
5312 return false;
5313}
5314
Jim Laskey9ff542f2006-08-01 18:29:48 +00005315
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005316/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5317/// by tblgen. Others should not call it.
5318void SelectionDAGISel::
5319SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5320 std::vector<SDOperand> InOps;
5321 std::swap(InOps, Ops);
5322
5323 Ops.push_back(InOps[0]); // input chain.
5324 Ops.push_back(InOps[1]); // input asm string.
5325
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005326 unsigned i = 2, e = InOps.size();
5327 if (InOps[e-1].getValueType() == MVT::Flag)
5328 --e; // Don't process a flag operand if it is here.
5329
5330 while (i != e) {
5331 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5332 if ((Flags & 7) != 4 /*MEM*/) {
5333 // Just skip over this operand, copying the operands verbatim.
5334 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5335 i += (Flags >> 3) + 1;
5336 } else {
5337 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5338 // Otherwise, this is a memory operand. Ask the target to select it.
5339 std::vector<SDOperand> SelOps;
5340 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005341 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005342 exit(1);
5343 }
5344
5345 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00005346 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005347 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005348 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005349 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5350 i += 2;
5351 }
5352 }
5353
5354 // Add the flag input back if present.
5355 if (e != InOps.size())
5356 Ops.push_back(InOps.back());
5357}
Devang Patel794fd752007-05-01 21:15:47 +00005358
Devang Patel19974732007-05-03 01:11:54 +00005359char SelectionDAGISel::ID = 0;