blob: 241ad7e8a951a8baddf9df34ab114bf493fc7e83 [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//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000077namespace {
Dan Gohman4a3f6c82008-05-06 01:53:16 +000078 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000080 ISHeuristic("pre-RA-sched",
Chris Lattner3700f902006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Chris Lattner5bab7852008-01-25 17:24:52 +000082 cl::desc("Instruction schedulers available (before register"
83 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +000084
Jim Laskey9ff542f2006-08-01 18:29:48 +000085 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000086 defaultListDAGScheduler("default", " Best scheduler for the target",
87 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000088} // namespace
89
Evan Cheng5c807602008-02-26 02:33:44 +000090namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +000091
Chris Lattnerf899fce2008-04-27 23:48:12 +000092/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
93/// MVT::ValueTypes that represent all the individual underlying
94/// non-aggregate types that comprise it.
95static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
96 SmallVectorImpl<MVT::ValueType> &ValueVTs) {
97 // Given a struct type, recursively traverse the elements.
98 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
99 for (StructType::element_iterator EI = STy->element_begin(),
100 EB = STy->element_end();
101 EI != EB; ++EI)
102 ComputeValueVTs(TLI, *EI, ValueVTs);
103 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000104 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000105 // Given an array type, recursively traverse the elements.
106 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
107 const Type *EltTy = ATy->getElementType();
108 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
109 ComputeValueVTs(TLI, EltTy, ValueVTs);
110 return;
111 }
112 // Base case: we can get an MVT::ValueType for this LLVM IR type.
113 ValueVTs.push_back(TLI.getValueType(Ty));
114}
Dan Gohman23ce5022008-04-25 18:27:55 +0000115
Chris Lattnerf899fce2008-04-27 23:48:12 +0000116namespace {
Dan Gohman0fe00902008-04-28 18:10:39 +0000117 /// RegsForValue - This struct represents the registers (physical or virtual)
118 /// that a particular set of values is assigned, and the type information about
119 /// the value. The most common situation is to represent one value at a time,
120 /// but struct or array values are handled element-wise as multiple values.
121 /// The splitting of aggregates is performed recursively, so that we never
122 /// have aggregate-typed registers. The values at this point do not necessarily
123 /// have legal types, so each value may require one or more registers of some
124 /// legal type.
125 ///
Chris Lattner95255282006-06-28 23:17:24 +0000126 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000127 /// TLI - The TargetLowering object.
Dan Gohman0fe00902008-04-28 18:10:39 +0000128 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000129 const TargetLowering *TLI;
130
Dan Gohman0fe00902008-04-28 18:10:39 +0000131 /// ValueVTs - The value types of the values, which may not be legal, and
132 /// may need be promoted or synthesized from one or more registers.
133 ///
134 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000135
Dan Gohman0fe00902008-04-28 18:10:39 +0000136 /// RegVTs - The value types of the registers. This is the same size as
137 /// ValueVTs and it records, for each value, what the type of the assigned
138 /// register or registers are. (Individual values are never synthesized
139 /// from more than one type of register.)
140 ///
141 /// With virtual registers, the contents of RegVTs is redundant with TLI's
142 /// getRegisterType member function, however when with physical registers
143 /// it is necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000144 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000145 SmallVector<MVT::ValueType, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000146
Dan Gohman0fe00902008-04-28 18:10:39 +0000147 /// Regs - This list holds the registers assigned to the values.
148 /// Each legal or promoted value requires one register, and each
149 /// expanded value requires multiple registers.
150 ///
151 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000152
Dan Gohman23ce5022008-04-25 18:27:55 +0000153 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000154
Dan Gohman23ce5022008-04-25 18:27:55 +0000155 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000156 const SmallVector<unsigned, 4> &regs,
Chris Lattner864635a2006-02-22 22:37:12 +0000157 MVT::ValueType regvt, MVT::ValueType valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000158 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000159 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000160 const SmallVector<unsigned, 4> &regs,
Dan Gohman23ce5022008-04-25 18:27:55 +0000161 const SmallVector<MVT::ValueType, 4> &regvts,
162 const SmallVector<MVT::ValueType, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000163 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000164 RegsForValue(const TargetLowering &tli,
165 unsigned Reg, const Type *Ty) : TLI(&tli) {
166 ComputeValueVTs(tli, Ty, ValueVTs);
167
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000168 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000169 MVT::ValueType ValueVT = ValueVTs[Value];
170 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
171 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
172 for (unsigned i = 0; i != NumRegs; ++i)
173 Regs.push_back(Reg + i);
174 RegVTs.push_back(RegisterVT);
175 Reg += NumRegs;
176 }
Chris Lattner864635a2006-02-22 22:37:12 +0000177 }
178
Chris Lattner41f62592008-04-29 04:29:54 +0000179 /// append - Add the specified values to this one.
180 void append(const RegsForValue &RHS) {
181 TLI = RHS.TLI;
182 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
183 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
184 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
185 }
186
187
Chris Lattner864635a2006-02-22 22:37:12 +0000188 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000189 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000190 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000191 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000192 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000193 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000194
195 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
196 /// specified value into the registers specified by this object. This uses
197 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000198 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000199 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000200 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000201
202 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
203 /// operand list. This adds the code marker and includes the number of
204 /// values added into it.
205 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000206 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000207 };
208}
Evan Cheng4ef10862006-01-23 07:01:07 +0000209
Chris Lattner1c08c712005-01-07 07:47:53 +0000210namespace llvm {
211 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000212 /// createDefaultScheduler - This creates an instruction scheduler appropriate
213 /// for the target.
214 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
215 SelectionDAG *DAG,
216 MachineBasicBlock *BB) {
217 TargetLowering &TLI = IS->getTargetLowering();
218
219 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
220 return createTDListDAGScheduler(IS, DAG, BB);
221 } else {
222 assert(TLI.getSchedulingPreference() ==
223 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
224 return createBURRListDAGScheduler(IS, DAG, BB);
225 }
226 }
227
228
229 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000230 /// FunctionLoweringInfo - This contains information that is global to a
231 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000232 class FunctionLoweringInfo {
233 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000234 TargetLowering &TLI;
235 Function &Fn;
236 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000237 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000238
239 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
240
241 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
242 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
243
244 /// ValueMap - Since we emit code for the function a basic block at a time,
245 /// we must remember which virtual registers hold the values for
246 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000247 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000248
249 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
250 /// the entry block. This allows the allocas to be efficiently referenced
251 /// anywhere in the function.
252 std::map<const AllocaInst*, int> StaticAllocaMap;
253
Duncan Sandsf4070822007-06-15 19:04:19 +0000254#ifndef NDEBUG
255 SmallSet<Instruction*, 8> CatchInfoLost;
256 SmallSet<Instruction*, 8> CatchInfoFound;
257#endif
258
Chris Lattner1c08c712005-01-07 07:47:53 +0000259 unsigned MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000260 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000261 }
Chris Lattner571e4342006-10-27 21:36:01 +0000262
263 /// isExportedInst - Return true if the specified value is an instruction
264 /// exported from its block.
265 bool isExportedInst(const Value *V) {
266 return ValueMap.count(V);
267 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000268
Chris Lattner3c384492006-03-16 19:51:18 +0000269 unsigned CreateRegForValue(const Value *V);
270
Chris Lattner1c08c712005-01-07 07:47:53 +0000271 unsigned InitializeRegForValue(const Value *V) {
272 unsigned &R = ValueMap[V];
273 assert(R == 0 && "Already initialized this value register!");
274 return R = CreateRegForValue(V);
275 }
276 };
277}
278
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000279/// isSelector - Return true if this instruction is a call to the
280/// eh.selector intrinsic.
281static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000282 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000283 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
284 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000285 return false;
286}
287
Chris Lattner1c08c712005-01-07 07:47:53 +0000288/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000289/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000290/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000291static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
292 if (isa<PHINode>(I)) return true;
293 BasicBlock *BB = I->getParent();
294 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000295 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000296 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000297 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000298 return true;
299 return false;
300}
301
Chris Lattnerbf209482005-10-30 19:42:35 +0000302/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000303/// entry block, return true. This includes arguments used by switches, since
304/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000305static bool isOnlyUsedInEntryBlock(Argument *A) {
306 BasicBlock *Entry = A->getParent()->begin();
307 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000308 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000309 return false; // Use not in entry block.
310 return true;
311}
312
Chris Lattner1c08c712005-01-07 07:47:53 +0000313FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000314 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000315 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000316
Chris Lattnerbf209482005-10-30 19:42:35 +0000317 // Create a vreg for each argument register that is not dead and is used
318 // outside of the entry block for the function.
319 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
320 AI != E; ++AI)
321 if (!isOnlyUsedInEntryBlock(AI))
322 InitializeRegForValue(AI);
323
Chris Lattner1c08c712005-01-07 07:47:53 +0000324 // Initialize the mapping of values to registers. This is only set up for
325 // instruction values that are used outside of the block that defines
326 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000327 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000328 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
329 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000330 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000331 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000332 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000333 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000334 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000335 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000336
Reid Spencerb83eb642006-10-20 07:07:24 +0000337 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000338 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000339 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000340 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000341 }
342
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000343 for (; BB != EB; ++BB)
344 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000345 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
346 if (!isa<AllocaInst>(I) ||
347 !StaticAllocaMap.count(cast<AllocaInst>(I)))
348 InitializeRegForValue(I);
349
350 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
351 // also creates the initial PHI MachineInstrs, though none of the input
352 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000353 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000354 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
355 MBBMap[BB] = MBB;
356 MF.getBasicBlockList().push_back(MBB);
357
358 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
359 // appropriate.
360 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000361 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
362 if (PN->use_empty()) continue;
363
364 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000365 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000366 unsigned PHIReg = ValueMap[PN];
367 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000368 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000369 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000370 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000371 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000372 }
373}
374
Chris Lattner3c384492006-03-16 19:51:18 +0000375/// CreateRegForValue - Allocate the appropriate number of virtual registers of
376/// the correctly promoted or expanded types. Assign these registers
377/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000378///
379/// In the case that the given value has struct or array type, this function
380/// will assign registers for each member or element.
381///
Chris Lattner3c384492006-03-16 19:51:18 +0000382unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000383 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000384 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000385
Dan Gohman23ce5022008-04-25 18:27:55 +0000386 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000387 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000388 MVT::ValueType ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000389 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000390
Chris Lattnerb606dba2008-04-28 06:44:42 +0000391 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000392 for (unsigned i = 0; i != NumRegs; ++i) {
393 unsigned R = MakeReg(RegisterVT);
394 if (!FirstReg) FirstReg = R;
395 }
396 }
397 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000398}
Chris Lattner1c08c712005-01-07 07:47:53 +0000399
400//===----------------------------------------------------------------------===//
401/// SelectionDAGLowering - This is the common target-independent lowering
402/// implementation that is parameterized by a TargetLowering object.
403/// Also, targets can overload any lowering method.
404///
405namespace llvm {
406class SelectionDAGLowering {
407 MachineBasicBlock *CurMBB;
408
Chris Lattner0da331f2007-02-04 01:31:47 +0000409 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000410
Chris Lattnerd3948112005-01-17 22:19:26 +0000411 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
412 /// them up and then emit token factor nodes when possible. This allows us to
413 /// get simple disambiguation between loads without worrying about alias
414 /// analysis.
415 std::vector<SDOperand> PendingLoads;
416
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000417 /// PendingExports - CopyToReg nodes that copy values to virtual registers
418 /// for export to other blocks need to be emitted before any terminator
419 /// instruction, but they have no other ordering requirements. We bunch them
420 /// up and the emit a single tokenfactor for them just before terminator
421 /// instructions.
422 std::vector<SDOperand> PendingExports;
423
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000424 /// Case - A struct to record the Value for a switch case, and the
425 /// case's target basic block.
426 struct Case {
427 Constant* Low;
428 Constant* High;
429 MachineBasicBlock* BB;
430
431 Case() : Low(0), High(0), BB(0) { }
432 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
433 Low(low), High(high), BB(bb) { }
434 uint64_t size() const {
435 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
436 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
437 return (rHigh - rLow + 1ULL);
438 }
439 };
440
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000441 struct CaseBits {
442 uint64_t Mask;
443 MachineBasicBlock* BB;
444 unsigned Bits;
445
446 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
447 Mask(mask), BB(bb), Bits(bits) { }
448 };
449
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000450 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000451 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000452 typedef CaseVector::iterator CaseItr;
453 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000454
455 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
456 /// of conditional branches.
457 struct CaseRec {
458 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
459 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
460
461 /// CaseBB - The MBB in which to emit the compare and branch
462 MachineBasicBlock *CaseBB;
463 /// LT, GE - If nonzero, we know the current case value must be less-than or
464 /// greater-than-or-equal-to these Constants.
465 Constant *LT;
466 Constant *GE;
467 /// Range - A pair of iterators representing the range of case values to be
468 /// processed at this point in the binary search tree.
469 CaseRange Range;
470 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000471
472 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000473
474 /// The comparison function for sorting the switch case values in the vector.
475 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000476 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000477 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000478 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
479 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
480 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
481 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000482 }
483 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000484
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000485 struct CaseBitsCmp {
486 bool operator () (const CaseBits& C1, const CaseBits& C2) {
487 return C1.Bits > C2.Bits;
488 }
489 };
490
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000491 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000492
Chris Lattner1c08c712005-01-07 07:47:53 +0000493public:
494 // TLI - This is information that describes the available target features we
495 // need for lowering. This indicates when operations are unavailable,
496 // implemented with a libcall, etc.
497 TargetLowering &TLI;
498 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000499 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000500 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000501
Nate Begemanf15485a2006-03-27 01:32:24 +0000502 /// SwitchCases - Vector of CaseBlock structures used to communicate
503 /// SwitchInst code generation information.
504 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000505 /// JTCases - Vector of JumpTable structures used to communicate
506 /// SwitchInst code generation information.
507 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000508 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000509
Chris Lattner1c08c712005-01-07 07:47:53 +0000510 /// FuncInfo - Information about the function as a whole.
511 ///
512 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000513
514 /// GCI - Garbage collection metadata for the function.
515 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000516
517 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000518 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000519 FunctionLoweringInfo &funcinfo,
520 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000521 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000522 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000523 }
524
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000525 /// getRoot - Return the current virtual root of the Selection DAG,
526 /// flushing any PendingLoad items. This must be done before emitting
527 /// a store or any other node that may need to be ordered after any
528 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000529 ///
530 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000531 if (PendingLoads.empty())
532 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000533
Chris Lattnerd3948112005-01-17 22:19:26 +0000534 if (PendingLoads.size() == 1) {
535 SDOperand Root = PendingLoads[0];
536 DAG.setRoot(Root);
537 PendingLoads.clear();
538 return Root;
539 }
540
541 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000542 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
543 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000544 PendingLoads.clear();
545 DAG.setRoot(Root);
546 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000547 }
548
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000549 /// getControlRoot - Similar to getRoot, but instead of flushing all the
550 /// PendingLoad items, flush all the PendingExports items. It is necessary
551 /// to do this before emitting a terminator instruction.
552 ///
553 SDOperand getControlRoot() {
554 SDOperand Root = DAG.getRoot();
555
556 if (PendingExports.empty())
557 return Root;
558
559 // Turn all of the CopyToReg chains into one factored node.
560 if (Root.getOpcode() != ISD::EntryToken) {
561 unsigned i = 0, e = PendingExports.size();
562 for (; i != e; ++i) {
563 assert(PendingExports[i].Val->getNumOperands() > 1);
564 if (PendingExports[i].Val->getOperand(0) == Root)
565 break; // Don't add the root if we already indirectly depend on it.
566 }
567
568 if (i == e)
569 PendingExports.push_back(Root);
570 }
571
572 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
573 &PendingExports[0],
574 PendingExports.size());
575 PendingExports.clear();
576 DAG.setRoot(Root);
577 return Root;
578 }
579
580 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000581
Chris Lattner1c08c712005-01-07 07:47:53 +0000582 void visit(Instruction &I) { visit(I.getOpcode(), I); }
583
584 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000585 // Note: this doesn't use InstVisitor, because it has to work with
586 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000587 switch (Opcode) {
588 default: assert(0 && "Unknown instruction type encountered!");
589 abort();
590 // Build the switch statement using the Instruction.def file.
591#define HANDLE_INST(NUM, OPCODE, CLASS) \
592 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
593#include "llvm/Instruction.def"
594 }
595 }
596
597 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
598
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000599 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000600 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000601 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000602
Chris Lattner199862b2006-03-16 19:57:50 +0000603 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000604
Chris Lattner0da331f2007-02-04 01:31:47 +0000605 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000606 SDOperand &N = NodeMap[V];
607 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000608 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000609 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000610
Evan Cheng5c807602008-02-26 02:33:44 +0000611 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000612 std::set<unsigned> &OutputRegs,
613 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000614
Chris Lattner571e4342006-10-27 21:36:01 +0000615 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
616 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
617 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000618 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000619 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000620 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000621 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000622
Chris Lattner1c08c712005-01-07 07:47:53 +0000623 // Terminator instructions.
624 void visitRet(ReturnInst &I);
625 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000626 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000627 void visitUnreachable(UnreachableInst &I) { /* noop */ }
628
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000629 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000630 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000631 CaseRecVector& WorkList,
632 Value* SV,
633 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000634 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000635 CaseRecVector& WorkList,
636 Value* SV,
637 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000638 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000639 CaseRecVector& WorkList,
640 Value* SV,
641 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000642 bool handleBitTestsSwitchCase(CaseRec& CR,
643 CaseRecVector& WorkList,
644 Value* SV,
645 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000646 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000647 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
648 void visitBitTestCase(MachineBasicBlock* NextMBB,
649 unsigned Reg,
650 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000651 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000652 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
653 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000654
Chris Lattner1c08c712005-01-07 07:47:53 +0000655 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000656 void visitInvoke(InvokeInst &I);
657 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000658
Dan Gohman7f321562007-06-25 16:23:39 +0000659 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000660 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000661 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000662 if (I.getType()->isFPOrFPVector())
663 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000664 else
Dan Gohman7f321562007-06-25 16:23:39 +0000665 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000666 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000667 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000668 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000669 if (I.getType()->isFPOrFPVector())
670 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000671 else
Dan Gohman7f321562007-06-25 16:23:39 +0000672 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000673 }
Dan Gohman7f321562007-06-25 16:23:39 +0000674 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
675 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
676 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
677 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
678 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
679 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
680 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
681 void visitOr (User &I) { visitBinary(I, ISD::OR); }
682 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000683 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000684 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
685 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000686 void visitICmp(User &I);
687 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000688 void visitVICmp(User &I);
689 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000690 // Visit the conversion instructions
691 void visitTrunc(User &I);
692 void visitZExt(User &I);
693 void visitSExt(User &I);
694 void visitFPTrunc(User &I);
695 void visitFPExt(User &I);
696 void visitFPToUI(User &I);
697 void visitFPToSI(User &I);
698 void visitUIToFP(User &I);
699 void visitSIToFP(User &I);
700 void visitPtrToInt(User &I);
701 void visitIntToPtr(User &I);
702 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000703
Chris Lattner2bbd8102006-03-29 00:11:43 +0000704 void visitExtractElement(User &I);
705 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000706 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000707
Chris Lattner1c08c712005-01-07 07:47:53 +0000708 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000709 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000710
711 void visitMalloc(MallocInst &I);
712 void visitFree(FreeInst &I);
713 void visitAlloca(AllocaInst &I);
714 void visitLoad(LoadInst &I);
715 void visitStore(StoreInst &I);
716 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
717 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000718 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000719 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000720 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000721
Chris Lattner1c08c712005-01-07 07:47:53 +0000722 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000723 void visitVAArg(VAArgInst &I);
724 void visitVAEnd(CallInst &I);
725 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000726
Dan Gohmanef5d1942008-03-11 21:11:25 +0000727 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000728
Chris Lattner1c08c712005-01-07 07:47:53 +0000729 void visitUserOp1(Instruction &I) {
730 assert(0 && "UserOp1 should not exist at instruction selection time!");
731 abort();
732 }
733 void visitUserOp2(Instruction &I) {
734 assert(0 && "UserOp2 should not exist at instruction selection time!");
735 abort();
736 }
Mon P Wang63307c32008-05-05 19:05:59 +0000737
738private:
739 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
740
Chris Lattner1c08c712005-01-07 07:47:53 +0000741};
742} // end namespace llvm
743
Dan Gohman6183f782007-07-05 20:12:34 +0000744
Duncan Sandsb988bac2008-02-11 20:58:28 +0000745/// getCopyFromParts - Create a value that contains the specified legal parts
746/// combined into the value they represent. If the parts combine to a type
747/// larger then ValueVT then AssertOp can be used to specify whether the extra
748/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000749/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000750static SDOperand getCopyFromParts(SelectionDAG &DAG,
751 const SDOperand *Parts,
752 unsigned NumParts,
753 MVT::ValueType PartVT,
754 MVT::ValueType ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000755 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000756 assert(NumParts > 0 && "No parts to assemble!");
757 TargetLowering &TLI = DAG.getTargetLoweringInfo();
758 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000759
Duncan Sands014e04a2008-02-12 20:46:31 +0000760 if (NumParts > 1) {
761 // Assemble the value from multiple parts.
762 if (!MVT::isVector(ValueVT)) {
763 unsigned PartBits = MVT::getSizeInBits(PartVT);
764 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000765
Duncan Sands014e04a2008-02-12 20:46:31 +0000766 // Assemble the power of 2 part.
767 unsigned RoundParts = NumParts & (NumParts - 1) ?
768 1 << Log2_32(NumParts) : NumParts;
769 unsigned RoundBits = PartBits * RoundParts;
770 MVT::ValueType RoundVT = RoundBits == ValueBits ?
771 ValueVT : MVT::getIntegerType(RoundBits);
772 SDOperand Lo, Hi;
773
774 if (RoundParts > 2) {
775 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
776 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
777 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
778 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000779 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000780 Lo = Parts[0];
781 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000782 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000783 if (TLI.isBigEndian())
784 std::swap(Lo, Hi);
785 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
786
787 if (RoundParts < NumParts) {
788 // Assemble the trailing non-power-of-2 part.
789 unsigned OddParts = NumParts - RoundParts;
790 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
791 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
792
793 // Combine the round and odd parts.
794 Lo = Val;
795 if (TLI.isBigEndian())
796 std::swap(Lo, Hi);
797 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
798 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
799 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
800 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
801 TLI.getShiftAmountTy()));
802 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
803 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
804 }
805 } else {
806 // Handle a multi-element vector.
807 MVT::ValueType IntermediateVT, RegisterVT;
808 unsigned NumIntermediates;
809 unsigned NumRegs =
810 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
811 RegisterVT);
812
813 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
814 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
815 assert(RegisterVT == Parts[0].getValueType() &&
816 "Part type doesn't match part!");
817
818 // Assemble the parts into intermediate operands.
819 SmallVector<SDOperand, 8> Ops(NumIntermediates);
820 if (NumIntermediates == NumParts) {
821 // If the register was not expanded, truncate or copy the value,
822 // as appropriate.
823 for (unsigned i = 0; i != NumParts; ++i)
824 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
825 PartVT, IntermediateVT);
826 } else if (NumParts > 0) {
827 // If the intermediate type was expanded, build the intermediate operands
828 // from the parts.
829 assert(NumParts % NumIntermediates == 0 &&
830 "Must expand into a divisible number of parts!");
831 unsigned Factor = NumParts / NumIntermediates;
832 for (unsigned i = 0; i != NumIntermediates; ++i)
833 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
834 PartVT, IntermediateVT);
835 }
836
837 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
838 // operands.
839 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
840 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
841 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000842 }
Dan Gohman6183f782007-07-05 20:12:34 +0000843 }
844
Duncan Sands014e04a2008-02-12 20:46:31 +0000845 // There is now one part, held in Val. Correct it to match ValueVT.
846 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000847
Duncan Sands014e04a2008-02-12 20:46:31 +0000848 if (PartVT == ValueVT)
849 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000850
Duncan Sands014e04a2008-02-12 20:46:31 +0000851 if (MVT::isVector(PartVT)) {
852 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
853 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000854 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000855
856 if (MVT::isVector(ValueVT)) {
857 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
858 MVT::getVectorNumElements(ValueVT) == 1 &&
859 "Only trivial scalar-to-vector conversions should get here!");
860 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
861 }
862
863 if (MVT::isInteger(PartVT) &&
864 MVT::isInteger(ValueVT)) {
865 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
866 // For a truncate, see if we have any information to
867 // indicate whether the truncated bits will always be
868 // zero or sign-extension.
869 if (AssertOp != ISD::DELETED_NODE)
870 Val = DAG.getNode(AssertOp, PartVT, Val,
871 DAG.getValueType(ValueVT));
872 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
873 } else {
874 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
875 }
876 }
877
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000878 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
879 if (ValueVT < Val.getValueType())
Chris Lattner4468c1f2008-03-09 09:38:46 +0000880 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000881 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000882 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000883 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
884 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000885
886 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
887 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
888
889 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000890 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000891}
892
Duncan Sandsb988bac2008-02-11 20:58:28 +0000893/// getCopyToParts - Create a series of nodes that contain the specified value
894/// split into legal parts. If the parts contain more bits than Val, then, for
895/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000896static void getCopyToParts(SelectionDAG &DAG,
897 SDOperand Val,
898 SDOperand *Parts,
899 unsigned NumParts,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000900 MVT::ValueType PartVT,
901 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000902 TargetLowering &TLI = DAG.getTargetLoweringInfo();
903 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohman6183f782007-07-05 20:12:34 +0000904 MVT::ValueType ValueVT = Val.getValueType();
Duncan Sands014e04a2008-02-12 20:46:31 +0000905 unsigned PartBits = MVT::getSizeInBits(PartVT);
906 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000907
Duncan Sands014e04a2008-02-12 20:46:31 +0000908 if (!NumParts)
909 return;
910
911 if (!MVT::isVector(ValueVT)) {
912 if (PartVT == ValueVT) {
913 assert(NumParts == 1 && "No-op copy with multiple parts!");
914 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000915 return;
916 }
917
Duncan Sands014e04a2008-02-12 20:46:31 +0000918 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
919 // If the parts cover more bits than the value has, promote the value.
920 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
921 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000922 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000923 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
924 ValueVT = MVT::getIntegerType(NumParts * PartBits);
925 Val = DAG.getNode(ExtendKind, ValueVT, Val);
926 } else {
927 assert(0 && "Unknown mismatch!");
928 }
929 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
930 // Different types of the same size.
931 assert(NumParts == 1 && PartVT != ValueVT);
932 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
933 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
934 // If the parts cover less bits than value has, truncate the value.
935 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
936 ValueVT = MVT::getIntegerType(NumParts * PartBits);
937 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000938 } else {
939 assert(0 && "Unknown mismatch!");
940 }
941 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000942
943 // The value may have changed - recompute ValueVT.
944 ValueVT = Val.getValueType();
945 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
946 "Failed to tile the value with PartVT!");
947
948 if (NumParts == 1) {
949 assert(PartVT == ValueVT && "Type conversion failed!");
950 Parts[0] = Val;
951 return;
952 }
953
954 // Expand the value into multiple parts.
955 if (NumParts & (NumParts - 1)) {
956 // The number of parts is not a power of 2. Split off and copy the tail.
957 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
958 "Do not know what to expand to!");
959 unsigned RoundParts = 1 << Log2_32(NumParts);
960 unsigned RoundBits = RoundParts * PartBits;
961 unsigned OddParts = NumParts - RoundParts;
962 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
963 DAG.getConstant(RoundBits,
964 TLI.getShiftAmountTy()));
965 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
966 if (TLI.isBigEndian())
967 // The odd parts were reversed by getCopyToParts - unreverse them.
968 std::reverse(Parts + RoundParts, Parts + NumParts);
969 NumParts = RoundParts;
970 ValueVT = MVT::getIntegerType(NumParts * PartBits);
971 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
972 }
973
974 // The number of parts is a power of 2. Repeatedly bisect the value using
975 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +0000976 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
977 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
978 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000979 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
980 for (unsigned i = 0; i < NumParts; i += StepSize) {
981 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands25eb0432008-03-12 20:30:08 +0000982 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
983 SDOperand &Part0 = Parts[i];
984 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +0000985
Duncan Sands25eb0432008-03-12 20:30:08 +0000986 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
987 DAG.getConstant(1, PtrVT));
988 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
989 DAG.getConstant(0, PtrVT));
990
991 if (ThisBits == PartBits && ThisVT != PartVT) {
992 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
993 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
994 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000995 }
996 }
997
998 if (TLI.isBigEndian())
999 std::reverse(Parts, Parts + NumParts);
1000
1001 return;
1002 }
1003
1004 // Vector ValueVT.
1005 if (NumParts == 1) {
1006 if (PartVT != ValueVT) {
1007 if (MVT::isVector(PartVT)) {
1008 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1009 } else {
1010 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
1011 MVT::getVectorNumElements(ValueVT) == 1 &&
1012 "Only trivial vector-to-scalar conversions should get here!");
1013 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1014 DAG.getConstant(0, PtrVT));
1015 }
1016 }
1017
Dan Gohman6183f782007-07-05 20:12:34 +00001018 Parts[0] = Val;
1019 return;
1020 }
1021
1022 // Handle a multi-element vector.
1023 MVT::ValueType IntermediateVT, RegisterVT;
1024 unsigned NumIntermediates;
1025 unsigned NumRegs =
1026 DAG.getTargetLoweringInfo()
1027 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1028 RegisterVT);
1029 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1030
1031 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1032 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1033
1034 // Split the vector into intermediate operands.
1035 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1036 for (unsigned i = 0; i != NumIntermediates; ++i)
1037 if (MVT::isVector(IntermediateVT))
1038 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1039 IntermediateVT, Val,
1040 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001041 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001042 else
1043 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1044 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001045 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001046
1047 // Split the intermediate operands into legal parts.
1048 if (NumParts == NumIntermediates) {
1049 // If the register was not expanded, promote or copy the value,
1050 // as appropriate.
1051 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001052 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001053 } else if (NumParts > 0) {
1054 // If the intermediate type was expanded, split each the value into
1055 // legal parts.
1056 assert(NumParts % NumIntermediates == 0 &&
1057 "Must expand into a divisible number of parts!");
1058 unsigned Factor = NumParts / NumIntermediates;
1059 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001060 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001061 }
1062}
1063
1064
Chris Lattner199862b2006-03-16 19:57:50 +00001065SDOperand SelectionDAGLowering::getValue(const Value *V) {
1066 SDOperand &N = NodeMap[V];
1067 if (N.Val) return N;
1068
Chris Lattner199862b2006-03-16 19:57:50 +00001069 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Chris Lattner6833b062008-04-28 07:16:35 +00001070 MVT::ValueType VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001071
1072 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1073 return N = DAG.getConstant(CI->getValue(), VT);
1074
1075 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001076 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001077
1078 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001079 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001080
1081 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1082 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1083
Chris Lattner6833b062008-04-28 07:16:35 +00001084 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1085 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001086
1087 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1088 visit(CE->getOpcode(), *CE);
1089 SDOperand N1 = NodeMap[V];
1090 assert(N1.Val && "visit didn't populate the ValueMap!");
1091 return N1;
1092 }
1093
Chris Lattner6833b062008-04-28 07:16:35 +00001094 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001095 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001096
Chris Lattner6833b062008-04-28 07:16:35 +00001097 // Now that we know the number and type of the elements, get that number of
1098 // elements into the Ops array based on what kind of constant it is.
1099 SmallVector<SDOperand, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001100 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1101 for (unsigned i = 0; i != NumElements; ++i)
1102 Ops.push_back(getValue(CP->getOperand(i)));
1103 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001104 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1105 "Unknown vector constant!");
1106 MVT::ValueType EltVT = TLI.getValueType(VecTy->getElementType());
1107
Chris Lattnerb606dba2008-04-28 06:44:42 +00001108 SDOperand Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001109 if (isa<UndefValue>(C))
1110 Op = DAG.getNode(ISD::UNDEF, EltVT);
1111 else if (MVT::isFloatingPoint(EltVT))
1112 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001113 else
Chris Lattner6833b062008-04-28 07:16:35 +00001114 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001115 Ops.assign(NumElements, Op);
1116 }
1117
1118 // Create a BUILD_VECTOR node.
1119 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001120 }
1121
Chris Lattnerb606dba2008-04-28 06:44:42 +00001122 // If this is a static alloca, generate it as the frameindex instead of
1123 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001124 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1125 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001126 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001127 if (SI != FuncInfo.StaticAllocaMap.end())
1128 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1129 }
1130
Chris Lattner251db182007-02-25 18:40:32 +00001131 unsigned InReg = FuncInfo.ValueMap[V];
1132 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001133
Chris Lattner6833b062008-04-28 07:16:35 +00001134 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001135 SDOperand Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001136 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001137}
1138
1139
Chris Lattner1c08c712005-01-07 07:47:53 +00001140void SelectionDAGLowering::visitRet(ReturnInst &I) {
1141 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001142 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001143 return;
1144 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001145
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001146 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001147 NewValues.push_back(getControlRoot());
1148 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001149 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001150 MVT::ValueType VT = RetOp.getValueType();
1151
Evan Cheng8e7d0562006-05-26 23:09:09 +00001152 // FIXME: C calling convention requires the return type to be promoted to
1153 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sandsb988bac2008-02-11 20:58:28 +00001154 if (MVT::isInteger(VT)) {
1155 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1156 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1157 VT = MinVT;
1158 }
1159
1160 unsigned NumParts = TLI.getNumRegisters(VT);
1161 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1162 SmallVector<SDOperand, 4> Parts(NumParts);
1163 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1164
1165 const Function *F = I.getParent()->getParent();
1166 if (F->paramHasAttr(0, ParamAttr::SExt))
1167 ExtendKind = ISD::SIGN_EXTEND;
1168 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1169 ExtendKind = ISD::ZERO_EXTEND;
1170
1171 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1172
1173 for (unsigned i = 0; i < NumParts; ++i) {
1174 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001175 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001176 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001177 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001178 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1179 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001180}
1181
Chris Lattner571e4342006-10-27 21:36:01 +00001182/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1183/// the current basic block, add it to ValueMap now so that we'll get a
1184/// CopyTo/FromReg.
1185void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1186 // No need to export constants.
1187 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1188
1189 // Already exported?
1190 if (FuncInfo.isExportedInst(V)) return;
1191
1192 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001193 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001194}
1195
Chris Lattner8c494ab2006-10-27 23:50:33 +00001196bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1197 const BasicBlock *FromBB) {
1198 // The operands of the setcc have to be in this block. We don't know
1199 // how to export them from some other block.
1200 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1201 // Can export from current BB.
1202 if (VI->getParent() == FromBB)
1203 return true;
1204
1205 // Is already exported, noop.
1206 return FuncInfo.isExportedInst(V);
1207 }
1208
1209 // If this is an argument, we can export it if the BB is the entry block or
1210 // if it is already exported.
1211 if (isa<Argument>(V)) {
1212 if (FromBB == &FromBB->getParent()->getEntryBlock())
1213 return true;
1214
1215 // Otherwise, can only export this if it is already exported.
1216 return FuncInfo.isExportedInst(V);
1217 }
1218
1219 // Otherwise, constants can always be exported.
1220 return true;
1221}
1222
Chris Lattner6a586c82006-10-29 21:01:20 +00001223static bool InBlock(const Value *V, const BasicBlock *BB) {
1224 if (const Instruction *I = dyn_cast<Instruction>(V))
1225 return I->getParent() == BB;
1226 return true;
1227}
1228
Chris Lattner571e4342006-10-27 21:36:01 +00001229/// FindMergedConditions - If Cond is an expression like
1230void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1231 MachineBasicBlock *TBB,
1232 MachineBasicBlock *FBB,
1233 MachineBasicBlock *CurBB,
1234 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001235 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001236 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001237
Reid Spencere4d87aa2006-12-23 06:05:41 +00001238 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1239 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001240 BOp->getParent() != CurBB->getBasicBlock() ||
1241 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1242 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001243 const BasicBlock *BB = CurBB->getBasicBlock();
1244
Reid Spencere4d87aa2006-12-23 06:05:41 +00001245 // If the leaf of the tree is a comparison, merge the condition into
1246 // the caseblock.
1247 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1248 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001249 // how to export them from some other block. If this is the first block
1250 // of the sequence, no exporting is needed.
1251 (CurBB == CurMBB ||
1252 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1253 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001254 BOp = cast<Instruction>(Cond);
1255 ISD::CondCode Condition;
1256 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1257 switch (IC->getPredicate()) {
1258 default: assert(0 && "Unknown icmp predicate opcode!");
1259 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1260 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1261 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1262 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1263 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1264 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1265 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1266 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1267 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1268 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1269 }
1270 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1271 ISD::CondCode FPC, FOC;
1272 switch (FC->getPredicate()) {
1273 default: assert(0 && "Unknown fcmp predicate opcode!");
1274 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1275 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1276 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1277 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1278 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1279 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1280 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001281 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1282 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001283 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1284 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1285 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1286 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1287 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1288 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1289 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1290 }
1291 if (FiniteOnlyFPMath())
1292 Condition = FOC;
1293 else
1294 Condition = FPC;
1295 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001296 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001297 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001298 }
1299
Chris Lattner571e4342006-10-27 21:36:01 +00001300 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001301 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001302 SwitchCases.push_back(CB);
1303 return;
1304 }
1305
1306 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001307 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001308 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001309 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001310 return;
1311 }
1312
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001313
1314 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001315 MachineFunction::iterator BBI = CurBB;
1316 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1317 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1318
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001319 if (Opc == Instruction::Or) {
1320 // Codegen X | Y as:
1321 // jmp_if_X TBB
1322 // jmp TmpBB
1323 // TmpBB:
1324 // jmp_if_Y TBB
1325 // jmp FBB
1326 //
Chris Lattner571e4342006-10-27 21:36:01 +00001327
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001328 // Emit the LHS condition.
1329 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1330
1331 // Emit the RHS condition into TmpBB.
1332 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1333 } else {
1334 assert(Opc == Instruction::And && "Unknown merge op!");
1335 // Codegen X & Y as:
1336 // jmp_if_X TmpBB
1337 // jmp FBB
1338 // TmpBB:
1339 // jmp_if_Y TBB
1340 // jmp FBB
1341 //
1342 // This requires creation of TmpBB after CurBB.
1343
1344 // Emit the LHS condition.
1345 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1346
1347 // Emit the RHS condition into TmpBB.
1348 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1349 }
Chris Lattner571e4342006-10-27 21:36:01 +00001350}
1351
Chris Lattnerdf19f272006-10-31 22:37:42 +00001352/// If the set of cases should be emitted as a series of branches, return true.
1353/// If we should emit this as a bunch of and/or'd together conditions, return
1354/// false.
1355static bool
1356ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1357 if (Cases.size() != 2) return true;
1358
Chris Lattner0ccb5002006-10-31 23:06:00 +00001359 // If this is two comparisons of the same values or'd or and'd together, they
1360 // will get folded into a single comparison, so don't emit two blocks.
1361 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1362 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1363 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1364 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1365 return false;
1366 }
1367
Chris Lattnerdf19f272006-10-31 22:37:42 +00001368 return true;
1369}
1370
Chris Lattner1c08c712005-01-07 07:47:53 +00001371void SelectionDAGLowering::visitBr(BranchInst &I) {
1372 // Update machine-CFG edges.
1373 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001374
1375 // Figure out which block is immediately after the current one.
1376 MachineBasicBlock *NextBlock = 0;
1377 MachineFunction::iterator BBI = CurMBB;
1378 if (++BBI != CurMBB->getParent()->end())
1379 NextBlock = BBI;
1380
1381 if (I.isUnconditional()) {
1382 // If this is not a fall-through branch, emit the branch.
1383 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001384 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001385 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001386
Chris Lattner57ab6592006-10-24 17:57:59 +00001387 // Update machine-CFG edges.
1388 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner57ab6592006-10-24 17:57:59 +00001389 return;
1390 }
1391
1392 // If this condition is one of the special cases we handle, do special stuff
1393 // now.
1394 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001395 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001396
1397 // If this is a series of conditions that are or'd or and'd together, emit
1398 // this as a sequence of branches instead of setcc's with and/or operations.
1399 // For example, instead of something like:
1400 // cmp A, B
1401 // C = seteq
1402 // cmp D, E
1403 // F = setle
1404 // or C, F
1405 // jnz foo
1406 // Emit:
1407 // cmp A, B
1408 // je foo
1409 // cmp D, E
1410 // jle foo
1411 //
1412 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1413 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001414 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001415 BOp->getOpcode() == Instruction::Or)) {
1416 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001417 // If the compares in later blocks need to use values not currently
1418 // exported from this block, export them now. This block should always
1419 // be the first entry.
1420 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1421
Chris Lattnerdf19f272006-10-31 22:37:42 +00001422 // Allow some cases to be rejected.
1423 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001424 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1425 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1426 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1427 }
1428
1429 // Emit the branch for this block.
1430 visitSwitchCase(SwitchCases[0]);
1431 SwitchCases.erase(SwitchCases.begin());
1432 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001433 }
1434
Chris Lattner0ccb5002006-10-31 23:06:00 +00001435 // Okay, we decided not to do this, remove any inserted MBB's and clear
1436 // SwitchCases.
1437 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1438 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1439
Chris Lattnerdf19f272006-10-31 22:37:42 +00001440 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001441 }
1442 }
Chris Lattner24525952006-10-24 18:07:37 +00001443
1444 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001445 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001446 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001447 // Use visitSwitchCase to actually insert the fast branch sequence for this
1448 // cond branch.
1449 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001450}
1451
Nate Begemanf15485a2006-03-27 01:32:24 +00001452/// visitSwitchCase - Emits the necessary code to represent a single node in
1453/// the binary search tree resulting from lowering a switch instruction.
1454void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001455 SDOperand Cond;
1456 SDOperand CondLHS = getValue(CB.CmpLHS);
1457
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001458 // Build the setcc now.
1459 if (CB.CmpMHS == NULL) {
1460 // Fold "(X == true)" to X and "(X == false)" to !X to
1461 // handle common cases produced by branch lowering.
1462 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1463 Cond = CondLHS;
1464 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1465 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1466 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1467 } else
1468 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1469 } else {
1470 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001471
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001472 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1473 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1474
1475 SDOperand CmpOp = getValue(CB.CmpMHS);
1476 MVT::ValueType VT = CmpOp.getValueType();
1477
1478 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1479 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1480 } else {
1481 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1482 Cond = DAG.getSetCC(MVT::i1, SUB,
1483 DAG.getConstant(High-Low, VT), ISD::SETULE);
1484 }
1485
1486 }
1487
Nate Begemanf15485a2006-03-27 01:32:24 +00001488 // Set NextBlock to be the MBB immediately after the current one, if any.
1489 // This is used to avoid emitting unnecessary branches to the next block.
1490 MachineBasicBlock *NextBlock = 0;
1491 MachineFunction::iterator BBI = CurMBB;
1492 if (++BBI != CurMBB->getParent()->end())
1493 NextBlock = BBI;
1494
1495 // If the lhs block is the next block, invert the condition so that we can
1496 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001497 if (CB.TrueBB == NextBlock) {
1498 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001499 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1500 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1501 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001502 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001503 DAG.getBasicBlock(CB.TrueBB));
1504 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001505 DAG.setRoot(BrCond);
1506 else
1507 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001508 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001509 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001510 CurMBB->addSuccessor(CB.TrueBB);
1511 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001512}
1513
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001514/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001515void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001516 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001517 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001518 MVT::ValueType PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001519 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001520 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1521 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1522 Table, Index));
1523 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001524}
1525
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001526/// visitJumpTableHeader - This function emits necessary code to produce index
1527/// in the JumpTable from switch case.
1528void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1529 SelectionDAGISel::JumpTableHeader &JTH) {
1530 // Subtract the lowest switch case value from the value being switched on
1531 // and conditional branch to default mbb if the result is greater than the
1532 // difference between smallest and largest cases.
1533 SDOperand SwitchOp = getValue(JTH.SValue);
1534 MVT::ValueType VT = SwitchOp.getValueType();
1535 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1536 DAG.getConstant(JTH.First, VT));
1537
1538 // The SDNode we just created, which holds the value being switched on
1539 // minus the the smallest case value, needs to be copied to a virtual
1540 // register so it can be used as an index into the jump table in a
1541 // subsequent basic block. This value may be smaller or larger than the
1542 // target's pointer type, and therefore require extension or truncating.
Dan Gohman7f321562007-06-25 16:23:39 +00001543 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001544 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1545 else
1546 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1547
1548 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001549 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001550 JT.Reg = JumpTableReg;
1551
1552 // Emit the range check for the jump table, and branch to the default
1553 // block for the switch statement if the value being switched on exceeds
1554 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001555 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001556 DAG.getConstant(JTH.Last-JTH.First,VT),
1557 ISD::SETUGT);
1558
1559 // Set NextBlock to be the MBB immediately after the current one, if any.
1560 // This is used to avoid emitting unnecessary branches to the next block.
1561 MachineBasicBlock *NextBlock = 0;
1562 MachineFunction::iterator BBI = CurMBB;
1563 if (++BBI != CurMBB->getParent()->end())
1564 NextBlock = BBI;
1565
1566 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1567 DAG.getBasicBlock(JT.Default));
1568
1569 if (JT.MBB == NextBlock)
1570 DAG.setRoot(BrCond);
1571 else
1572 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001573 DAG.getBasicBlock(JT.MBB)));
1574
1575 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001576}
1577
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001578/// visitBitTestHeader - This function emits necessary code to produce value
1579/// suitable for "bit tests"
1580void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1581 // Subtract the minimum value
1582 SDOperand SwitchOp = getValue(B.SValue);
1583 MVT::ValueType VT = SwitchOp.getValueType();
1584 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1585 DAG.getConstant(B.First, VT));
1586
1587 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001588 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001589 DAG.getConstant(B.Range, VT),
1590 ISD::SETUGT);
1591
1592 SDOperand ShiftOp;
Dan Gohman7f321562007-06-25 16:23:39 +00001593 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001594 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1595 else
1596 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1597
1598 // Make desired shift
1599 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1600 DAG.getConstant(1, TLI.getPointerTy()),
1601 ShiftOp);
1602
1603 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001604 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001605 B.Reg = SwitchReg;
1606
1607 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1608 DAG.getBasicBlock(B.Default));
1609
1610 // Set NextBlock to be the MBB immediately after the current one, if any.
1611 // This is used to avoid emitting unnecessary branches to the next block.
1612 MachineBasicBlock *NextBlock = 0;
1613 MachineFunction::iterator BBI = CurMBB;
1614 if (++BBI != CurMBB->getParent()->end())
1615 NextBlock = BBI;
1616
1617 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1618 if (MBB == NextBlock)
1619 DAG.setRoot(BrRange);
1620 else
1621 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1622 DAG.getBasicBlock(MBB)));
1623
1624 CurMBB->addSuccessor(B.Default);
1625 CurMBB->addSuccessor(MBB);
1626
1627 return;
1628}
1629
1630/// visitBitTestCase - this function produces one "bit test"
1631void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1632 unsigned Reg,
1633 SelectionDAGISel::BitTestCase &B) {
1634 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001635 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001636
1637 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1638 SwitchVal,
1639 DAG.getConstant(B.Mask,
1640 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001641 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001642 DAG.getConstant(0, TLI.getPointerTy()),
1643 ISD::SETNE);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001644 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001645 AndCmp, DAG.getBasicBlock(B.TargetBB));
1646
1647 // Set NextBlock to be the MBB immediately after the current one, if any.
1648 // This is used to avoid emitting unnecessary branches to the next block.
1649 MachineBasicBlock *NextBlock = 0;
1650 MachineFunction::iterator BBI = CurMBB;
1651 if (++BBI != CurMBB->getParent()->end())
1652 NextBlock = BBI;
1653
1654 if (NextMBB == NextBlock)
1655 DAG.setRoot(BrAnd);
1656 else
1657 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1658 DAG.getBasicBlock(NextMBB)));
1659
1660 CurMBB->addSuccessor(B.TargetBB);
1661 CurMBB->addSuccessor(NextMBB);
1662
1663 return;
1664}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001665
Jim Laskeyb180aa12007-02-21 22:53:45 +00001666void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1667 // Retrieve successors.
1668 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001669 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001670
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001671 if (isa<InlineAsm>(I.getCalledValue()))
1672 visitInlineAsm(&I);
1673 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001674 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001675
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001676 // If the value of the invoke is used outside of its defining block, make it
1677 // available as a virtual register.
1678 if (!I.use_empty()) {
1679 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1680 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001681 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001682 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001683
1684 // Drop into normal successor.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001685 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001686 DAG.getBasicBlock(Return)));
1687
1688 // Update successor info
1689 CurMBB->addSuccessor(Return);
1690 CurMBB->addSuccessor(LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001691}
1692
1693void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1694}
1695
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001696/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001697/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001698bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001699 CaseRecVector& WorkList,
1700 Value* SV,
1701 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001702 Case& BackCase = *(CR.Range.second-1);
1703
1704 // Size is the number of Cases represented by this range.
1705 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001706 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001707 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001708
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001709 // Get the MachineFunction which holds the current MBB. This is used when
1710 // inserting any additional MBBs necessary to represent the switch.
1711 MachineFunction *CurMF = CurMBB->getParent();
1712
1713 // Figure out which block is immediately after the current one.
1714 MachineBasicBlock *NextBlock = 0;
1715 MachineFunction::iterator BBI = CR.CaseBB;
1716
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001717 if (++BBI != CurMBB->getParent()->end())
1718 NextBlock = BBI;
1719
1720 // TODO: If any two of the cases has the same destination, and if one value
1721 // is the same as the other, but has one bit unset that the other has set,
1722 // use bit manipulation to do two compares at once. For example:
1723 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1724
1725 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001726 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001727 // The last case block won't fall through into 'NextBlock' if we emit the
1728 // branches in this order. See if rearranging a case value would help.
1729 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001730 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001731 std::swap(*I, BackCase);
1732 break;
1733 }
1734 }
1735 }
1736
1737 // Create a CaseBlock record representing a conditional branch to
1738 // the Case's target mbb if the value being switched on SV is equal
1739 // to C.
1740 MachineBasicBlock *CurBlock = CR.CaseBB;
1741 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1742 MachineBasicBlock *FallThrough;
1743 if (I != E-1) {
1744 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1745 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1746 } else {
1747 // If the last case doesn't match, go to the default block.
1748 FallThrough = Default;
1749 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001750
1751 Value *RHS, *LHS, *MHS;
1752 ISD::CondCode CC;
1753 if (I->High == I->Low) {
1754 // This is just small small case range :) containing exactly 1 case
1755 CC = ISD::SETEQ;
1756 LHS = SV; RHS = I->High; MHS = NULL;
1757 } else {
1758 CC = ISD::SETLE;
1759 LHS = I->Low; MHS = SV; RHS = I->High;
1760 }
1761 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1762 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001763
1764 // If emitting the first comparison, just call visitSwitchCase to emit the
1765 // code into the current block. Otherwise, push the CaseBlock onto the
1766 // vector to be later processed by SDISel, and insert the node's MBB
1767 // before the next MBB.
1768 if (CurBlock == CurMBB)
1769 visitSwitchCase(CB);
1770 else
1771 SwitchCases.push_back(CB);
1772
1773 CurBlock = FallThrough;
1774 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001775
1776 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001777}
1778
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001779static inline bool areJTsAllowed(const TargetLowering &TLI) {
1780 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1781 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1782}
1783
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001784/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001785bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001786 CaseRecVector& WorkList,
1787 Value* SV,
1788 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001789 Case& FrontCase = *CR.Range.first;
1790 Case& BackCase = *(CR.Range.second-1);
1791
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001792 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1793 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1794
1795 uint64_t TSize = 0;
1796 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1797 I!=E; ++I)
1798 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001799
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001800 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001801 return false;
1802
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001803 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1804 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001805 return false;
1806
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001807 DOUT << "Lowering jump table\n"
1808 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001809 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001810
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001811 // Get the MachineFunction which holds the current MBB. This is used when
1812 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001813 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001814
1815 // Figure out which block is immediately after the current one.
1816 MachineBasicBlock *NextBlock = 0;
1817 MachineFunction::iterator BBI = CR.CaseBB;
1818
1819 if (++BBI != CurMBB->getParent()->end())
1820 NextBlock = BBI;
1821
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001822 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1823
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001824 // Create a new basic block to hold the code for loading the address
1825 // of the jump table, and jumping to it. Update successor information;
1826 // we will either branch to the default case for the switch, or the jump
1827 // table.
1828 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1829 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1830 CR.CaseBB->addSuccessor(Default);
1831 CR.CaseBB->addSuccessor(JumpTableBB);
1832
1833 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001834 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001835 // a case statement, push the case's BB onto the vector, otherwise, push
1836 // the default BB.
1837 std::vector<MachineBasicBlock*> DestBBs;
1838 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001839 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1840 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1841 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1842
1843 if ((Low <= TEI) && (TEI <= High)) {
1844 DestBBs.push_back(I->BB);
1845 if (TEI==High)
1846 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001847 } else {
1848 DestBBs.push_back(Default);
1849 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001850 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001851
1852 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001853 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001854 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1855 E = DestBBs.end(); I != E; ++I) {
1856 if (!SuccsHandled[(*I)->getNumber()]) {
1857 SuccsHandled[(*I)->getNumber()] = true;
1858 JumpTableBB->addSuccessor(*I);
1859 }
1860 }
1861
1862 // Create a jump table index for this jump table, or return an existing
1863 // one.
1864 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1865
1866 // Set the jump table information so that we can codegen it as a second
1867 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001868 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001869 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1870 (CR.CaseBB == CurMBB));
1871 if (CR.CaseBB == CurMBB)
1872 visitJumpTableHeader(JT, JTH);
1873
1874 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001875
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001876 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001877}
1878
1879/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1880/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001881bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001882 CaseRecVector& WorkList,
1883 Value* SV,
1884 MachineBasicBlock* Default) {
1885 // Get the MachineFunction which holds the current MBB. This is used when
1886 // inserting any additional MBBs necessary to represent the switch.
1887 MachineFunction *CurMF = CurMBB->getParent();
1888
1889 // Figure out which block is immediately after the current one.
1890 MachineBasicBlock *NextBlock = 0;
1891 MachineFunction::iterator BBI = CR.CaseBB;
1892
1893 if (++BBI != CurMBB->getParent()->end())
1894 NextBlock = BBI;
1895
1896 Case& FrontCase = *CR.Range.first;
1897 Case& BackCase = *(CR.Range.second-1);
1898 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1899
1900 // Size is the number of Cases represented by this range.
1901 unsigned Size = CR.Range.second - CR.Range.first;
1902
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001903 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1904 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001905 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001906 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001907
1908 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1909 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001910 uint64_t TSize = 0;
1911 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1912 I!=E; ++I)
1913 TSize += I->size();
1914
1915 uint64_t LSize = FrontCase.size();
1916 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001917 DOUT << "Selecting best pivot: \n"
1918 << "First: " << First << ", Last: " << Last <<"\n"
1919 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001920 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001921 J!=E; ++I, ++J) {
1922 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1923 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001924 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001925 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1926 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001927 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001928 // Should always split in some non-trivial place
1929 DOUT <<"=>Step\n"
1930 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1931 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1932 << "Metric: " << Metric << "\n";
1933 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001934 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001935 FMetric = Metric;
1936 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001937 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001938
1939 LSize += J->size();
1940 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001941 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001942 if (areJTsAllowed(TLI)) {
1943 // If our case is dense we *really* should handle it earlier!
1944 assert((FMetric > 0) && "Should handle dense range earlier!");
1945 } else {
1946 Pivot = CR.Range.first + Size/2;
1947 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001948
1949 CaseRange LHSR(CR.Range.first, Pivot);
1950 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001951 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001952 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1953
1954 // We know that we branch to the LHS if the Value being switched on is
1955 // less than the Pivot value, C. We use this to optimize our binary
1956 // tree a bit, by recognizing that if SV is greater than or equal to the
1957 // LHS's Case Value, and that Case Value is exactly one less than the
1958 // Pivot's Value, then we can branch directly to the LHS's Target,
1959 // rather than creating a leaf node for it.
1960 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001961 LHSR.first->High == CR.GE &&
1962 cast<ConstantInt>(C)->getSExtValue() ==
1963 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1964 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001965 } else {
1966 TrueBB = new MachineBasicBlock(LLVMBB);
1967 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1968 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1969 }
1970
1971 // Similar to the optimization above, if the Value being switched on is
1972 // known to be less than the Constant CR.LT, and the current Case Value
1973 // is CR.LT - 1, then we can branch directly to the target block for
1974 // the current Case Value, rather than emitting a RHS leaf node for it.
1975 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001976 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1977 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1978 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001979 } else {
1980 FalseBB = new MachineBasicBlock(LLVMBB);
1981 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1982 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1983 }
1984
1985 // Create a CaseBlock record representing a conditional branch to
1986 // the LHS node if the value being switched on SV is less than C.
1987 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001988 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1989 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001990
1991 if (CR.CaseBB == CurMBB)
1992 visitSwitchCase(CB);
1993 else
1994 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001995
1996 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001997}
1998
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001999/// handleBitTestsSwitchCase - if current case range has few destination and
2000/// range span less, than machine word bitwidth, encode case range into series
2001/// of masks and emit bit tests with these masks.
2002bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2003 CaseRecVector& WorkList,
2004 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002005 MachineBasicBlock* Default){
Dan Gohmanb55757e2007-05-18 17:52:13 +00002006 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002007
2008 Case& FrontCase = *CR.Range.first;
2009 Case& BackCase = *(CR.Range.second-1);
2010
2011 // Get the MachineFunction which holds the current MBB. This is used when
2012 // inserting any additional MBBs necessary to represent the switch.
2013 MachineFunction *CurMF = CurMBB->getParent();
2014
2015 unsigned numCmps = 0;
2016 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2017 I!=E; ++I) {
2018 // Single case counts one, case range - two.
2019 if (I->Low == I->High)
2020 numCmps +=1;
2021 else
2022 numCmps +=2;
2023 }
2024
2025 // Count unique destinations
2026 SmallSet<MachineBasicBlock*, 4> Dests;
2027 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2028 Dests.insert(I->BB);
2029 if (Dests.size() > 3)
2030 // Don't bother the code below, if there are too much unique destinations
2031 return false;
2032 }
2033 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2034 << "Total number of comparisons: " << numCmps << "\n";
2035
2036 // Compute span of values.
2037 Constant* minValue = FrontCase.Low;
2038 Constant* maxValue = BackCase.High;
2039 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2040 cast<ConstantInt>(minValue)->getSExtValue();
2041 DOUT << "Compare range: " << range << "\n"
2042 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2043 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2044
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002045 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002046 (!(Dests.size() == 1 && numCmps >= 3) &&
2047 !(Dests.size() == 2 && numCmps >= 5) &&
2048 !(Dests.size() >= 3 && numCmps >= 6)))
2049 return false;
2050
2051 DOUT << "Emitting bit tests\n";
2052 int64_t lowBound = 0;
2053
2054 // Optimize the case where all the case values fit in a
2055 // word without having to subtract minValue. In this case,
2056 // we can optimize away the subtraction.
2057 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002058 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002059 range = cast<ConstantInt>(maxValue)->getSExtValue();
2060 } else {
2061 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2062 }
2063
2064 CaseBitsVector CasesBits;
2065 unsigned i, count = 0;
2066
2067 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2068 MachineBasicBlock* Dest = I->BB;
2069 for (i = 0; i < count; ++i)
2070 if (Dest == CasesBits[i].BB)
2071 break;
2072
2073 if (i == count) {
2074 assert((count < 3) && "Too much destinations to test!");
2075 CasesBits.push_back(CaseBits(0, Dest, 0));
2076 count++;
2077 }
2078
2079 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2080 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2081
2082 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002083 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002084 CasesBits[i].Bits++;
2085 }
2086
2087 }
2088 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2089
2090 SelectionDAGISel::BitTestInfo BTC;
2091
2092 // Figure out which block is immediately after the current one.
2093 MachineFunction::iterator BBI = CR.CaseBB;
2094 ++BBI;
2095
2096 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2097
2098 DOUT << "Cases:\n";
2099 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2100 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2101 << ", BB: " << CasesBits[i].BB << "\n";
2102
2103 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2104 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2105 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2106 CaseBB,
2107 CasesBits[i].BB));
2108 }
2109
2110 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002111 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002112 CR.CaseBB, Default, BTC);
2113
2114 if (CR.CaseBB == CurMBB)
2115 visitBitTestHeader(BTB);
2116
2117 BitTestCases.push_back(BTB);
2118
2119 return true;
2120}
2121
2122
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002123/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002124unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2125 const SwitchInst& SI) {
2126 unsigned numCmps = 0;
2127
2128 // Start with "simple" cases
2129 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2130 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2131 Cases.push_back(Case(SI.getSuccessorValue(i),
2132 SI.getSuccessorValue(i),
2133 SMBB));
2134 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002135 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002136
2137 // Merge case into clusters
2138 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002139 // Must recompute end() each iteration because it may be
2140 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002141 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002142 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2143 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2144 MachineBasicBlock* nextBB = J->BB;
2145 MachineBasicBlock* currentBB = I->BB;
2146
2147 // If the two neighboring cases go to the same destination, merge them
2148 // into a single case.
2149 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2150 I->High = J->High;
2151 J = Cases.erase(J);
2152 } else {
2153 I = J++;
2154 }
2155 }
2156
2157 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2158 if (I->Low != I->High)
2159 // A range counts double, since it requires two compares.
2160 ++numCmps;
2161 }
2162
2163 return numCmps;
2164}
2165
2166void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002167 // Figure out which block is immediately after the current one.
2168 MachineBasicBlock *NextBlock = 0;
2169 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002170
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002171 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002172
Nate Begemanf15485a2006-03-27 01:32:24 +00002173 // If there is only the default destination, branch to it if it is not the
2174 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002175 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002176 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002177
Nate Begemanf15485a2006-03-27 01:32:24 +00002178 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002179 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002180 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002181 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002182
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002183 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002184 return;
2185 }
2186
2187 // If there are any non-default case statements, create a vector of Cases
2188 // representing each one, and sort the vector so that we can efficiently
2189 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002190 CaseVector Cases;
2191 unsigned numCmps = Clusterify(Cases, SI);
2192 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2193 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002194
Nate Begemanf15485a2006-03-27 01:32:24 +00002195 // Get the Value to be switched on and default basic blocks, which will be
2196 // inserted into CaseBlock records, representing basic blocks in the binary
2197 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002198 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002199
Nate Begemanf15485a2006-03-27 01:32:24 +00002200 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002201 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002202 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2203
2204 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002205 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002206 CaseRec CR = WorkList.back();
2207 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002208
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002209 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2210 continue;
2211
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002212 // If the range has few cases (two or less) emit a series of specific
2213 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002214 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2215 continue;
2216
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002217 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002218 // target supports indirect branches, then emit a jump table rather than
2219 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002220 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2221 continue;
2222
2223 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2224 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2225 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002226 }
2227}
2228
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002229
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002230void SelectionDAGLowering::visitSub(User &I) {
2231 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002232 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002233 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002234 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2235 const VectorType *DestTy = cast<VectorType>(I.getType());
2236 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002237 if (ElTy->isFloatingPoint()) {
2238 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002239 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002240 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2241 if (CV == CNZ) {
2242 SDOperand Op2 = getValue(I.getOperand(1));
2243 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2244 return;
2245 }
Dan Gohman7f321562007-06-25 16:23:39 +00002246 }
2247 }
2248 }
2249 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002250 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002251 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002252 SDOperand Op2 = getValue(I.getOperand(1));
2253 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2254 return;
2255 }
Dan Gohman7f321562007-06-25 16:23:39 +00002256 }
2257
2258 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002259}
2260
Dan Gohman7f321562007-06-25 16:23:39 +00002261void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002262 SDOperand Op1 = getValue(I.getOperand(0));
2263 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002264
2265 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002266}
2267
Nate Begemane21ea612005-11-18 07:42:56 +00002268void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2269 SDOperand Op1 = getValue(I.getOperand(0));
2270 SDOperand Op2 = getValue(I.getOperand(1));
2271
Dan Gohman7f321562007-06-25 16:23:39 +00002272 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2273 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002274 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2275 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2276 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002277
Chris Lattner1c08c712005-01-07 07:47:53 +00002278 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2279}
2280
Reid Spencer45fb3f32006-11-20 01:22:35 +00002281void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002282 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2283 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2284 predicate = IC->getPredicate();
2285 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2286 predicate = ICmpInst::Predicate(IC->getPredicate());
2287 SDOperand Op1 = getValue(I.getOperand(0));
2288 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002289 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002290 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002291 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2292 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2293 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2294 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2295 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2296 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2297 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2298 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2299 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2300 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2301 default:
2302 assert(!"Invalid ICmp predicate value");
2303 Opcode = ISD::SETEQ;
2304 break;
2305 }
2306 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2307}
2308
2309void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002310 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2311 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2312 predicate = FC->getPredicate();
2313 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2314 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002315 SDOperand Op1 = getValue(I.getOperand(0));
2316 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002317 ISD::CondCode Condition, FOC, FPC;
2318 switch (predicate) {
2319 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2320 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2321 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2322 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2323 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2324 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2325 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002326 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2327 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002328 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2329 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2330 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2331 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2332 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2333 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2334 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2335 default:
2336 assert(!"Invalid FCmp predicate value");
2337 FOC = FPC = ISD::SETFALSE;
2338 break;
2339 }
2340 if (FiniteOnlyFPMath())
2341 Condition = FOC;
2342 else
2343 Condition = FPC;
2344 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002345}
2346
Nate Begemanb43e9c12008-05-12 19:40:03 +00002347void SelectionDAGLowering::visitVICmp(User &I) {
2348 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2349 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2350 predicate = IC->getPredicate();
2351 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2352 predicate = ICmpInst::Predicate(IC->getPredicate());
2353 SDOperand Op1 = getValue(I.getOperand(0));
2354 SDOperand Op2 = getValue(I.getOperand(1));
2355 ISD::CondCode Opcode;
2356 switch (predicate) {
2357 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2358 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2359 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2360 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2361 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2362 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2363 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2364 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2365 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2366 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2367 default:
2368 assert(!"Invalid ICmp predicate value");
2369 Opcode = ISD::SETEQ;
2370 break;
2371 }
2372 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2373}
2374
2375void SelectionDAGLowering::visitVFCmp(User &I) {
2376 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2377 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2378 predicate = FC->getPredicate();
2379 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2380 predicate = FCmpInst::Predicate(FC->getPredicate());
2381 SDOperand Op1 = getValue(I.getOperand(0));
2382 SDOperand Op2 = getValue(I.getOperand(1));
2383 ISD::CondCode Condition, FOC, FPC;
2384 switch (predicate) {
2385 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2386 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2387 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2388 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2389 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2390 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2391 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2392 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2393 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2394 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2395 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2396 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2397 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2398 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2399 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2400 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2401 default:
2402 assert(!"Invalid VFCmp predicate value");
2403 FOC = FPC = ISD::SETFALSE;
2404 break;
2405 }
2406 if (FiniteOnlyFPMath())
2407 Condition = FOC;
2408 else
2409 Condition = FPC;
2410
2411 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2412
2413 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2414}
2415
Chris Lattner1c08c712005-01-07 07:47:53 +00002416void SelectionDAGLowering::visitSelect(User &I) {
2417 SDOperand Cond = getValue(I.getOperand(0));
2418 SDOperand TrueVal = getValue(I.getOperand(1));
2419 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002420 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2421 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002422}
2423
Reid Spencer3da59db2006-11-27 01:05:10 +00002424
2425void SelectionDAGLowering::visitTrunc(User &I) {
2426 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2427 SDOperand N = getValue(I.getOperand(0));
2428 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2429 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2430}
2431
2432void SelectionDAGLowering::visitZExt(User &I) {
2433 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2434 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2435 SDOperand N = getValue(I.getOperand(0));
2436 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2437 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2438}
2439
2440void SelectionDAGLowering::visitSExt(User &I) {
2441 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2442 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2443 SDOperand N = getValue(I.getOperand(0));
2444 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2445 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2446}
2447
2448void SelectionDAGLowering::visitFPTrunc(User &I) {
2449 // FPTrunc is never a no-op cast, no need to check
2450 SDOperand N = getValue(I.getOperand(0));
2451 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002452 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002453}
2454
2455void SelectionDAGLowering::visitFPExt(User &I){
2456 // FPTrunc is never a no-op cast, no need to check
2457 SDOperand N = getValue(I.getOperand(0));
2458 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2459 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2460}
2461
2462void SelectionDAGLowering::visitFPToUI(User &I) {
2463 // FPToUI is never a no-op cast, no need to check
2464 SDOperand N = getValue(I.getOperand(0));
2465 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2466 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2467}
2468
2469void SelectionDAGLowering::visitFPToSI(User &I) {
2470 // FPToSI is never a no-op cast, no need to check
2471 SDOperand N = getValue(I.getOperand(0));
2472 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2473 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2474}
2475
2476void SelectionDAGLowering::visitUIToFP(User &I) {
2477 // UIToFP is never a no-op cast, no need to check
2478 SDOperand N = getValue(I.getOperand(0));
2479 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2480 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2481}
2482
2483void SelectionDAGLowering::visitSIToFP(User &I){
2484 // UIToFP is never a no-op cast, no need to check
2485 SDOperand N = getValue(I.getOperand(0));
2486 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2487 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2488}
2489
2490void SelectionDAGLowering::visitPtrToInt(User &I) {
2491 // What to do depends on the size of the integer and the size of the pointer.
2492 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002493 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002494 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002495 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002496 SDOperand Result;
2497 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2498 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2499 else
2500 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2501 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2502 setValue(&I, Result);
2503}
Chris Lattner1c08c712005-01-07 07:47:53 +00002504
Reid Spencer3da59db2006-11-27 01:05:10 +00002505void SelectionDAGLowering::visitIntToPtr(User &I) {
2506 // What to do depends on the size of the integer and the size of the pointer.
2507 // We can either truncate, zero extend, or no-op, accordingly.
2508 SDOperand N = getValue(I.getOperand(0));
2509 MVT::ValueType SrcVT = N.getValueType();
2510 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2511 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2512 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2513 else
2514 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2515 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2516}
2517
2518void SelectionDAGLowering::visitBitCast(User &I) {
2519 SDOperand N = getValue(I.getOperand(0));
2520 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002521
2522 // BitCast assures us that source and destination are the same size so this
2523 // is either a BIT_CONVERT or a no-op.
2524 if (DestVT != N.getValueType())
2525 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2526 else
2527 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002528}
2529
Chris Lattner2bbd8102006-03-29 00:11:43 +00002530void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002531 SDOperand InVec = getValue(I.getOperand(0));
2532 SDOperand InVal = getValue(I.getOperand(1));
2533 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2534 getValue(I.getOperand(2)));
2535
Dan Gohman7f321562007-06-25 16:23:39 +00002536 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2537 TLI.getValueType(I.getType()),
2538 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002539}
2540
Chris Lattner2bbd8102006-03-29 00:11:43 +00002541void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002542 SDOperand InVec = getValue(I.getOperand(0));
2543 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2544 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002545 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002546 TLI.getValueType(I.getType()), InVec, InIdx));
2547}
Chris Lattnerc7029802006-03-18 01:44:44 +00002548
Chris Lattner3e104b12006-04-08 04:15:24 +00002549void SelectionDAGLowering::visitShuffleVector(User &I) {
2550 SDOperand V1 = getValue(I.getOperand(0));
2551 SDOperand V2 = getValue(I.getOperand(1));
2552 SDOperand Mask = getValue(I.getOperand(2));
2553
Dan Gohman7f321562007-06-25 16:23:39 +00002554 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2555 TLI.getValueType(I.getType()),
2556 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002557}
2558
2559
Chris Lattner1c08c712005-01-07 07:47:53 +00002560void SelectionDAGLowering::visitGetElementPtr(User &I) {
2561 SDOperand N = getValue(I.getOperand(0));
2562 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002563
2564 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2565 OI != E; ++OI) {
2566 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002567 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002568 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002569 if (Field) {
2570 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002571 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002572 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002573 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002574 }
2575 Ty = StTy->getElementType(Field);
2576 } else {
2577 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002578
Chris Lattner7c0104b2005-11-09 04:45:33 +00002579 // If this is a constant subscript, handle it quickly.
2580 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002581 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002582 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002583 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002584 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2585 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002586 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002587 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002588
2589 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002590 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002591 SDOperand IdxN = getValue(Idx);
2592
2593 // If the index is smaller or larger than intptr_t, truncate or extend
2594 // it.
2595 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002596 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002597 } else if (IdxN.getValueType() > N.getValueType())
2598 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2599
2600 // If this is a multiply by a power of two, turn it into a shl
2601 // immediately. This is a very common case.
2602 if (isPowerOf2_64(ElementSize)) {
2603 unsigned Amt = Log2_64(ElementSize);
2604 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002605 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002606 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2607 continue;
2608 }
2609
Chris Lattner0bd48932008-01-17 07:00:52 +00002610 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002611 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2612 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002613 }
2614 }
2615 setValue(&I, N);
2616}
2617
2618void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2619 // If this is a fixed sized alloca in the entry block of the function,
2620 // allocate it statically on the stack.
2621 if (FuncInfo.StaticAllocaMap.count(&I))
2622 return; // getValue will auto-populate this.
2623
2624 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002625 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002626 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002627 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002628 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002629
2630 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002631 MVT::ValueType IntPtr = TLI.getPointerTy();
2632 if (IntPtr < AllocSize.getValueType())
2633 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2634 else if (IntPtr > AllocSize.getValueType())
2635 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002636
Chris Lattner68cd65e2005-01-22 23:04:37 +00002637 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002638 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002639
Evan Cheng45157792007-08-16 23:46:29 +00002640 // Handle alignment. If the requested alignment is less than or equal to
2641 // the stack alignment, ignore it. If the size is greater than or equal to
2642 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002643 unsigned StackAlign =
2644 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002645 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002646 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002647
2648 // Round the size of the allocation up to the stack alignment size
2649 // by add SA-1 to the size.
2650 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002651 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002652 // Mask out the low bits for alignment purposes.
2653 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002654 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002655
Chris Lattner0bd48932008-01-17 07:00:52 +00002656 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002657 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2658 MVT::Other);
2659 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002660 setValue(&I, DSA);
2661 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002662
2663 // Inform the Frame Information that we have just allocated a variable-sized
2664 // object.
2665 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2666}
2667
Chris Lattner1c08c712005-01-07 07:47:53 +00002668void SelectionDAGLowering::visitLoad(LoadInst &I) {
2669 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002670
Chris Lattnerd3948112005-01-17 22:19:26 +00002671 SDOperand Root;
2672 if (I.isVolatile())
2673 Root = getRoot();
2674 else {
2675 // Do not serialize non-volatile loads against each other.
2676 Root = DAG.getRoot();
2677 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002678
Evan Cheng466685d2006-10-09 20:57:25 +00002679 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002680 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002681}
2682
2683SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002684 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002685 bool isVolatile,
2686 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002687 SDOperand L =
2688 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2689 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002690
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002691 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002692 DAG.setRoot(L.getValue(1));
2693 else
2694 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002695
2696 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002697}
2698
2699
2700void SelectionDAGLowering::visitStore(StoreInst &I) {
2701 Value *SrcV = I.getOperand(0);
2702 SDOperand Src = getValue(SrcV);
2703 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002704 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002705 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002706}
2707
Chris Lattner0eade312006-03-24 02:22:33 +00002708/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2709/// node.
2710void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2711 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002712 bool HasChain = !I.doesNotAccessMemory();
2713 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2714
Chris Lattner0eade312006-03-24 02:22:33 +00002715 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002716 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002717 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2718 if (OnlyLoad) {
2719 // We don't need to serialize loads against other loads.
2720 Ops.push_back(DAG.getRoot());
2721 } else {
2722 Ops.push_back(getRoot());
2723 }
2724 }
Chris Lattner0eade312006-03-24 02:22:33 +00002725
2726 // Add the intrinsic ID as an integer operand.
2727 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2728
2729 // Add all operands of the call to the operand list.
2730 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2731 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002732 assert(TLI.isTypeLegal(Op.getValueType()) &&
2733 "Intrinsic uses a non-legal type?");
2734 Ops.push_back(Op);
2735 }
2736
2737 std::vector<MVT::ValueType> VTs;
2738 if (I.getType() != Type::VoidTy) {
2739 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00002740 if (MVT::isVector(VT)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002741 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002742 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2743
2744 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2745 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2746 }
2747
2748 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2749 VTs.push_back(VT);
2750 }
2751 if (HasChain)
2752 VTs.push_back(MVT::Other);
2753
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002754 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2755
Chris Lattner0eade312006-03-24 02:22:33 +00002756 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002757 SDOperand Result;
2758 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002759 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2760 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002761 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002762 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2763 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002764 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002765 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2766 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002767
Chris Lattnere58a7802006-04-02 03:41:14 +00002768 if (HasChain) {
2769 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2770 if (OnlyLoad)
2771 PendingLoads.push_back(Chain);
2772 else
2773 DAG.setRoot(Chain);
2774 }
Chris Lattner0eade312006-03-24 02:22:33 +00002775 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002776 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohman7f321562007-06-25 16:23:39 +00002777 MVT::ValueType VT = TLI.getValueType(PTy);
2778 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002779 }
2780 setValue(&I, Result);
2781 }
2782}
2783
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002784/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002785static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00002786 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002787 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00002788 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002789 "TypeInfo must be a global variable or NULL");
2790 return GV;
2791}
2792
Duncan Sandsf4070822007-06-15 19:04:19 +00002793/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002794/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002795static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2796 MachineBasicBlock *MBB) {
2797 // Inform the MachineModuleInfo of the personality for this landing pad.
2798 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2799 assert(CE->getOpcode() == Instruction::BitCast &&
2800 isa<Function>(CE->getOperand(0)) &&
2801 "Personality should be a function");
2802 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2803
2804 // Gather all the type infos for this landing pad and pass them along to
2805 // MachineModuleInfo.
2806 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002807 unsigned N = I.getNumOperands();
2808
2809 for (unsigned i = N - 1; i > 2; --i) {
2810 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2811 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002812 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002813 assert (FirstCatch <= N && "Invalid filter length");
2814
2815 if (FirstCatch < N) {
2816 TyInfo.reserve(N - FirstCatch);
2817 for (unsigned j = FirstCatch; j < N; ++j)
2818 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2819 MMI->addCatchTypeInfo(MBB, TyInfo);
2820 TyInfo.clear();
2821 }
2822
Duncan Sands6590b042007-08-27 15:47:50 +00002823 if (!FilterLength) {
2824 // Cleanup.
2825 MMI->addCleanup(MBB);
2826 } else {
2827 // Filter.
2828 TyInfo.reserve(FilterLength - 1);
2829 for (unsigned j = i + 1; j < FirstCatch; ++j)
2830 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2831 MMI->addFilterTypeInfo(MBB, TyInfo);
2832 TyInfo.clear();
2833 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002834
2835 N = i;
2836 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002837 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002838
2839 if (N > 3) {
2840 TyInfo.reserve(N - 3);
2841 for (unsigned j = 3; j < N; ++j)
2842 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002843 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002844 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002845}
2846
Mon P Wang63307c32008-05-05 19:05:59 +00002847
2848/// Inlined utility function to implement binary input atomic intrinsics for
2849// visitIntrinsicCall: I is a call instruction
2850// Op is the associated NodeType for I
2851const char *
2852SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2853 SDOperand Root = getRoot();
2854 SDOperand O2 = getValue(I.getOperand(2));
2855 SDOperand L = DAG.getAtomic(Op, Root,
2856 getValue(I.getOperand(1)),
2857 O2, O2.getValueType());
2858 setValue(&I, L);
2859 DAG.setRoot(L.getValue(1));
2860 return 0;
2861}
2862
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002863/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2864/// we want to emit this as a call to a named external function, return the name
2865/// otherwise lower it and return null.
2866const char *
2867SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2868 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002869 default:
2870 // By default, turn this into a target intrinsic node.
2871 visitTargetIntrinsic(I, Intrinsic);
2872 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002873 case Intrinsic::vastart: visitVAStart(I); return 0;
2874 case Intrinsic::vaend: visitVAEnd(I); return 0;
2875 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002876 case Intrinsic::returnaddress:
2877 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2878 getValue(I.getOperand(1))));
2879 return 0;
2880 case Intrinsic::frameaddress:
2881 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2882 getValue(I.getOperand(1))));
2883 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002884 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002885 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002886 break;
2887 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002888 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002889 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002890 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002891 case Intrinsic::memcpy_i64: {
2892 SDOperand Op1 = getValue(I.getOperand(1));
2893 SDOperand Op2 = getValue(I.getOperand(2));
2894 SDOperand Op3 = getValue(I.getOperand(3));
2895 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2896 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2897 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002898 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002899 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002900 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002901 case Intrinsic::memset_i64: {
2902 SDOperand Op1 = getValue(I.getOperand(1));
2903 SDOperand Op2 = getValue(I.getOperand(2));
2904 SDOperand Op3 = getValue(I.getOperand(3));
2905 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2906 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2907 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002908 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002909 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002910 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002911 case Intrinsic::memmove_i64: {
2912 SDOperand Op1 = getValue(I.getOperand(1));
2913 SDOperand Op2 = getValue(I.getOperand(2));
2914 SDOperand Op3 = getValue(I.getOperand(3));
2915 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2916
2917 // If the source and destination are known to not be aliases, we can
2918 // lower memmove as memcpy.
2919 uint64_t Size = -1ULL;
2920 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2921 Size = C->getValue();
2922 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2923 AliasAnalysis::NoAlias) {
2924 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2925 I.getOperand(1), 0, I.getOperand(2), 0));
2926 return 0;
2927 }
2928
2929 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2930 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002931 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002932 }
Chris Lattner86cb6432005-12-13 17:40:33 +00002933 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002934 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002935 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002936 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002937 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002938
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002939 Ops[0] = getRoot();
2940 Ops[1] = getValue(SPI.getLineValue());
2941 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002942
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002943 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002944 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002945 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2946
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002947 Ops[3] = DAG.getString(CompileUnit->getFileName());
2948 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002949
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002950 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002951 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002952
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002953 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002954 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002955 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002956 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002957 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002958 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2959 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002960 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00002961 DAG.getConstant(LabelID, MVT::i32),
2962 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002963 }
2964
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002965 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002966 }
2967 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002968 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002969 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002970 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2971 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00002972 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2973 DAG.getConstant(LabelID, MVT::i32),
2974 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002975 }
2976
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002977 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002978 }
2979 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002980 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002981 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002982 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002983 Value *SP = FSI.getSubprogram();
2984 if (SP && MMI->Verify(SP)) {
2985 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2986 // what (most?) gdb expects.
2987 DebugInfoDesc *DD = MMI->getDescFor(SP);
2988 assert(DD && "Not a debug information descriptor");
2989 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2990 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2991 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2992 CompileUnit->getFileName());
2993 // Record the source line but does create a label. It will be emitted
2994 // at asm emission time.
2995 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00002996 }
2997
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002998 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002999 }
3000 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003001 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003002 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003003 Value *Variable = DI.getVariable();
3004 if (MMI && Variable && MMI->Verify(Variable))
3005 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3006 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003007 return 0;
3008 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003009
Jim Laskeyb180aa12007-02-21 22:53:45 +00003010 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003011 if (!CurMBB->isLandingPad()) {
3012 // FIXME: Mark exception register as live in. Hack for PR1508.
3013 unsigned Reg = TLI.getExceptionAddressRegister();
3014 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003015 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003016 // Insert the EXCEPTIONADDR instruction.
3017 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3018 SDOperand Ops[1];
3019 Ops[0] = DAG.getRoot();
3020 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3021 setValue(&I, Op);
3022 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003023 return 0;
3024 }
3025
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003026 case Intrinsic::eh_selector_i32:
3027 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003028 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003029 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3030 MVT::i32 : MVT::i64);
3031
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003032 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003033 if (CurMBB->isLandingPad())
3034 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003035 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003036#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003037 FuncInfo.CatchInfoLost.insert(&I);
3038#endif
Duncan Sands90291952007-07-06 09:18:59 +00003039 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3040 unsigned Reg = TLI.getExceptionSelectorRegister();
3041 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003042 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003043
3044 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003045 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00003046 SDOperand Ops[2];
3047 Ops[0] = getValue(I.getOperand(1));
3048 Ops[1] = getRoot();
3049 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3050 setValue(&I, Op);
3051 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003052 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003053 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003054 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003055
3056 return 0;
3057 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003058
3059 case Intrinsic::eh_typeid_for_i32:
3060 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003061 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003062 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3063 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003064
Jim Laskey735b6f82007-02-22 15:38:06 +00003065 if (MMI) {
3066 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003067 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003068
Jim Laskey735b6f82007-02-22 15:38:06 +00003069 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003070 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003071 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003072 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003073 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003074 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003075
3076 return 0;
3077 }
3078
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003079 case Intrinsic::eh_return: {
3080 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3081
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003082 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003083 MMI->setCallsEHReturn(true);
3084 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3085 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003086 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003087 getValue(I.getOperand(1)),
3088 getValue(I.getOperand(2))));
3089 } else {
3090 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3091 }
3092
3093 return 0;
3094 }
3095
3096 case Intrinsic::eh_unwind_init: {
3097 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3098 MMI->setCallsUnwindInit(true);
3099 }
3100
3101 return 0;
3102 }
3103
3104 case Intrinsic::eh_dwarf_cfa: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003105 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3106 SDOperand CfaArg;
3107 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3108 CfaArg = DAG.getNode(ISD::TRUNCATE,
3109 TLI.getPointerTy(), getValue(I.getOperand(1)));
3110 else
3111 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3112 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003113
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003114 SDOperand Offset = DAG.getNode(ISD::ADD,
3115 TLI.getPointerTy(),
3116 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3117 TLI.getPointerTy()),
3118 CfaArg);
3119 setValue(&I, DAG.getNode(ISD::ADD,
3120 TLI.getPointerTy(),
3121 DAG.getNode(ISD::FRAMEADDR,
3122 TLI.getPointerTy(),
3123 DAG.getConstant(0,
3124 TLI.getPointerTy())),
3125 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003126 return 0;
3127 }
3128
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003129 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003130 setValue(&I, DAG.getNode(ISD::FSQRT,
3131 getValue(I.getOperand(1)).getValueType(),
3132 getValue(I.getOperand(1))));
3133 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003134 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003135 setValue(&I, DAG.getNode(ISD::FPOWI,
3136 getValue(I.getOperand(1)).getValueType(),
3137 getValue(I.getOperand(1)),
3138 getValue(I.getOperand(2))));
3139 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003140 case Intrinsic::sin:
3141 setValue(&I, DAG.getNode(ISD::FSIN,
3142 getValue(I.getOperand(1)).getValueType(),
3143 getValue(I.getOperand(1))));
3144 return 0;
3145 case Intrinsic::cos:
3146 setValue(&I, DAG.getNode(ISD::FCOS,
3147 getValue(I.getOperand(1)).getValueType(),
3148 getValue(I.getOperand(1))));
3149 return 0;
3150 case Intrinsic::pow:
3151 setValue(&I, DAG.getNode(ISD::FPOW,
3152 getValue(I.getOperand(1)).getValueType(),
3153 getValue(I.getOperand(1)),
3154 getValue(I.getOperand(2))));
3155 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003156 case Intrinsic::pcmarker: {
3157 SDOperand Tmp = getValue(I.getOperand(1));
3158 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3159 return 0;
3160 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003161 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003162 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003163 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3164 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3165 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003166 setValue(&I, Tmp);
3167 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003168 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003169 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003170 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003171 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003172 assert(0 && "part_select intrinsic not implemented");
3173 abort();
3174 }
3175 case Intrinsic::part_set: {
3176 // Currently not implemented: just abort
3177 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003178 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003179 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003180 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003181 setValue(&I, DAG.getNode(ISD::BSWAP,
3182 getValue(I.getOperand(1)).getValueType(),
3183 getValue(I.getOperand(1))));
3184 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003185 case Intrinsic::cttz: {
3186 SDOperand Arg = getValue(I.getOperand(1));
3187 MVT::ValueType Ty = Arg.getValueType();
3188 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003189 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003190 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003191 }
3192 case Intrinsic::ctlz: {
3193 SDOperand Arg = getValue(I.getOperand(1));
3194 MVT::ValueType Ty = Arg.getValueType();
3195 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003196 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003197 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003198 }
3199 case Intrinsic::ctpop: {
3200 SDOperand Arg = getValue(I.getOperand(1));
3201 MVT::ValueType Ty = Arg.getValueType();
3202 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003203 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003204 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003205 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003206 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003207 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003208 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3209 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003210 setValue(&I, Tmp);
3211 DAG.setRoot(Tmp.getValue(1));
3212 return 0;
3213 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003214 case Intrinsic::stackrestore: {
3215 SDOperand Tmp = getValue(I.getOperand(1));
3216 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003217 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003218 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003219 case Intrinsic::var_annotation:
3220 // Discard annotate attributes
3221 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003222
Duncan Sands36397f52007-07-27 12:58:54 +00003223 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003224 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003225
3226 SDOperand Ops[6];
3227 Ops[0] = getRoot();
3228 Ops[1] = getValue(I.getOperand(1));
3229 Ops[2] = getValue(I.getOperand(2));
3230 Ops[3] = getValue(I.getOperand(3));
3231 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3232 Ops[5] = DAG.getSrcValue(F);
3233
Duncan Sandsf7331b32007-09-11 14:10:23 +00003234 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3235 DAG.getNodeValueTypes(TLI.getPointerTy(),
3236 MVT::Other), 2,
3237 Ops, 6);
3238
3239 setValue(&I, Tmp);
3240 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003241 return 0;
3242 }
Gordon Henriksence224772008-01-07 01:30:38 +00003243
3244 case Intrinsic::gcroot:
3245 if (GCI) {
3246 Value *Alloca = I.getOperand(1);
3247 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3248
3249 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3250 GCI->addStackRoot(FI->getIndex(), TypeMap);
3251 }
3252 return 0;
3253
3254 case Intrinsic::gcread:
3255 case Intrinsic::gcwrite:
3256 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3257 return 0;
3258
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003259 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003260 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003261 return 0;
3262 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003263
3264 case Intrinsic::trap: {
3265 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3266 return 0;
3267 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003268 case Intrinsic::prefetch: {
3269 SDOperand Ops[4];
3270 Ops[0] = getRoot();
3271 Ops[1] = getValue(I.getOperand(1));
3272 Ops[2] = getValue(I.getOperand(2));
3273 Ops[3] = getValue(I.getOperand(3));
3274 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3275 return 0;
3276 }
3277
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003278 case Intrinsic::memory_barrier: {
3279 SDOperand Ops[6];
3280 Ops[0] = getRoot();
3281 for (int x = 1; x < 6; ++x)
3282 Ops[x] = getValue(I.getOperand(x));
3283
3284 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3285 return 0;
3286 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003287 case Intrinsic::atomic_lcs: {
3288 SDOperand Root = getRoot();
3289 SDOperand O3 = getValue(I.getOperand(3));
3290 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3291 getValue(I.getOperand(1)),
3292 getValue(I.getOperand(2)),
3293 O3, O3.getValueType());
3294 setValue(&I, L);
3295 DAG.setRoot(L.getValue(1));
3296 return 0;
3297 }
Mon P Wang63307c32008-05-05 19:05:59 +00003298 case Intrinsic::atomic_las:
3299 return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3300 case Intrinsic::atomic_lss:
3301 return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3302 case Intrinsic::atomic_load_and:
3303 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3304 case Intrinsic::atomic_load_or:
3305 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3306 case Intrinsic::atomic_load_xor:
3307 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3308 case Intrinsic::atomic_load_min:
3309 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3310 case Intrinsic::atomic_load_max:
3311 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3312 case Intrinsic::atomic_load_umin:
3313 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3314 case Intrinsic::atomic_load_umax:
3315 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3316 case Intrinsic::atomic_swap:
3317 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003318 }
3319}
3320
3321
Duncan Sands6f74b482007-12-19 09:48:52 +00003322void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003323 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003324 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003325 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003326 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003327 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3328 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003329
Jim Laskey735b6f82007-02-22 15:38:06 +00003330 TargetLowering::ArgListTy Args;
3331 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003332 Args.reserve(CS.arg_size());
3333 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3334 i != e; ++i) {
3335 SDOperand ArgNode = getValue(*i);
3336 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003337
Duncan Sands6f74b482007-12-19 09:48:52 +00003338 unsigned attrInd = i - CS.arg_begin() + 1;
3339 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3340 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3341 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3342 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3343 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3344 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003345 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003346 Args.push_back(Entry);
3347 }
3348
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003349 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003350 // Insert a label before the invoke call to mark the try range. This can be
3351 // used to detect deletion of the invoke via the MachineModuleInfo.
3352 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003353 // Both PendingLoads and PendingExports must be flushed here;
3354 // this call might not return.
3355 (void)getRoot();
3356 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003357 DAG.getConstant(BeginLabel, MVT::i32),
3358 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003359 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003360
Jim Laskey735b6f82007-02-22 15:38:06 +00003361 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003362 TLI.LowerCallTo(getRoot(), CS.getType(),
3363 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003364 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003365 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003366 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003367 if (CS.getType() != Type::VoidTy)
3368 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003369 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003370
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003371 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003372 // Insert a label at the end of the invoke call to mark the try range. This
3373 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3374 EndLabel = MMI->NextLabelID();
3375 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003376 DAG.getConstant(EndLabel, MVT::i32),
3377 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003378
Duncan Sands6f74b482007-12-19 09:48:52 +00003379 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003380 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3381 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003382}
3383
3384
Chris Lattner1c08c712005-01-07 07:47:53 +00003385void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003386 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003387 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003388 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003389 if (unsigned IID = F->getIntrinsicID()) {
3390 RenameFn = visitIntrinsicCall(I, IID);
3391 if (!RenameFn)
3392 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003393 }
3394 }
3395
3396 // Check for well-known libc/libm calls. If the function is internal, it
3397 // can't be a library call.
3398 unsigned NameLen = F->getNameLen();
3399 if (!F->hasInternalLinkage() && NameLen) {
3400 const char *NameStr = F->getNameStart();
3401 if (NameStr[0] == 'c' &&
3402 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3403 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3404 if (I.getNumOperands() == 3 && // Basic sanity checks.
3405 I.getOperand(1)->getType()->isFloatingPoint() &&
3406 I.getType() == I.getOperand(1)->getType() &&
3407 I.getType() == I.getOperand(2)->getType()) {
3408 SDOperand LHS = getValue(I.getOperand(1));
3409 SDOperand RHS = getValue(I.getOperand(2));
3410 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3411 LHS, RHS));
3412 return;
3413 }
3414 } else if (NameStr[0] == 'f' &&
3415 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003416 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3417 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003418 if (I.getNumOperands() == 2 && // Basic sanity checks.
3419 I.getOperand(1)->getType()->isFloatingPoint() &&
3420 I.getType() == I.getOperand(1)->getType()) {
3421 SDOperand Tmp = getValue(I.getOperand(1));
3422 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3423 return;
3424 }
3425 } else if (NameStr[0] == 's' &&
3426 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003427 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3428 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003429 if (I.getNumOperands() == 2 && // Basic sanity checks.
3430 I.getOperand(1)->getType()->isFloatingPoint() &&
3431 I.getType() == I.getOperand(1)->getType()) {
3432 SDOperand Tmp = getValue(I.getOperand(1));
3433 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3434 return;
3435 }
3436 } else if (NameStr[0] == 'c' &&
3437 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003438 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3439 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003440 if (I.getNumOperands() == 2 && // Basic sanity checks.
3441 I.getOperand(1)->getType()->isFloatingPoint() &&
3442 I.getType() == I.getOperand(1)->getType()) {
3443 SDOperand Tmp = getValue(I.getOperand(1));
3444 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3445 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003446 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003447 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003448 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003449 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003450 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003451 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003452 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003453
Chris Lattner64e14b12005-01-08 22:48:57 +00003454 SDOperand Callee;
3455 if (!RenameFn)
3456 Callee = getValue(I.getOperand(0));
3457 else
3458 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003459
Duncan Sands6f74b482007-12-19 09:48:52 +00003460 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003461}
3462
Jim Laskey735b6f82007-02-22 15:38:06 +00003463
Dan Gohmanef5d1942008-03-11 21:11:25 +00003464void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003465 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003466 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3467 setValue(&I, Undef);
Chris Lattner6833b062008-04-28 07:16:35 +00003468 return;
Dan Gohman3dc34f62008-04-23 20:21:29 +00003469 }
Chris Lattner6833b062008-04-28 07:16:35 +00003470
3471 // To add support for individual return values with aggregate types,
3472 // we'd need a way to take a getresult index and determine which
3473 // values of the Call SDNode are associated with it.
3474 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3475 "Individual return values must not be aggregates!");
3476
3477 SDOperand Call = getValue(I.getOperand(0));
3478 setValue(&I, SDOperand(Call.Val, I.getIndex()));
Dan Gohmanef5d1942008-03-11 21:11:25 +00003479}
3480
3481
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003482/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3483/// this value and returns the result as a ValueVT value. This uses
3484/// Chain/Flag as the input and updates them for the output Chain/Flag.
3485/// If the Flag pointer is NULL, no flag is used.
3486SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner6833b062008-04-28 07:16:35 +00003487 SDOperand &Chain,
3488 SDOperand *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003489 // Assemble the legal parts into the final values.
3490 SmallVector<SDOperand, 4> Values(ValueVTs.size());
Chris Lattner6833b062008-04-28 07:16:35 +00003491 SmallVector<SDOperand, 8> Parts;
3492 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003493 // Copy the legal parts from the registers.
3494 MVT::ValueType ValueVT = ValueVTs[Value];
3495 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3496 MVT::ValueType RegisterVT = RegVTs[Value];
3497
Chris Lattner6833b062008-04-28 07:16:35 +00003498 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003499 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003500 SDOperand P;
3501 if (Flag == 0)
3502 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3503 else {
3504 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003505 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003506 }
3507 Chain = P.getValue(1);
Dan Gohman23ce5022008-04-25 18:27:55 +00003508 Parts[Part+i] = P;
3509 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003510
Dan Gohman23ce5022008-04-25 18:27:55 +00003511 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3512 ValueVT);
3513 Part += NumRegs;
3514 }
Chris Lattner6833b062008-04-28 07:16:35 +00003515
3516 if (ValueVTs.size() == 1)
3517 return Values[0];
3518
Dan Gohman23ce5022008-04-25 18:27:55 +00003519 return DAG.getNode(ISD::MERGE_VALUES,
3520 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3521 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003522}
3523
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003524/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3525/// specified value into the registers specified by this object. This uses
3526/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003527/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003528void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003529 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003530 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003531 unsigned NumRegs = Regs.size();
3532 SmallVector<SDOperand, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003533 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003534 MVT::ValueType ValueVT = ValueVTs[Value];
3535 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3536 MVT::ValueType RegisterVT = RegVTs[Value];
3537
3538 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3539 &Parts[Part], NumParts, RegisterVT);
3540 Part += NumParts;
3541 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003542
3543 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003544 SmallVector<SDOperand, 8> Chains(NumRegs);
3545 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003546 SDOperand Part;
3547 if (Flag == 0)
3548 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3549 else {
3550 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003551 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003552 }
3553 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003554 }
Chris Lattner6833b062008-04-28 07:16:35 +00003555
Evan Cheng33bf38a2008-04-28 22:07:13 +00003556 if (NumRegs == 1 || Flag)
3557 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3558 // flagged to it. That is the CopyToReg nodes and the user are considered
3559 // a single scheduling unit. If we create a TokenFactor and return it as
3560 // chain, then the TokenFactor is both a predecessor (operand) of the
3561 // user as well as a successor (the TF operands are flagged to the user).
3562 // c1, f1 = CopyToReg
3563 // c2, f2 = CopyToReg
3564 // c3 = TokenFactor c1, c2
3565 // ...
3566 // = op c3, ..., f2
3567 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003568 else
3569 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003570}
Chris Lattner864635a2006-02-22 22:37:12 +00003571
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003572/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3573/// operand list. This adds the code marker and includes the number of
3574/// values added into it.
3575void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003576 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00003577 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3578 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003579 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3580 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Dan Gohman23ce5022008-04-25 18:27:55 +00003581 MVT::ValueType RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003582 for (unsigned i = 0; i != NumRegs; ++i)
3583 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003584 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003585}
Chris Lattner864635a2006-02-22 22:37:12 +00003586
3587/// isAllocatableRegister - If the specified register is safe to allocate,
3588/// i.e. it isn't a stack pointer or some other special register, return the
3589/// register class for the register. Otherwise, return null.
3590static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003591isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003592 const TargetLowering &TLI,
3593 const TargetRegisterInfo *TRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003594 MVT::ValueType FoundVT = MVT::Other;
3595 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003596 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3597 E = TRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003598 MVT::ValueType ThisVT = MVT::Other;
3599
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003600 const TargetRegisterClass *RC = *RCI;
3601 // If none of the the value types for this register class are valid, we
3602 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003603 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3604 I != E; ++I) {
3605 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003606 // If we have already found this register in a different register class,
3607 // choose the one with the largest VT specified. For example, on
3608 // PowerPC, we favor f64 register classes over f32.
3609 if (FoundVT == MVT::Other ||
3610 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3611 ThisVT = *I;
3612 break;
3613 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003614 }
3615 }
3616
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003617 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003618
Chris Lattner864635a2006-02-22 22:37:12 +00003619 // NOTE: This isn't ideal. In particular, this might allocate the
3620 // frame pointer in functions that need it (due to them not being taken
3621 // out of allocation, because a variable sized allocation hasn't been seen
3622 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003623 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3624 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003625 if (*I == Reg) {
3626 // We found a matching register class. Keep looking at others in case
3627 // we find one with larger registers that this physreg is also in.
3628 FoundRC = RC;
3629 FoundVT = ThisVT;
3630 break;
3631 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003632 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003633 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003634}
3635
Chris Lattner4e4b5762006-02-01 18:59:47 +00003636
Chris Lattner0c583402007-04-28 20:49:53 +00003637namespace {
3638/// AsmOperandInfo - This contains information for each constraint that we are
3639/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003640struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3641 /// CallOperand - If this is the result output operand or a clobber
3642 /// this is null, otherwise it is the incoming operand to the CallInst.
3643 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003644 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003645
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003646 /// AssignedRegs - If this is a register or register class operand, this
3647 /// contains the set of register corresponding to the operand.
3648 RegsForValue AssignedRegs;
3649
Dan Gohman23ce5022008-04-25 18:27:55 +00003650 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003651 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003652 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003653
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003654 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3655 /// busy in OutputRegs/InputRegs.
3656 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3657 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003658 std::set<unsigned> &InputRegs,
3659 const TargetRegisterInfo &TRI) const {
3660 if (isOutReg) {
3661 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3662 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3663 }
3664 if (isInReg) {
3665 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3666 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3667 }
3668 }
3669
3670private:
3671 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3672 /// specified set.
3673 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3674 const TargetRegisterInfo &TRI) {
3675 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3676 Regs.insert(Reg);
3677 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3678 for (; *Aliases; ++Aliases)
3679 Regs.insert(*Aliases);
3680 }
Chris Lattner0c583402007-04-28 20:49:53 +00003681};
3682} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003683
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003684
Chris Lattner0fe71e92008-02-21 19:43:13 +00003685/// GetRegistersForValue - Assign registers (virtual or physical) for the
3686/// specified operand. We prefer to assign virtual registers, to allow the
3687/// register allocator handle the assignment process. However, if the asm uses
3688/// features that we can't model on machineinstrs, we have SDISel do the
3689/// allocation. This produces generally horrible, but correct, code.
3690///
3691/// OpInfo describes the operand.
3692/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3693/// or any explicitly clobbered registers.
3694/// Input and OutputRegs are the set of already allocated physical registers.
3695///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003696void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003697GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003698 std::set<unsigned> &OutputRegs,
3699 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003700 // Compute whether this value requires an input register, an output register,
3701 // or both.
3702 bool isOutReg = false;
3703 bool isInReg = false;
3704 switch (OpInfo.Type) {
3705 case InlineAsm::isOutput:
3706 isOutReg = true;
3707
3708 // If this is an early-clobber output, or if there is an input
3709 // constraint that matches this, we need to reserve the input register
3710 // so no other inputs allocate to it.
3711 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3712 break;
3713 case InlineAsm::isInput:
3714 isInReg = true;
3715 isOutReg = false;
3716 break;
3717 case InlineAsm::isClobber:
3718 isOutReg = true;
3719 isInReg = true;
3720 break;
3721 }
3722
3723
3724 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003725 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003726
3727 // If this is a constraint for a single physreg, or a constraint for a
3728 // register class, find it.
3729 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3730 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3731 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003732
3733 unsigned NumRegs = 1;
3734 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003735 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003736 MVT::ValueType RegVT;
3737 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3738
Chris Lattnerbf996f12007-04-30 17:29:31 +00003739
3740 // If this is a constraint for a specific physical register, like {r17},
3741 // assign it now.
3742 if (PhysReg.first) {
3743 if (OpInfo.ConstraintVT == MVT::Other)
3744 ValueVT = *PhysReg.second->vt_begin();
3745
3746 // Get the actual register value type. This is important, because the user
3747 // may have asked for (e.g.) the AX register in i32 type. We need to
3748 // remember that AX is actually i16 to get the right extension.
3749 RegVT = *PhysReg.second->vt_begin();
3750
3751 // This is a explicit reference to a physical register.
3752 Regs.push_back(PhysReg.first);
3753
3754 // If this is an expanded reference, add the rest of the regs to Regs.
3755 if (NumRegs != 1) {
3756 TargetRegisterClass::iterator I = PhysReg.second->begin();
3757 TargetRegisterClass::iterator E = PhysReg.second->end();
3758 for (; *I != PhysReg.first; ++I)
3759 assert(I != E && "Didn't find reg!");
3760
3761 // Already added the first reg.
3762 --NumRegs; ++I;
3763 for (; NumRegs; --NumRegs, ++I) {
3764 assert(I != E && "Ran out of registers to allocate!");
3765 Regs.push_back(*I);
3766 }
3767 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003768 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003769 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3770 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003771 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003772 }
3773
3774 // Otherwise, if this was a reference to an LLVM register class, create vregs
3775 // for this reference.
3776 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003777 const TargetRegisterClass *RC = PhysReg.second;
3778 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003779 // If this is an early clobber or tied register, our regalloc doesn't know
3780 // how to maintain the constraint. If it isn't, go ahead and create vreg
3781 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003782 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3783 // If there is some other early clobber and this is an input register,
3784 // then we are forced to pre-allocate the input reg so it doesn't
3785 // conflict with the earlyclobber.
3786 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003787 RegVT = *PhysReg.second->vt_begin();
3788
3789 if (OpInfo.ConstraintVT == MVT::Other)
3790 ValueVT = RegVT;
3791
3792 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00003793 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003794 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00003795 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00003796
Dan Gohman23ce5022008-04-25 18:27:55 +00003797 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003798 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003799 }
3800
3801 // Otherwise, we can't allocate it. Let the code below figure out how to
3802 // maintain these constraints.
3803 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3804
3805 } else {
3806 // This is a reference to a register class that doesn't directly correspond
3807 // to an LLVM register class. Allocate NumRegs consecutive, available,
3808 // registers from the class.
3809 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3810 OpInfo.ConstraintVT);
3811 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003812
Dan Gohman6f0d0242008-02-10 18:45:23 +00003813 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003814 unsigned NumAllocated = 0;
3815 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3816 unsigned Reg = RegClassRegs[i];
3817 // See if this register is available.
3818 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3819 (isInReg && InputRegs.count(Reg))) { // Already used.
3820 // Make sure we find consecutive registers.
3821 NumAllocated = 0;
3822 continue;
3823 }
3824
3825 // Check to see if this register is allocatable (i.e. don't give out the
3826 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003827 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00003828 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003829 if (!RC) { // Couldn't allocate this register.
3830 // Reset NumAllocated to make sure we return consecutive registers.
3831 NumAllocated = 0;
3832 continue;
3833 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003834 }
3835
3836 // Okay, this register is good, we can use it.
3837 ++NumAllocated;
3838
3839 // If we allocated enough consecutive registers, succeed.
3840 if (NumAllocated == NumRegs) {
3841 unsigned RegStart = (i-NumAllocated)+1;
3842 unsigned RegEnd = i+1;
3843 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003844 for (unsigned i = RegStart; i != RegEnd; ++i)
3845 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003846
Dan Gohman23ce5022008-04-25 18:27:55 +00003847 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003848 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003849 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003850 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003851 }
3852 }
3853
3854 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00003855}
3856
3857
Chris Lattnerce7518c2006-01-26 22:24:51 +00003858/// visitInlineAsm - Handle a call to an InlineAsm object.
3859///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003860void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3861 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003862
Chris Lattner0c583402007-04-28 20:49:53 +00003863 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00003864 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003865
3866 SDOperand Chain = getRoot();
3867 SDOperand Flag;
3868
Chris Lattner4e4b5762006-02-01 18:59:47 +00003869 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003870
Chris Lattner0c583402007-04-28 20:49:53 +00003871 // Do a prepass over the constraints, canonicalizing them, and building up the
3872 // ConstraintOperands list.
3873 std::vector<InlineAsm::ConstraintInfo>
3874 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003875
3876 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3877 // constraint. If so, we can't let the register allocator allocate any input
3878 // registers, because it will not know to avoid the earlyclobbered output reg.
3879 bool SawEarlyClobber = false;
3880
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003881 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00003882 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00003883 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003884 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3885 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00003886
Chris Lattner0c583402007-04-28 20:49:53 +00003887 MVT::ValueType OpVT = MVT::Other;
3888
3889 // Compute the value type for each operand.
3890 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003891 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00003892 // Indirect outputs just consume an argument.
3893 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003894 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00003895 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003896 }
Chris Lattneracf8b012008-04-27 23:44:28 +00003897 // The return value of the call is this value. As such, there is no
3898 // corresponding argument.
3899 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3900 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3901 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3902 } else {
3903 assert(ResNo == 0 && "Asm only has one result!");
3904 OpVT = TLI.getValueType(CS.getType());
3905 }
3906 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003907 break;
3908 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003909 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003910 break;
3911 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003912 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003913 break;
3914 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003915
Chris Lattner0c583402007-04-28 20:49:53 +00003916 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003917 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00003918 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00003919 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3920 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003921 else {
3922 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3923 const Type *OpTy = OpInfo.CallOperandVal->getType();
3924 // If this is an indirect operand, the operand is a pointer to the
3925 // accessed type.
3926 if (OpInfo.isIndirect)
3927 OpTy = cast<PointerType>(OpTy)->getElementType();
3928
3929 // If OpTy is not a first-class value, it may be a struct/union that we
3930 // can tile with integers.
3931 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3932 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3933 switch (BitSize) {
3934 default: break;
3935 case 1:
3936 case 8:
3937 case 16:
3938 case 32:
3939 case 64:
3940 OpTy = IntegerType::get(BitSize);
3941 break;
3942 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003943 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003944
3945 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003946 }
3947 }
3948
3949 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003950
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003951 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00003952 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00003953
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003954 // Keep track of whether we see an earlyclobber.
3955 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003956
Chris Lattner0fe71e92008-02-21 19:43:13 +00003957 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00003958 if (!SawEarlyClobber &&
3959 OpInfo.Type == InlineAsm::isClobber &&
3960 OpInfo.ConstraintType == TargetLowering::C_Register) {
3961 // Note that we want to ignore things that we don't trick here, like
3962 // dirflag, fpsr, flags, etc.
3963 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3964 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3965 OpInfo.ConstraintVT);
3966 if (PhysReg.first || PhysReg.second) {
3967 // This is a register we know of.
3968 SawEarlyClobber = true;
3969 }
3970 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00003971
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003972 // If this is a memory input, and if the operand is not indirect, do what we
3973 // need to to provide an address for the memory input.
3974 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3975 !OpInfo.isIndirect) {
3976 assert(OpInfo.Type == InlineAsm::isInput &&
3977 "Can only indirectify direct input operands!");
3978
3979 // Memory operands really want the address of the value. If we don't have
3980 // an indirect input, put it in the constpool if we can, otherwise spill
3981 // it to a stack slot.
3982
3983 // If the operand is a float, integer, or vector constant, spill to a
3984 // constant pool entry to get its address.
3985 Value *OpVal = OpInfo.CallOperandVal;
3986 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3987 isa<ConstantVector>(OpVal)) {
3988 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3989 TLI.getPointerTy());
3990 } else {
3991 // Otherwise, create a stack slot and emit a store to it before the
3992 // asm.
3993 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00003994 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003995 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3996 MachineFunction &MF = DAG.getMachineFunction();
3997 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3998 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3999 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4000 OpInfo.CallOperand = StackSlot;
4001 }
4002
4003 // There is no longer a Value* corresponding to this operand.
4004 OpInfo.CallOperandVal = 0;
4005 // It is now an indirect operand.
4006 OpInfo.isIndirect = true;
4007 }
4008
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004009 // If this constraint is for a specific register, allocate it before
4010 // anything else.
4011 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4012 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004013 }
Chris Lattner0c583402007-04-28 20:49:53 +00004014 ConstraintInfos.clear();
4015
4016
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004017 // Second pass - Loop over all of the operands, assigning virtual or physregs
4018 // to registerclass operands.
4019 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004020 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004021
4022 // C_Register operands have already been allocated, Other/Memory don't need
4023 // to be.
4024 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4025 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4026 }
4027
Chris Lattner0c583402007-04-28 20:49:53 +00004028 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4029 std::vector<SDOperand> AsmNodeOperands;
4030 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
4031 AsmNodeOperands.push_back(
4032 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4033
Chris Lattner2cc2f662006-02-01 01:28:23 +00004034
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004035 // Loop over all of the inputs, copying the operand values into the
4036 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004037 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004038
Chris Lattner0c583402007-04-28 20:49:53 +00004039 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4040 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4041
4042 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004043 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004044
Chris Lattner0c583402007-04-28 20:49:53 +00004045 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004046 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004047 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4048 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004049 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004050 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004051
Chris Lattner22873462006-02-27 23:45:39 +00004052 // Add information to the INLINEASM node to know about this output.
4053 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004054 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4055 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004056 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004057 break;
4058 }
4059
Chris Lattner2a600be2007-04-28 21:01:43 +00004060 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004061
Chris Lattner864635a2006-02-22 22:37:12 +00004062 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004063 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004064 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004065 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004066 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004067 exit(1);
4068 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004069
Chris Lattner41f62592008-04-29 04:29:54 +00004070 // If this is an indirect operand, store through the pointer after the
4071 // asm.
4072 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004073 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004074 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004075 } else {
4076 // This is the result value of the call.
4077 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4078 // Concatenate this output onto the outputs list.
4079 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004080 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004081
4082 // Add information to the INLINEASM node to know that this register is
4083 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004084 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4085 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004086 break;
4087 }
4088 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00004089 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004090
Chris Lattner0c583402007-04-28 20:49:53 +00004091 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004092 // If this is required to match an output register we have already set,
4093 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004094 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004095
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004096 // Scan until we find the definition we already emitted of this operand.
4097 // When we find it, create a RegsForValue operand.
4098 unsigned CurOp = 2; // The first operand.
4099 for (; OperandNo; --OperandNo) {
4100 // Advance to the next operand.
4101 unsigned NumOps =
4102 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004103 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4104 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004105 "Skipped past definitions?");
4106 CurOp += (NumOps>>3)+1;
4107 }
4108
4109 unsigned NumOps =
4110 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004111 if ((NumOps & 7) == 2 /*REGDEF*/) {
4112 // Add NumOps>>3 registers to MatchedRegs.
4113 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004114 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004115 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4116 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004117 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4118 unsigned Reg =
4119 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4120 MatchedRegs.Regs.push_back(Reg);
4121 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004122
Chris Lattner527fae12007-02-01 01:21:12 +00004123 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004124 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004125 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4126 break;
4127 } else {
4128 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004129 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4130 // Add information to the INLINEASM node to know about this input.
4131 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4132 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4133 TLI.getPointerTy()));
4134 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4135 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004136 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004137 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004138
Chris Lattner2a600be2007-04-28 21:01:43 +00004139 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004140 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004141 "Don't know how to handle indirect other inputs yet!");
4142
Chris Lattner48884cd2007-08-25 00:47:38 +00004143 std::vector<SDOperand> Ops;
4144 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4145 Ops, DAG);
4146 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004147 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004148 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004149 exit(1);
4150 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004151
4152 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004153 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004154 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4155 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004156 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004157 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004158 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004159 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004160 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4161 "Memory operands expect pointer values");
4162
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004163 // Add information to the INLINEASM node to know about this input.
4164 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004165 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4166 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004167 AsmNodeOperands.push_back(InOperandVal);
4168 break;
4169 }
4170
Chris Lattner2a600be2007-04-28 21:01:43 +00004171 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4172 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4173 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004174 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004175 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004176
4177 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004178 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4179 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004180
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004181 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004182
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004183 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4184 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004185 break;
4186 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004187 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004188 // Add the clobbered value to the operand list, so that the register
4189 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004190 if (!OpInfo.AssignedRegs.Regs.empty())
4191 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4192 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004193 break;
4194 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004195 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004196 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004197
4198 // Finish up input operands.
4199 AsmNodeOperands[0] = Chain;
4200 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4201
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004202 Chain = DAG.getNode(ISD::INLINEASM,
4203 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004204 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004205 Flag = Chain.getValue(1);
4206
Chris Lattner6656dd12006-01-31 02:03:41 +00004207 // If this asm returns a register value, copy the result from that register
4208 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004209 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004210 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004211
4212 // If any of the results of the inline asm is a vector, it may have the
4213 // wrong width/num elts. This can happen for register classes that can
4214 // contain multiple different value types. The preg or vreg allocated may
4215 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004216 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004217 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4218 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4219 if (MVT::isVector(Val.Val->getValueType(i)))
4220 Val = DAG.getNode(ISD::BIT_CONVERT,
4221 TLI.getValueType(ResSTy->getElementType(i)), Val);
4222 }
4223 } else {
4224 if (MVT::isVector(Val.getValueType()))
4225 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4226 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004227 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004228
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004229 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004230 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004231
Chris Lattner6656dd12006-01-31 02:03:41 +00004232 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4233
4234 // Process indirect outputs, first output all of the flagged copies out of
4235 // physregs.
4236 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004237 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004238 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004239 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004240 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004241 }
4242
4243 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004244 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004245 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004246 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004247 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004248 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004249 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004250 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4251 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004252 DAG.setRoot(Chain);
4253}
4254
4255
Chris Lattner1c08c712005-01-07 07:47:53 +00004256void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4257 SDOperand Src = getValue(I.getOperand(0));
4258
4259 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004260
4261 if (IntPtr < Src.getValueType())
4262 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4263 else if (IntPtr > Src.getValueType())
4264 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004265
4266 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004267 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004268 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004269 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004270
Reid Spencer47857812006-12-31 05:55:36 +00004271 TargetLowering::ArgListTy Args;
4272 TargetLowering::ArgListEntry Entry;
4273 Entry.Node = Src;
4274 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004275 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004276
4277 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004278 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4279 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004280 setValue(&I, Result.first); // Pointers always fit in registers
4281 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004282}
4283
4284void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004285 TargetLowering::ArgListTy Args;
4286 TargetLowering::ArgListEntry Entry;
4287 Entry.Node = getValue(I.getOperand(0));
4288 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004289 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00004290 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004291 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004292 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4293 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004294 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4295 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004296}
4297
Evan Chengff9b3732008-01-30 18:18:23 +00004298// EmitInstrWithCustomInserter - This method should be implemented by targets
4299// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004300// instructions are special in various ways, which require special support to
4301// insert. The specified MachineInstr is created but not inserted into any
4302// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004303MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004304 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004305 cerr << "If a target marks an instruction with "
4306 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004307 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004308 abort();
4309 return 0;
4310}
4311
Chris Lattner39ae3622005-01-09 00:00:49 +00004312void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004313 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4314 getValue(I.getOperand(1)),
4315 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004316}
4317
4318void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004319 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4320 getValue(I.getOperand(0)),
4321 DAG.getSrcValue(I.getOperand(0)));
4322 setValue(&I, V);
4323 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004324}
4325
4326void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004327 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4328 getValue(I.getOperand(1)),
4329 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004330}
4331
4332void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004333 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4334 getValue(I.getOperand(1)),
4335 getValue(I.getOperand(2)),
4336 DAG.getSrcValue(I.getOperand(1)),
4337 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004338}
4339
Chris Lattnerfdfded52006-04-12 16:20:43 +00004340/// TargetLowering::LowerArguments - This is the default LowerArguments
4341/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004342/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4343/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004344std::vector<SDOperand>
4345TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4346 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4347 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004348 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004349 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4350 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4351
4352 // Add one result value for each formal argument.
4353 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004354 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004355 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4356 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004357 MVT::ValueType VT = getValueType(I->getType());
Duncan Sands276dcbd2008-03-21 09:14:45 +00004358 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004359 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004360 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004361
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004362 if (F.paramHasAttr(j, ParamAttr::ZExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004363 Flags.setZExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004364 if (F.paramHasAttr(j, ParamAttr::SExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004365 Flags.setSExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004366 if (F.paramHasAttr(j, ParamAttr::InReg))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004367 Flags.setInReg();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004368 if (F.paramHasAttr(j, ParamAttr::StructRet))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004369 Flags.setSRet();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004370 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004371 Flags.setByVal();
Rafael Espindola594d37e2007-08-10 14:44:42 +00004372 const PointerType *Ty = cast<PointerType>(I->getType());
Duncan Sandsa41d7192008-01-13 21:19:59 +00004373 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004374 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004375 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004376 // For ByVal, alignment should be passed from FE. BE will guess if
4377 // this info is not there but there are cases it cannot get right.
4378 if (F.getParamAlignment(j))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004379 FrameAlign = F.getParamAlignment(j);
4380 Flags.setByValAlign(FrameAlign);
4381 Flags.setByValSize(FrameSize);
Rafael Espindola594d37e2007-08-10 14:44:42 +00004382 }
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004383 if (F.paramHasAttr(j, ParamAttr::Nest))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004384 Flags.setNest();
4385 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004386
4387 MVT::ValueType RegisterVT = getRegisterType(VT);
4388 unsigned NumRegs = getNumRegisters(VT);
4389 for (unsigned i = 0; i != NumRegs; ++i) {
4390 RetVals.push_back(RegisterVT);
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004391 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004392 if (NumRegs > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004393 MyFlags.setSplit();
Duncan Sandsb988bac2008-02-11 20:58:28 +00004394 // if it isn't first piece, alignment must be 1
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004395 else if (i > 0)
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004396 MyFlags.setOrigAlign(1);
4397 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004398 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004399 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004400
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004401 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004402
4403 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004404 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004405 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004406 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004407
4408 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4409 // allows exposing the loads that may be part of the argument access to the
4410 // first DAGCombiner pass.
4411 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4412
4413 // The number of results should match up, except that the lowered one may have
4414 // an extra flag result.
4415 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4416 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4417 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4418 && "Lowering produced unexpected number of results!");
4419 Result = TmpRes.Val;
4420
Dan Gohman27a70be2007-07-02 16:18:06 +00004421 unsigned NumArgRegs = Result->getNumValues() - 1;
4422 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004423
4424 // Set up the return result vector.
4425 Ops.clear();
4426 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004427 unsigned Idx = 1;
4428 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4429 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004430 MVT::ValueType VT = getValueType(I->getType());
Duncan Sandsb988bac2008-02-11 20:58:28 +00004431 MVT::ValueType PartVT = getRegisterType(VT);
4432
4433 unsigned NumParts = getNumRegisters(VT);
4434 SmallVector<SDOperand, 4> Parts(NumParts);
4435 for (unsigned j = 0; j != NumParts; ++j)
4436 Parts[j] = SDOperand(Result, i++);
4437
4438 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4439 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4440 AssertOp = ISD::AssertSext;
4441 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4442 AssertOp = ISD::AssertZext;
4443
4444 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
Chris Lattner4468c1f2008-03-09 09:38:46 +00004445 AssertOp));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004446 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004447 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004448 return Ops;
4449}
4450
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004451
4452/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4453/// implementation, which just inserts an ISD::CALL node, which is later custom
4454/// lowered by the target to something concrete. FIXME: When all targets are
4455/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4456std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004457TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4458 bool RetSExt, bool RetZExt, bool isVarArg,
4459 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004460 SDOperand Callee,
4461 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004462 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004463 Ops.push_back(Chain); // Op#0 - Chain
4464 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4465 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4466 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4467 Ops.push_back(Callee);
4468
4469 // Handle all of the outgoing arguments.
4470 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00004471 MVT::ValueType VT = getValueType(Args[i].Ty);
4472 SDOperand Op = Args[i].Node;
Duncan Sands276dcbd2008-03-21 09:14:45 +00004473 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004474 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004475 getTargetData()->getABITypeAlignment(Args[i].Ty);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004476
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004477 if (Args[i].isZExt)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004478 Flags.setZExt();
4479 if (Args[i].isSExt)
4480 Flags.setSExt();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004481 if (Args[i].isInReg)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004482 Flags.setInReg();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004483 if (Args[i].isSRet)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004484 Flags.setSRet();
Rafael Espindola21485be2007-08-20 15:18:24 +00004485 if (Args[i].isByVal) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004486 Flags.setByVal();
Rafael Espindola21485be2007-08-20 15:18:24 +00004487 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004488 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004489 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004490 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004491 // For ByVal, alignment should come from FE. BE will guess if this
4492 // info is not there but there are cases it cannot get right.
4493 if (Args[i].Alignment)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004494 FrameAlign = Args[i].Alignment;
4495 Flags.setByValAlign(FrameAlign);
4496 Flags.setByValSize(FrameSize);
Rafael Espindola21485be2007-08-20 15:18:24 +00004497 }
Duncan Sands36397f52007-07-27 12:58:54 +00004498 if (Args[i].isNest)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004499 Flags.setNest();
4500 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004501
Duncan Sandsb988bac2008-02-11 20:58:28 +00004502 MVT::ValueType PartVT = getRegisterType(VT);
4503 unsigned NumParts = getNumRegisters(VT);
4504 SmallVector<SDOperand, 4> Parts(NumParts);
4505 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4506
4507 if (Args[i].isSExt)
4508 ExtendKind = ISD::SIGN_EXTEND;
4509 else if (Args[i].isZExt)
4510 ExtendKind = ISD::ZERO_EXTEND;
4511
4512 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4513
4514 for (unsigned i = 0; i != NumParts; ++i) {
4515 // if it isn't first piece, alignment must be 1
Duncan Sands276dcbd2008-03-21 09:14:45 +00004516 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004517 if (NumParts > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004518 MyFlags.setSplit();
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004519 else if (i != 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004520 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004521
4522 Ops.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004523 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohman27a70be2007-07-02 16:18:06 +00004524 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004525 }
4526
Dan Gohmanef5d1942008-03-11 21:11:25 +00004527 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004528 // the potentially illegal return value types.
Dan Gohmanef5d1942008-03-11 21:11:25 +00004529 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4530 SmallVector<MVT::ValueType, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004531 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004532
Dan Gohman23ce5022008-04-25 18:27:55 +00004533 // Then we translate that to a list of legal types.
4534 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4535 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004536 MVT::ValueType RegisterVT = getRegisterType(VT);
4537 unsigned NumRegs = getNumRegisters(VT);
4538 for (unsigned i = 0; i != NumRegs; ++i)
4539 LoweredRetTys.push_back(RegisterVT);
4540 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004541
Dan Gohmanef5d1942008-03-11 21:11:25 +00004542 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004543
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004544 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004545 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004546 DAG.getVTList(&LoweredRetTys[0],
4547 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004548 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004549 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004550
4551 // Gather up the call result into a single value.
4552 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004553 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4554
4555 if (RetSExt)
4556 AssertOp = ISD::AssertSext;
4557 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004558 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004559
Dan Gohmanef5d1942008-03-11 21:11:25 +00004560 SmallVector<SDOperand, 4> ReturnValues;
4561 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004562 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4563 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004564 MVT::ValueType RegisterVT = getRegisterType(VT);
4565 unsigned NumRegs = getNumRegisters(VT);
4566 unsigned RegNoEnd = NumRegs + RegNo;
4567 SmallVector<SDOperand, 4> Results;
4568 for (; RegNo != RegNoEnd; ++RegNo)
4569 Results.push_back(Res.getValue(RegNo));
4570 SDOperand ReturnValue =
4571 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4572 AssertOp);
4573 ReturnValues.push_back(ReturnValue);
4574 }
4575 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4576 DAG.getNode(ISD::MERGE_VALUES,
4577 DAG.getVTList(&RetTys[0], RetTys.size()),
4578 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004579 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004580
4581 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004582}
4583
Chris Lattner50381b62005-05-14 05:50:48 +00004584SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004585 assert(0 && "LowerOperation not implemented for this target!");
4586 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004587 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004588}
4589
Nate Begeman0aed7842006-01-28 03:14:31 +00004590SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4591 SelectionDAG &DAG) {
4592 assert(0 && "CustomPromoteOperation not implemented for this target!");
4593 abort();
4594 return SDOperand();
4595}
4596
Chris Lattner7041ee32005-01-11 05:56:49 +00004597//===----------------------------------------------------------------------===//
4598// SelectionDAGISel code
4599//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004600
4601unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004602 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004603}
4604
Chris Lattner495a0b52005-08-17 06:37:43 +00004605void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004606 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004607 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004608 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004609}
Chris Lattner1c08c712005-01-07 07:47:53 +00004610
Chris Lattner1c08c712005-01-07 07:47:53 +00004611bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004612 // Get alias analysis for load/store combining.
4613 AA = &getAnalysis<AliasAnalysis>();
4614
Chris Lattner1c08c712005-01-07 07:47:53 +00004615 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004616 if (MF.getFunction()->hasCollector())
4617 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4618 else
4619 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004620 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004621 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004622
4623 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4624
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004625 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4626 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4627 // Mark landing pad.
4628 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004629
4630 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004631 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004632
Evan Chengad2070c2007-02-10 02:43:39 +00004633 // Add function live-ins to entry block live-in set.
4634 BasicBlock *EntryBB = &Fn.getEntryBlock();
4635 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004636 if (!RegInfo->livein_empty())
4637 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4638 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004639 BB->addLiveIn(I->first);
4640
Duncan Sandsf4070822007-06-15 19:04:19 +00004641#ifndef NDEBUG
4642 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4643 "Not all catch info was assigned to a landing pad!");
4644#endif
4645
Chris Lattner1c08c712005-01-07 07:47:53 +00004646 return true;
4647}
4648
Chris Lattner6833b062008-04-28 07:16:35 +00004649void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004650 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004651 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004652 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004653 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004654 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004655
Dan Gohman23ce5022008-04-25 18:27:55 +00004656 RegsForValue RFV(TLI, Reg, V->getType());
4657 SDOperand Chain = DAG.getEntryNode();
4658 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4659 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004660}
4661
Chris Lattner068a81e2005-01-17 17:15:02 +00004662void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004663LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004664 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004665 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004666 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004667 SDOperand OldRoot = SDL.DAG.getRoot();
4668 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004669
Chris Lattnerbf209482005-10-30 19:42:35 +00004670 unsigned a = 0;
4671 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4672 AI != E; ++AI, ++a)
4673 if (!AI->use_empty()) {
4674 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004675
Chris Lattnerbf209482005-10-30 19:42:35 +00004676 // If this argument is live outside of the entry block, insert a copy from
4677 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004678 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4679 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004680 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004681 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004682 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004683
Chris Lattnerbf209482005-10-30 19:42:35 +00004684 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004685 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004686 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004687}
4688
Duncan Sandsf4070822007-06-15 19:04:19 +00004689static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4690 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004691 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004692 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004693 // Apply the catch info to DestBB.
4694 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4695#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004696 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4697 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004698#endif
4699 }
4700}
4701
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004702/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4703/// whether object offset >= 0.
4704static bool
4705IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4706 if (!isa<FrameIndexSDNode>(Op)) return false;
4707
4708 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4709 int FrameIdx = FrameIdxNode->getIndex();
4710 return MFI->isFixedObjectIndex(FrameIdx) &&
4711 MFI->getObjectOffset(FrameIdx) >= 0;
4712}
4713
4714/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4715/// possibly be overwritten when lowering the outgoing arguments in a tail
4716/// call. Currently the implementation of this call is very conservative and
4717/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4718/// virtual registers would be overwritten by direct lowering.
4719static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4720 MachineFrameInfo * MFI) {
4721 RegisterSDNode * OpReg = NULL;
4722 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4723 (Op.getOpcode()== ISD::CopyFromReg &&
4724 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4725 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4726 (Op.getOpcode() == ISD::LOAD &&
4727 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4728 (Op.getOpcode() == ISD::MERGE_VALUES &&
4729 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4730 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4731 getOperand(1))))
4732 return true;
4733 return false;
4734}
4735
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004736/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004737/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004738static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4739 TargetLowering& TLI) {
4740 SDNode * Ret = NULL;
4741 SDOperand Terminator = DAG.getRoot();
4742
4743 // Find RET node.
4744 if (Terminator.getOpcode() == ISD::RET) {
4745 Ret = Terminator.Val;
4746 }
4747
4748 // Fix tail call attribute of CALL nodes.
4749 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4750 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4751 if (BI->getOpcode() == ISD::CALL) {
4752 SDOperand OpRet(Ret, 0);
4753 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4754 bool isMarkedTailCall =
4755 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4756 // If CALL node has tail call attribute set to true and the call is not
4757 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004758 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004759 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004760 if (!isMarkedTailCall) continue;
4761 if (Ret==NULL ||
4762 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
4763 // Not eligible. Mark CALL node as non tail call.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004764 SmallVector<SDOperand, 32> Ops;
4765 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004766 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4767 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004768 if (idx!=3)
4769 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004770 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004771 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4772 }
4773 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004774 } else {
4775 // Look for tail call clobbered arguments. Emit a series of
4776 // copyto/copyfrom virtual register nodes to protect them.
4777 SmallVector<SDOperand, 32> Ops;
4778 SDOperand Chain = OpCall.getOperand(0), InFlag;
4779 unsigned idx=0;
4780 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
4781 E = OpCall.Val->op_end(); I != E; I++, idx++) {
4782 SDOperand Arg = *I;
4783 if (idx > 4 && (idx % 2)) {
4784 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
4785 getArgFlags().isByVal();
4786 MachineFunction &MF = DAG.getMachineFunction();
4787 MachineFrameInfo *MFI = MF.getFrameInfo();
4788 if (!isByVal &&
4789 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
4790 MVT::ValueType VT = Arg.getValueType();
4791 unsigned VReg = MF.getRegInfo().
4792 createVirtualRegister(TLI.getRegClassFor(VT));
4793 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
4794 InFlag = Chain.getValue(1);
4795 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
4796 Chain = Arg.getValue(1);
4797 InFlag = Arg.getValue(2);
4798 }
4799 }
4800 Ops.push_back(Arg);
4801 }
4802 // Link in chain of CopyTo/CopyFromReg.
4803 Ops[0] = Chain;
4804 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004805 }
4806 }
4807 }
4808}
4809
Chris Lattner1c08c712005-01-07 07:47:53 +00004810void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4811 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004812 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00004813 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004814
Chris Lattnerbf209482005-10-30 19:42:35 +00004815 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004816 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004817 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00004818
4819 BB = FuncInfo.MBBMap[LLVMBB];
4820 SDL.setCurrentBasicBlock(BB);
4821
Duncan Sandsf4070822007-06-15 19:04:19 +00004822 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004823
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004824 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004825 // Add a label to mark the beginning of the landing pad. Deletion of the
4826 // landing pad can thus be detected via the MachineModuleInfo.
4827 unsigned LabelID = MMI->addLandingPad(BB);
4828 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00004829 DAG.getConstant(LabelID, MVT::i32),
4830 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00004831
Evan Chenge47c3332007-06-27 18:45:32 +00004832 // Mark exception register as live in.
4833 unsigned Reg = TLI.getExceptionAddressRegister();
4834 if (Reg) BB->addLiveIn(Reg);
4835
4836 // Mark exception selector register as live in.
4837 Reg = TLI.getExceptionSelectorRegister();
4838 if (Reg) BB->addLiveIn(Reg);
4839
Duncan Sandsf4070822007-06-15 19:04:19 +00004840 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4841 // function and list of typeids logically belong to the invoke (or, if you
4842 // like, the basic block containing the invoke), and need to be associated
4843 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004844 // information is provided by an intrinsic (eh.selector) that can be moved
4845 // to unexpected places by the optimizers: if the unwind edge is critical,
4846 // then breaking it can result in the intrinsics being in the successor of
4847 // the landing pad, not the landing pad itself. This results in exceptions
4848 // not being caught because no typeids are associated with the invoke.
4849 // This may not be the only way things can go wrong, but it is the only way
4850 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004851 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4852
4853 if (Br && Br->isUnconditional()) { // Critical edge?
4854 BasicBlock::iterator I, E;
4855 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004856 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004857 break;
4858
4859 if (I == E)
4860 // No catch info found - try to extract some from the successor.
4861 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004862 }
4863 }
4864
Chris Lattner1c08c712005-01-07 07:47:53 +00004865 // Lower all of the non-terminator instructions.
4866 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4867 I != E; ++I)
4868 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004869
Chris Lattner1c08c712005-01-07 07:47:53 +00004870 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004871 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004872 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004873 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004874 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004875 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004876 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004877 }
4878
4879 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4880 // ensure constants are generated when needed. Remember the virtual registers
4881 // that need to be added to the Machine PHI nodes as input. We cannot just
4882 // directly add them, because expansion might result in multiple MBB's for one
4883 // BB. As such, the start of the BB might correspond to a different MBB than
4884 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004885 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004886 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004887
4888 // Emit constants only once even if used by multiple PHI nodes.
4889 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004890
Chris Lattner8c494ab2006-10-27 23:50:33 +00004891 // Vector bool would be better, but vector<bool> is really slow.
4892 std::vector<unsigned char> SuccsHandled;
4893 if (TI->getNumSuccessors())
4894 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4895
Dan Gohman532dc2e2007-07-09 20:59:04 +00004896 // Check successor nodes' PHI nodes that expect a constant to be available
4897 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004898 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4899 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004900 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004901 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004902
Chris Lattner8c494ab2006-10-27 23:50:33 +00004903 // If this terminator has multiple identical successors (common for
4904 // switches), only handle each succ once.
4905 unsigned SuccMBBNo = SuccMBB->getNumber();
4906 if (SuccsHandled[SuccMBBNo]) continue;
4907 SuccsHandled[SuccMBBNo] = true;
4908
4909 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004910 PHINode *PN;
4911
4912 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4913 // nodes and Machine PHI nodes, but the incoming operands have not been
4914 // emitted yet.
4915 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004916 (PN = dyn_cast<PHINode>(I)); ++I) {
4917 // Ignore dead phi's.
4918 if (PN->use_empty()) continue;
4919
4920 unsigned Reg;
4921 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004922
Chris Lattner8c494ab2006-10-27 23:50:33 +00004923 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4924 unsigned &RegOut = ConstantsOut[C];
4925 if (RegOut == 0) {
4926 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004927 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00004928 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004929 Reg = RegOut;
4930 } else {
4931 Reg = FuncInfo.ValueMap[PHIOp];
4932 if (Reg == 0) {
4933 assert(isa<AllocaInst>(PHIOp) &&
4934 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4935 "Didn't codegen value into a register!??");
4936 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004937 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00004938 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004939 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004940
4941 // Remember that this register needs to added to the machine PHI node as
4942 // the input for this MBB.
4943 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004944 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004945 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004946 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4947 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004948 }
4949 ConstantsOut.clear();
4950
4951 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004952 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004953
Nate Begemanf15485a2006-03-27 01:32:24 +00004954 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004955 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004956 SwitchCases.clear();
4957 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004958 JTCases.clear();
4959 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004960 BitTestCases.clear();
4961 BitTestCases = SDL.BitTestCases;
4962
Chris Lattnera651cf62005-01-17 19:43:36 +00004963 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004964 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004965
4966 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4967 // with correct tailcall attribute so that the target can rely on the tailcall
4968 // attribute indicating whether the call is really eligible for tail call
4969 // optimization.
4970 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00004971}
4972
Nate Begemanf15485a2006-03-27 01:32:24 +00004973void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00004974 DOUT << "Lowered selection DAG:\n";
4975 DEBUG(DAG.dump());
4976
Chris Lattneraf21d552005-10-10 16:47:10 +00004977 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004978 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004979
Dan Gohman417e11b2007-10-08 15:12:17 +00004980 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004981 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004982
Chris Lattner1c08c712005-01-07 07:47:53 +00004983 // Second step, hack on the DAG until it only uses operations and types that
4984 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00004985#if 0 // Enable this some day.
4986 DAG.LegalizeTypes();
4987 // Someday even later, enable a dag combine pass here.
4988#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00004989 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004990
Bill Wendling832171c2006-12-07 20:04:42 +00004991 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004992 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004993
Chris Lattneraf21d552005-10-10 16:47:10 +00004994 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004995 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004996
Dan Gohman417e11b2007-10-08 15:12:17 +00004997 DOUT << "Optimized legalized selection DAG:\n";
4998 DEBUG(DAG.dump());
4999
Evan Chenga9c20912006-01-21 02:32:06 +00005000 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00005001
Chris Lattnera33ef482005-03-30 01:10:47 +00005002 // Third, instruction select all of the operations to machine code, adding the
5003 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00005004 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00005005
Bill Wendling832171c2006-12-07 20:04:42 +00005006 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005007 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005008}
Chris Lattner1c08c712005-01-07 07:47:53 +00005009
Nate Begemanf15485a2006-03-27 01:32:24 +00005010void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5011 FunctionLoweringInfo &FuncInfo) {
5012 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5013 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005014 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005015 CurDAG = &DAG;
5016
5017 // First step, lower LLVM code to some DAG. This DAG may use operations and
5018 // types that are not supported by the target.
5019 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5020
5021 // Second step, emit the lowered DAG as machine code.
5022 CodeGenAndEmitDAG(DAG);
5023 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005024
5025 DOUT << "Total amount of phi nodes to update: "
5026 << PHINodesToUpdate.size() << "\n";
5027 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5028 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5029 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005030
Chris Lattnera33ef482005-03-30 01:10:47 +00005031 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005032 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005033 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005034 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5035 MachineInstr *PHI = PHINodesToUpdate[i].first;
5036 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5037 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005038 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5039 false));
5040 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005041 }
5042 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005043 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005044
5045 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5046 // Lower header first, if it wasn't already lowered
5047 if (!BitTestCases[i].Emitted) {
5048 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5049 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005050 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005051 // Set the current basic block to the mbb we wish to insert the code into
5052 BB = BitTestCases[i].Parent;
5053 HSDL.setCurrentBasicBlock(BB);
5054 // Emit the code
5055 HSDL.visitBitTestHeader(BitTestCases[i]);
5056 HSDAG.setRoot(HSDL.getRoot());
5057 CodeGenAndEmitDAG(HSDAG);
5058 }
5059
5060 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5061 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5062 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005063 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005064 // Set the current basic block to the mbb we wish to insert the code into
5065 BB = BitTestCases[i].Cases[j].ThisBB;
5066 BSDL.setCurrentBasicBlock(BB);
5067 // Emit the code
5068 if (j+1 != ej)
5069 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5070 BitTestCases[i].Reg,
5071 BitTestCases[i].Cases[j]);
5072 else
5073 BSDL.visitBitTestCase(BitTestCases[i].Default,
5074 BitTestCases[i].Reg,
5075 BitTestCases[i].Cases[j]);
5076
5077
5078 BSDAG.setRoot(BSDL.getRoot());
5079 CodeGenAndEmitDAG(BSDAG);
5080 }
5081
5082 // Update PHI Nodes
5083 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5084 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5085 MachineBasicBlock *PHIBB = PHI->getParent();
5086 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5087 "This is not a machine PHI node that we are updating!");
5088 // This is "default" BB. We have two jumps to it. From "header" BB and
5089 // from last "case" BB.
5090 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005091 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5092 false));
5093 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5094 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5095 false));
5096 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5097 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005098 }
5099 // One of "cases" BB.
5100 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5101 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5102 if (cBB->succ_end() !=
5103 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005104 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5105 false));
5106 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005107 }
5108 }
5109 }
5110 }
5111
Nate Begeman9453eea2006-04-23 06:26:20 +00005112 // If the JumpTable record is filled in, then we need to emit a jump table.
5113 // Updating the PHI nodes is tricky in this case, since we need to determine
5114 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005115 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5116 // Lower header first, if it wasn't already lowered
5117 if (!JTCases[i].first.Emitted) {
5118 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5119 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005120 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005121 // Set the current basic block to the mbb we wish to insert the code into
5122 BB = JTCases[i].first.HeaderBB;
5123 HSDL.setCurrentBasicBlock(BB);
5124 // Emit the code
5125 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5126 HSDAG.setRoot(HSDL.getRoot());
5127 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005128 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005129
5130 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5131 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005132 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00005133 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005134 BB = JTCases[i].second.MBB;
5135 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005136 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005137 JSDL.visitJumpTable(JTCases[i].second);
5138 JSDAG.setRoot(JSDL.getRoot());
5139 CodeGenAndEmitDAG(JSDAG);
5140
Nate Begeman37efe672006-04-22 18:53:45 +00005141 // Update PHI Nodes
5142 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5143 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5144 MachineBasicBlock *PHIBB = PHI->getParent();
5145 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5146 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005147 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005148 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005149 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5150 false));
5151 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005152 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005153 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005154 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005155 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5156 false));
5157 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005158 }
5159 }
Nate Begeman37efe672006-04-22 18:53:45 +00005160 }
5161
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005162 // If the switch block involved a branch to one of the actual successors, we
5163 // need to update PHI nodes in that block.
5164 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5165 MachineInstr *PHI = PHINodesToUpdate[i].first;
5166 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5167 "This is not a machine PHI node that we are updating!");
5168 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005169 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5170 false));
5171 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005172 }
5173 }
5174
Nate Begemanf15485a2006-03-27 01:32:24 +00005175 // If we generated any switch lowering information, build and codegen any
5176 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005177 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005178 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005179 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005180 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005181
Nate Begemanf15485a2006-03-27 01:32:24 +00005182 // Set the current basic block to the mbb we wish to insert the code into
5183 BB = SwitchCases[i].ThisBB;
5184 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005185
Nate Begemanf15485a2006-03-27 01:32:24 +00005186 // Emit the code
5187 SDL.visitSwitchCase(SwitchCases[i]);
5188 SDAG.setRoot(SDL.getRoot());
5189 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005190
5191 // Handle any PHI nodes in successors of this chunk, as if we were coming
5192 // from the original BB before switch expansion. Note that PHI nodes can
5193 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5194 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005195 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005196 for (MachineBasicBlock::iterator Phi = BB->begin();
5197 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5198 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5199 for (unsigned pn = 0; ; ++pn) {
5200 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5201 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005202 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5203 second, false));
5204 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005205 break;
5206 }
5207 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005208 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005209
5210 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005211 if (BB == SwitchCases[i].FalseBB)
5212 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005213
5214 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005215 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005216 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005217 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005218 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005219 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005220}
Evan Chenga9c20912006-01-21 02:32:06 +00005221
Jim Laskey13ec7022006-08-01 14:21:23 +00005222
Evan Chenga9c20912006-01-21 02:32:06 +00005223//===----------------------------------------------------------------------===//
5224/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5225/// target node in the graph.
5226void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5227 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005228
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005229 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005230
5231 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005232 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005233 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005234 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005235
Jim Laskey9ff542f2006-08-01 18:29:48 +00005236 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005237 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005238
5239 if (ViewSUnitDAGs) SL->viewGraph();
5240
Evan Chengcccf1232006-02-04 06:49:00 +00005241 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005242}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005243
Chris Lattner03fc53c2006-03-06 00:22:00 +00005244
Jim Laskey9ff542f2006-08-01 18:29:48 +00005245HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5246 return new HazardRecognizer();
5247}
5248
Chris Lattner75548062006-10-11 03:58:02 +00005249//===----------------------------------------------------------------------===//
5250// Helper functions used by the generated instruction selector.
5251//===----------------------------------------------------------------------===//
5252// Calls to these methods are generated by tblgen.
5253
5254/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5255/// the dag combiner simplified the 255, we still want to match. RHS is the
5256/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5257/// specified in the .td file (e.g. 255).
5258bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005259 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005260 const APInt &ActualMask = RHS->getAPIntValue();
5261 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005262
5263 // If the actual mask exactly matches, success!
5264 if (ActualMask == DesiredMask)
5265 return true;
5266
5267 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005268 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005269 return false;
5270
5271 // Otherwise, the DAG Combiner may have proven that the value coming in is
5272 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005273 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005274 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005275 return true;
5276
5277 // TODO: check to see if missing bits are just not demanded.
5278
5279 // Otherwise, this pattern doesn't match.
5280 return false;
5281}
5282
5283/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5284/// the dag combiner simplified the 255, we still want to match. RHS is the
5285/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5286/// specified in the .td file (e.g. 255).
5287bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005288 int64_t DesiredMaskS) const {
5289 const APInt &ActualMask = RHS->getAPIntValue();
5290 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005291
5292 // If the actual mask exactly matches, success!
5293 if (ActualMask == DesiredMask)
5294 return true;
5295
5296 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005297 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005298 return false;
5299
5300 // Otherwise, the DAG Combiner may have proven that the value coming in is
5301 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005302 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005303
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005304 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005305 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005306
5307 // If all the missing bits in the or are already known to be set, match!
5308 if ((NeededMask & KnownOne) == NeededMask)
5309 return true;
5310
5311 // TODO: check to see if missing bits are just not demanded.
5312
5313 // Otherwise, this pattern doesn't match.
5314 return false;
5315}
5316
Jim Laskey9ff542f2006-08-01 18:29:48 +00005317
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005318/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5319/// by tblgen. Others should not call it.
5320void SelectionDAGISel::
5321SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5322 std::vector<SDOperand> InOps;
5323 std::swap(InOps, Ops);
5324
5325 Ops.push_back(InOps[0]); // input chain.
5326 Ops.push_back(InOps[1]); // input asm string.
5327
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005328 unsigned i = 2, e = InOps.size();
5329 if (InOps[e-1].getValueType() == MVT::Flag)
5330 --e; // Don't process a flag operand if it is here.
5331
5332 while (i != e) {
5333 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5334 if ((Flags & 7) != 4 /*MEM*/) {
5335 // Just skip over this operand, copying the operands verbatim.
5336 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5337 i += (Flags >> 3) + 1;
5338 } else {
5339 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5340 // Otherwise, this is a memory operand. Ask the target to select it.
5341 std::vector<SDOperand> SelOps;
5342 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005343 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005344 exit(1);
5345 }
5346
5347 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00005348 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005349 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005350 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005351 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5352 i += 2;
5353 }
5354 }
5355
5356 // Add the flag input back if present.
5357 if (e != InOps.size())
5358 Ops.push_back(InOps.back());
5359}
Devang Patel794fd752007-05-01 21:15:47 +00005360
Devang Patel19974732007-05-03 01:11:54 +00005361char SelectionDAGISel::ID = 0;