blob: 46b0cf576f435542d51f4fe6c36002bbbf8f8b56 [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 {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000078 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,
156 unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000157 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(1, Reg) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000158 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000159 const SmallVector<unsigned, 4> &regs,
Chris Lattner864635a2006-02-22 22:37:12 +0000160 MVT::ValueType regvt, MVT::ValueType valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000161 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000162 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000163 const SmallVector<unsigned, 4> &regs,
Dan Gohman23ce5022008-04-25 18:27:55 +0000164 const SmallVector<MVT::ValueType, 4> &regvts,
165 const SmallVector<MVT::ValueType, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000166 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000167 RegsForValue(const TargetLowering &tli,
168 unsigned Reg, const Type *Ty) : TLI(&tli) {
169 ComputeValueVTs(tli, Ty, ValueVTs);
170
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000171 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000172 MVT::ValueType ValueVT = ValueVTs[Value];
173 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
174 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
175 for (unsigned i = 0; i != NumRegs; ++i)
176 Regs.push_back(Reg + i);
177 RegVTs.push_back(RegisterVT);
178 Reg += NumRegs;
179 }
Chris Lattner864635a2006-02-22 22:37:12 +0000180 }
181
182 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000183 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000184 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000185 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000186 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000187 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000188
189 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
190 /// specified value into the registers specified by this object. This uses
191 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000192 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000193 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000194 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000195
196 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
197 /// operand list. This adds the code marker and includes the number of
198 /// values added into it.
199 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000200 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000201 };
202}
Evan Cheng4ef10862006-01-23 07:01:07 +0000203
Chris Lattner1c08c712005-01-07 07:47:53 +0000204namespace llvm {
205 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000206 /// createDefaultScheduler - This creates an instruction scheduler appropriate
207 /// for the target.
208 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
209 SelectionDAG *DAG,
210 MachineBasicBlock *BB) {
211 TargetLowering &TLI = IS->getTargetLowering();
212
213 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
214 return createTDListDAGScheduler(IS, DAG, BB);
215 } else {
216 assert(TLI.getSchedulingPreference() ==
217 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
218 return createBURRListDAGScheduler(IS, DAG, BB);
219 }
220 }
221
222
223 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000224 /// FunctionLoweringInfo - This contains information that is global to a
225 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000226 class FunctionLoweringInfo {
227 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 TargetLowering &TLI;
229 Function &Fn;
230 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000231 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000232
233 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
234
235 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
236 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
237
238 /// ValueMap - Since we emit code for the function a basic block at a time,
239 /// we must remember which virtual registers hold the values for
240 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000241 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000242
243 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
244 /// the entry block. This allows the allocas to be efficiently referenced
245 /// anywhere in the function.
246 std::map<const AllocaInst*, int> StaticAllocaMap;
247
Duncan Sandsf4070822007-06-15 19:04:19 +0000248#ifndef NDEBUG
249 SmallSet<Instruction*, 8> CatchInfoLost;
250 SmallSet<Instruction*, 8> CatchInfoFound;
251#endif
252
Chris Lattner1c08c712005-01-07 07:47:53 +0000253 unsigned MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000254 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000255 }
Chris Lattner571e4342006-10-27 21:36:01 +0000256
257 /// isExportedInst - Return true if the specified value is an instruction
258 /// exported from its block.
259 bool isExportedInst(const Value *V) {
260 return ValueMap.count(V);
261 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000262
Chris Lattner3c384492006-03-16 19:51:18 +0000263 unsigned CreateRegForValue(const Value *V);
264
Chris Lattner1c08c712005-01-07 07:47:53 +0000265 unsigned InitializeRegForValue(const Value *V) {
266 unsigned &R = ValueMap[V];
267 assert(R == 0 && "Already initialized this value register!");
268 return R = CreateRegForValue(V);
269 }
270 };
271}
272
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000273/// isSelector - Return true if this instruction is a call to the
274/// eh.selector intrinsic.
275static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000276 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000277 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
278 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000279 return false;
280}
281
Chris Lattner1c08c712005-01-07 07:47:53 +0000282/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000283/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000284/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000285static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
286 if (isa<PHINode>(I)) return true;
287 BasicBlock *BB = I->getParent();
288 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000289 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000290 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000291 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000292 return true;
293 return false;
294}
295
Chris Lattnerbf209482005-10-30 19:42:35 +0000296/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000297/// entry block, return true. This includes arguments used by switches, since
298/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000299static bool isOnlyUsedInEntryBlock(Argument *A) {
300 BasicBlock *Entry = A->getParent()->begin();
301 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000302 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000303 return false; // Use not in entry block.
304 return true;
305}
306
Chris Lattner1c08c712005-01-07 07:47:53 +0000307FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000308 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000309 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000310
Chris Lattnerbf209482005-10-30 19:42:35 +0000311 // Create a vreg for each argument register that is not dead and is used
312 // outside of the entry block for the function.
313 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
314 AI != E; ++AI)
315 if (!isOnlyUsedInEntryBlock(AI))
316 InitializeRegForValue(AI);
317
Chris Lattner1c08c712005-01-07 07:47:53 +0000318 // Initialize the mapping of values to registers. This is only set up for
319 // instruction values that are used outside of the block that defines
320 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000321 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000322 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
323 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000324 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000325 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000326 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000327 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000328 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000329 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000330
Reid Spencerb83eb642006-10-20 07:07:24 +0000331 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000332 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000333 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000334 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000335 }
336
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000337 for (; BB != EB; ++BB)
338 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000339 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
340 if (!isa<AllocaInst>(I) ||
341 !StaticAllocaMap.count(cast<AllocaInst>(I)))
342 InitializeRegForValue(I);
343
344 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
345 // also creates the initial PHI MachineInstrs, though none of the input
346 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000347 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000348 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
349 MBBMap[BB] = MBB;
350 MF.getBasicBlockList().push_back(MBB);
351
352 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
353 // appropriate.
354 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000355 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
356 if (PN->use_empty()) continue;
357
358 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000359 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000360 unsigned PHIReg = ValueMap[PN];
361 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000362 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000363 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000364 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000365 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000366 }
367}
368
Chris Lattner3c384492006-03-16 19:51:18 +0000369/// CreateRegForValue - Allocate the appropriate number of virtual registers of
370/// the correctly promoted or expanded types. Assign these registers
371/// consecutive vreg numbers and return the first assigned number.
372unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000373 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000374 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000375
Dan Gohman23ce5022008-04-25 18:27:55 +0000376 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000377 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000378 MVT::ValueType ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000379 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000380
Chris Lattnerb606dba2008-04-28 06:44:42 +0000381 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000382 for (unsigned i = 0; i != NumRegs; ++i) {
383 unsigned R = MakeReg(RegisterVT);
384 if (!FirstReg) FirstReg = R;
385 }
386 }
387 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000388}
Chris Lattner1c08c712005-01-07 07:47:53 +0000389
390//===----------------------------------------------------------------------===//
391/// SelectionDAGLowering - This is the common target-independent lowering
392/// implementation that is parameterized by a TargetLowering object.
393/// Also, targets can overload any lowering method.
394///
395namespace llvm {
396class SelectionDAGLowering {
397 MachineBasicBlock *CurMBB;
398
Chris Lattner0da331f2007-02-04 01:31:47 +0000399 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000400
Chris Lattnerd3948112005-01-17 22:19:26 +0000401 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
402 /// them up and then emit token factor nodes when possible. This allows us to
403 /// get simple disambiguation between loads without worrying about alias
404 /// analysis.
405 std::vector<SDOperand> PendingLoads;
406
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000407 /// PendingExports - CopyToReg nodes that copy values to virtual registers
408 /// for export to other blocks need to be emitted before any terminator
409 /// instruction, but they have no other ordering requirements. We bunch them
410 /// up and the emit a single tokenfactor for them just before terminator
411 /// instructions.
412 std::vector<SDOperand> PendingExports;
413
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000414 /// Case - A struct to record the Value for a switch case, and the
415 /// case's target basic block.
416 struct Case {
417 Constant* Low;
418 Constant* High;
419 MachineBasicBlock* BB;
420
421 Case() : Low(0), High(0), BB(0) { }
422 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
423 Low(low), High(high), BB(bb) { }
424 uint64_t size() const {
425 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
426 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
427 return (rHigh - rLow + 1ULL);
428 }
429 };
430
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000431 struct CaseBits {
432 uint64_t Mask;
433 MachineBasicBlock* BB;
434 unsigned Bits;
435
436 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
437 Mask(mask), BB(bb), Bits(bits) { }
438 };
439
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000440 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000441 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000442 typedef CaseVector::iterator CaseItr;
443 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000444
445 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
446 /// of conditional branches.
447 struct CaseRec {
448 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
449 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
450
451 /// CaseBB - The MBB in which to emit the compare and branch
452 MachineBasicBlock *CaseBB;
453 /// LT, GE - If nonzero, we know the current case value must be less-than or
454 /// greater-than-or-equal-to these Constants.
455 Constant *LT;
456 Constant *GE;
457 /// Range - A pair of iterators representing the range of case values to be
458 /// processed at this point in the binary search tree.
459 CaseRange Range;
460 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000461
462 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000463
464 /// The comparison function for sorting the switch case values in the vector.
465 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000466 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000467 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000468 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
469 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
470 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
471 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000472 }
473 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000474
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000475 struct CaseBitsCmp {
476 bool operator () (const CaseBits& C1, const CaseBits& C2) {
477 return C1.Bits > C2.Bits;
478 }
479 };
480
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000481 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000482
Chris Lattner1c08c712005-01-07 07:47:53 +0000483public:
484 // TLI - This is information that describes the available target features we
485 // need for lowering. This indicates when operations are unavailable,
486 // implemented with a libcall, etc.
487 TargetLowering &TLI;
488 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000489 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000490 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000491
Nate Begemanf15485a2006-03-27 01:32:24 +0000492 /// SwitchCases - Vector of CaseBlock structures used to communicate
493 /// SwitchInst code generation information.
494 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000495 /// JTCases - Vector of JumpTable structures used to communicate
496 /// SwitchInst code generation information.
497 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000498 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000499
Chris Lattner1c08c712005-01-07 07:47:53 +0000500 /// FuncInfo - Information about the function as a whole.
501 ///
502 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000503
504 /// GCI - Garbage collection metadata for the function.
505 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000506
507 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000508 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000509 FunctionLoweringInfo &funcinfo,
510 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000511 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000512 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000513 }
514
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000515 /// getRoot - Return the current virtual root of the Selection DAG,
516 /// flushing any PendingLoad items. This must be done before emitting
517 /// a store or any other node that may need to be ordered after any
518 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000519 ///
520 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000521 if (PendingLoads.empty())
522 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000523
Chris Lattnerd3948112005-01-17 22:19:26 +0000524 if (PendingLoads.size() == 1) {
525 SDOperand Root = PendingLoads[0];
526 DAG.setRoot(Root);
527 PendingLoads.clear();
528 return Root;
529 }
530
531 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000532 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
533 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000534 PendingLoads.clear();
535 DAG.setRoot(Root);
536 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000537 }
538
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000539 /// getControlRoot - Similar to getRoot, but instead of flushing all the
540 /// PendingLoad items, flush all the PendingExports items. It is necessary
541 /// to do this before emitting a terminator instruction.
542 ///
543 SDOperand getControlRoot() {
544 SDOperand Root = DAG.getRoot();
545
546 if (PendingExports.empty())
547 return Root;
548
549 // Turn all of the CopyToReg chains into one factored node.
550 if (Root.getOpcode() != ISD::EntryToken) {
551 unsigned i = 0, e = PendingExports.size();
552 for (; i != e; ++i) {
553 assert(PendingExports[i].Val->getNumOperands() > 1);
554 if (PendingExports[i].Val->getOperand(0) == Root)
555 break; // Don't add the root if we already indirectly depend on it.
556 }
557
558 if (i == e)
559 PendingExports.push_back(Root);
560 }
561
562 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
563 &PendingExports[0],
564 PendingExports.size());
565 PendingExports.clear();
566 DAG.setRoot(Root);
567 return Root;
568 }
569
570 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000571
Chris Lattner1c08c712005-01-07 07:47:53 +0000572 void visit(Instruction &I) { visit(I.getOpcode(), I); }
573
574 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000575 // Note: this doesn't use InstVisitor, because it has to work with
576 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000577 switch (Opcode) {
578 default: assert(0 && "Unknown instruction type encountered!");
579 abort();
580 // Build the switch statement using the Instruction.def file.
581#define HANDLE_INST(NUM, OPCODE, CLASS) \
582 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
583#include "llvm/Instruction.def"
584 }
585 }
586
587 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
588
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000589 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000590 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000591 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000592
Chris Lattner199862b2006-03-16 19:57:50 +0000593 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000594
Chris Lattner0da331f2007-02-04 01:31:47 +0000595 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000596 SDOperand &N = NodeMap[V];
597 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000598 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000599 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000600
Evan Cheng5c807602008-02-26 02:33:44 +0000601 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000602 std::set<unsigned> &OutputRegs,
603 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000604
Chris Lattner571e4342006-10-27 21:36:01 +0000605 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
606 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
607 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000608 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000609 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000610 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000611 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000612
Chris Lattner1c08c712005-01-07 07:47:53 +0000613 // Terminator instructions.
614 void visitRet(ReturnInst &I);
615 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000616 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000617 void visitUnreachable(UnreachableInst &I) { /* noop */ }
618
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000619 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000620 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000621 CaseRecVector& WorkList,
622 Value* SV,
623 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000624 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000625 CaseRecVector& WorkList,
626 Value* SV,
627 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000628 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000629 CaseRecVector& WorkList,
630 Value* SV,
631 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000632 bool handleBitTestsSwitchCase(CaseRec& CR,
633 CaseRecVector& WorkList,
634 Value* SV,
635 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000636 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000637 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
638 void visitBitTestCase(MachineBasicBlock* NextMBB,
639 unsigned Reg,
640 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000641 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000642 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
643 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000644
Chris Lattner1c08c712005-01-07 07:47:53 +0000645 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000646 void visitInvoke(InvokeInst &I);
647 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000648
Dan Gohman7f321562007-06-25 16:23:39 +0000649 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000650 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000651 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000652 if (I.getType()->isFPOrFPVector())
653 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000654 else
Dan Gohman7f321562007-06-25 16:23:39 +0000655 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000656 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000657 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000658 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000659 if (I.getType()->isFPOrFPVector())
660 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000661 else
Dan Gohman7f321562007-06-25 16:23:39 +0000662 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000663 }
Dan Gohman7f321562007-06-25 16:23:39 +0000664 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
665 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
666 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
667 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
668 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
669 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
670 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
671 void visitOr (User &I) { visitBinary(I, ISD::OR); }
672 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000673 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000674 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
675 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000676 void visitICmp(User &I);
677 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000678 // Visit the conversion instructions
679 void visitTrunc(User &I);
680 void visitZExt(User &I);
681 void visitSExt(User &I);
682 void visitFPTrunc(User &I);
683 void visitFPExt(User &I);
684 void visitFPToUI(User &I);
685 void visitFPToSI(User &I);
686 void visitUIToFP(User &I);
687 void visitSIToFP(User &I);
688 void visitPtrToInt(User &I);
689 void visitIntToPtr(User &I);
690 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000691
Chris Lattner2bbd8102006-03-29 00:11:43 +0000692 void visitExtractElement(User &I);
693 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000694 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000695
Chris Lattner1c08c712005-01-07 07:47:53 +0000696 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000697 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000698
699 void visitMalloc(MallocInst &I);
700 void visitFree(FreeInst &I);
701 void visitAlloca(AllocaInst &I);
702 void visitLoad(LoadInst &I);
703 void visitStore(StoreInst &I);
704 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
705 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000706 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000707 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000708 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000709
Chris Lattner1c08c712005-01-07 07:47:53 +0000710 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000711 void visitVAArg(VAArgInst &I);
712 void visitVAEnd(CallInst &I);
713 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000714
Dan Gohmanef5d1942008-03-11 21:11:25 +0000715 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000716
Chris Lattner1c08c712005-01-07 07:47:53 +0000717 void visitUserOp1(Instruction &I) {
718 assert(0 && "UserOp1 should not exist at instruction selection time!");
719 abort();
720 }
721 void visitUserOp2(Instruction &I) {
722 assert(0 && "UserOp2 should not exist at instruction selection time!");
723 abort();
724 }
725};
726} // end namespace llvm
727
Dan Gohman6183f782007-07-05 20:12:34 +0000728
Duncan Sandsb988bac2008-02-11 20:58:28 +0000729/// getCopyFromParts - Create a value that contains the specified legal parts
730/// combined into the value they represent. If the parts combine to a type
731/// larger then ValueVT then AssertOp can be used to specify whether the extra
732/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000733/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000734static SDOperand getCopyFromParts(SelectionDAG &DAG,
735 const SDOperand *Parts,
736 unsigned NumParts,
737 MVT::ValueType PartVT,
738 MVT::ValueType ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000739 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000740 assert(NumParts > 0 && "No parts to assemble!");
741 TargetLowering &TLI = DAG.getTargetLoweringInfo();
742 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000743
Duncan Sands014e04a2008-02-12 20:46:31 +0000744 if (NumParts > 1) {
745 // Assemble the value from multiple parts.
746 if (!MVT::isVector(ValueVT)) {
747 unsigned PartBits = MVT::getSizeInBits(PartVT);
748 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000749
Duncan Sands014e04a2008-02-12 20:46:31 +0000750 // Assemble the power of 2 part.
751 unsigned RoundParts = NumParts & (NumParts - 1) ?
752 1 << Log2_32(NumParts) : NumParts;
753 unsigned RoundBits = PartBits * RoundParts;
754 MVT::ValueType RoundVT = RoundBits == ValueBits ?
755 ValueVT : MVT::getIntegerType(RoundBits);
756 SDOperand Lo, Hi;
757
758 if (RoundParts > 2) {
759 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
760 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
761 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
762 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000763 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000764 Lo = Parts[0];
765 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000766 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000767 if (TLI.isBigEndian())
768 std::swap(Lo, Hi);
769 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
770
771 if (RoundParts < NumParts) {
772 // Assemble the trailing non-power-of-2 part.
773 unsigned OddParts = NumParts - RoundParts;
774 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
775 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
776
777 // Combine the round and odd parts.
778 Lo = Val;
779 if (TLI.isBigEndian())
780 std::swap(Lo, Hi);
781 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
782 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
783 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
784 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
785 TLI.getShiftAmountTy()));
786 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
787 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
788 }
789 } else {
790 // Handle a multi-element vector.
791 MVT::ValueType IntermediateVT, RegisterVT;
792 unsigned NumIntermediates;
793 unsigned NumRegs =
794 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
795 RegisterVT);
796
797 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
798 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
799 assert(RegisterVT == Parts[0].getValueType() &&
800 "Part type doesn't match part!");
801
802 // Assemble the parts into intermediate operands.
803 SmallVector<SDOperand, 8> Ops(NumIntermediates);
804 if (NumIntermediates == NumParts) {
805 // If the register was not expanded, truncate or copy the value,
806 // as appropriate.
807 for (unsigned i = 0; i != NumParts; ++i)
808 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
809 PartVT, IntermediateVT);
810 } else if (NumParts > 0) {
811 // If the intermediate type was expanded, build the intermediate operands
812 // from the parts.
813 assert(NumParts % NumIntermediates == 0 &&
814 "Must expand into a divisible number of parts!");
815 unsigned Factor = NumParts / NumIntermediates;
816 for (unsigned i = 0; i != NumIntermediates; ++i)
817 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
818 PartVT, IntermediateVT);
819 }
820
821 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
822 // operands.
823 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
824 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
825 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000826 }
Dan Gohman6183f782007-07-05 20:12:34 +0000827 }
828
Duncan Sands014e04a2008-02-12 20:46:31 +0000829 // There is now one part, held in Val. Correct it to match ValueVT.
830 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000831
Duncan Sands014e04a2008-02-12 20:46:31 +0000832 if (PartVT == ValueVT)
833 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000834
Duncan Sands014e04a2008-02-12 20:46:31 +0000835 if (MVT::isVector(PartVT)) {
836 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
837 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000838 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000839
840 if (MVT::isVector(ValueVT)) {
841 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
842 MVT::getVectorNumElements(ValueVT) == 1 &&
843 "Only trivial scalar-to-vector conversions should get here!");
844 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
845 }
846
847 if (MVT::isInteger(PartVT) &&
848 MVT::isInteger(ValueVT)) {
849 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
850 // For a truncate, see if we have any information to
851 // indicate whether the truncated bits will always be
852 // zero or sign-extension.
853 if (AssertOp != ISD::DELETED_NODE)
854 Val = DAG.getNode(AssertOp, PartVT, Val,
855 DAG.getValueType(ValueVT));
856 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
857 } else {
858 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
859 }
860 }
861
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000862 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
863 if (ValueVT < Val.getValueType())
Chris Lattner4468c1f2008-03-09 09:38:46 +0000864 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000865 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000866 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000867 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
868 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000869
870 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
871 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
872
873 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000874 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000875}
876
Duncan Sandsb988bac2008-02-11 20:58:28 +0000877/// getCopyToParts - Create a series of nodes that contain the specified value
878/// split into legal parts. If the parts contain more bits than Val, then, for
879/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000880static void getCopyToParts(SelectionDAG &DAG,
881 SDOperand Val,
882 SDOperand *Parts,
883 unsigned NumParts,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000884 MVT::ValueType PartVT,
885 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000886 TargetLowering &TLI = DAG.getTargetLoweringInfo();
887 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohman6183f782007-07-05 20:12:34 +0000888 MVT::ValueType ValueVT = Val.getValueType();
Duncan Sands014e04a2008-02-12 20:46:31 +0000889 unsigned PartBits = MVT::getSizeInBits(PartVT);
890 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000891
Duncan Sands014e04a2008-02-12 20:46:31 +0000892 if (!NumParts)
893 return;
894
895 if (!MVT::isVector(ValueVT)) {
896 if (PartVT == ValueVT) {
897 assert(NumParts == 1 && "No-op copy with multiple parts!");
898 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000899 return;
900 }
901
Duncan Sands014e04a2008-02-12 20:46:31 +0000902 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
903 // If the parts cover more bits than the value has, promote the value.
904 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
905 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000906 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000907 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
908 ValueVT = MVT::getIntegerType(NumParts * PartBits);
909 Val = DAG.getNode(ExtendKind, ValueVT, Val);
910 } else {
911 assert(0 && "Unknown mismatch!");
912 }
913 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
914 // Different types of the same size.
915 assert(NumParts == 1 && PartVT != ValueVT);
916 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
917 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
918 // If the parts cover less bits than value has, truncate the value.
919 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
920 ValueVT = MVT::getIntegerType(NumParts * PartBits);
921 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000922 } else {
923 assert(0 && "Unknown mismatch!");
924 }
925 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000926
927 // The value may have changed - recompute ValueVT.
928 ValueVT = Val.getValueType();
929 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
930 "Failed to tile the value with PartVT!");
931
932 if (NumParts == 1) {
933 assert(PartVT == ValueVT && "Type conversion failed!");
934 Parts[0] = Val;
935 return;
936 }
937
938 // Expand the value into multiple parts.
939 if (NumParts & (NumParts - 1)) {
940 // The number of parts is not a power of 2. Split off and copy the tail.
941 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
942 "Do not know what to expand to!");
943 unsigned RoundParts = 1 << Log2_32(NumParts);
944 unsigned RoundBits = RoundParts * PartBits;
945 unsigned OddParts = NumParts - RoundParts;
946 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
947 DAG.getConstant(RoundBits,
948 TLI.getShiftAmountTy()));
949 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
950 if (TLI.isBigEndian())
951 // The odd parts were reversed by getCopyToParts - unreverse them.
952 std::reverse(Parts + RoundParts, Parts + NumParts);
953 NumParts = RoundParts;
954 ValueVT = MVT::getIntegerType(NumParts * PartBits);
955 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
956 }
957
958 // The number of parts is a power of 2. Repeatedly bisect the value using
959 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +0000960 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
961 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
962 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000963 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
964 for (unsigned i = 0; i < NumParts; i += StepSize) {
965 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands25eb0432008-03-12 20:30:08 +0000966 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
967 SDOperand &Part0 = Parts[i];
968 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +0000969
Duncan Sands25eb0432008-03-12 20:30:08 +0000970 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
971 DAG.getConstant(1, PtrVT));
972 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
973 DAG.getConstant(0, PtrVT));
974
975 if (ThisBits == PartBits && ThisVT != PartVT) {
976 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
977 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
978 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000979 }
980 }
981
982 if (TLI.isBigEndian())
983 std::reverse(Parts, Parts + NumParts);
984
985 return;
986 }
987
988 // Vector ValueVT.
989 if (NumParts == 1) {
990 if (PartVT != ValueVT) {
991 if (MVT::isVector(PartVT)) {
992 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
993 } else {
994 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
995 MVT::getVectorNumElements(ValueVT) == 1 &&
996 "Only trivial vector-to-scalar conversions should get here!");
997 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
998 DAG.getConstant(0, PtrVT));
999 }
1000 }
1001
Dan Gohman6183f782007-07-05 20:12:34 +00001002 Parts[0] = Val;
1003 return;
1004 }
1005
1006 // Handle a multi-element vector.
1007 MVT::ValueType IntermediateVT, RegisterVT;
1008 unsigned NumIntermediates;
1009 unsigned NumRegs =
1010 DAG.getTargetLoweringInfo()
1011 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1012 RegisterVT);
1013 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1014
1015 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1016 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1017
1018 // Split the vector into intermediate operands.
1019 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1020 for (unsigned i = 0; i != NumIntermediates; ++i)
1021 if (MVT::isVector(IntermediateVT))
1022 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1023 IntermediateVT, Val,
1024 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001025 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001026 else
1027 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1028 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001029 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001030
1031 // Split the intermediate operands into legal parts.
1032 if (NumParts == NumIntermediates) {
1033 // If the register was not expanded, promote or copy the value,
1034 // as appropriate.
1035 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001036 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001037 } else if (NumParts > 0) {
1038 // If the intermediate type was expanded, split each the value into
1039 // legal parts.
1040 assert(NumParts % NumIntermediates == 0 &&
1041 "Must expand into a divisible number of parts!");
1042 unsigned Factor = NumParts / NumIntermediates;
1043 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001044 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001045 }
1046}
1047
1048
Chris Lattner199862b2006-03-16 19:57:50 +00001049SDOperand SelectionDAGLowering::getValue(const Value *V) {
1050 SDOperand &N = NodeMap[V];
1051 if (N.Val) return N;
1052
Chris Lattner199862b2006-03-16 19:57:50 +00001053 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Chris Lattner6833b062008-04-28 07:16:35 +00001054 MVT::ValueType VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001055
1056 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1057 return N = DAG.getConstant(CI->getValue(), VT);
1058
1059 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001060 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001061
1062 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001063 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001064
1065 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1066 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1067
Chris Lattner6833b062008-04-28 07:16:35 +00001068 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1069 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001070
1071 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1072 visit(CE->getOpcode(), *CE);
1073 SDOperand N1 = NodeMap[V];
1074 assert(N1.Val && "visit didn't populate the ValueMap!");
1075 return N1;
1076 }
1077
Chris Lattner6833b062008-04-28 07:16:35 +00001078 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001079 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001080
Chris Lattner6833b062008-04-28 07:16:35 +00001081 // Now that we know the number and type of the elements, get that number of
1082 // elements into the Ops array based on what kind of constant it is.
1083 SmallVector<SDOperand, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001084 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1085 for (unsigned i = 0; i != NumElements; ++i)
1086 Ops.push_back(getValue(CP->getOperand(i)));
1087 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001088 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1089 "Unknown vector constant!");
1090 MVT::ValueType EltVT = TLI.getValueType(VecTy->getElementType());
1091
Chris Lattnerb606dba2008-04-28 06:44:42 +00001092 SDOperand Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001093 if (isa<UndefValue>(C))
1094 Op = DAG.getNode(ISD::UNDEF, EltVT);
1095 else if (MVT::isFloatingPoint(EltVT))
1096 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001097 else
Chris Lattner6833b062008-04-28 07:16:35 +00001098 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001099 Ops.assign(NumElements, Op);
1100 }
1101
1102 // Create a BUILD_VECTOR node.
1103 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001104 }
1105
Chris Lattnerb606dba2008-04-28 06:44:42 +00001106 // If this is a static alloca, generate it as the frameindex instead of
1107 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001108 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1109 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001110 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001111 if (SI != FuncInfo.StaticAllocaMap.end())
1112 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1113 }
1114
Chris Lattner251db182007-02-25 18:40:32 +00001115 unsigned InReg = FuncInfo.ValueMap[V];
1116 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001117
Chris Lattner6833b062008-04-28 07:16:35 +00001118 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001119 SDOperand Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001120 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001121}
1122
1123
Chris Lattner1c08c712005-01-07 07:47:53 +00001124void SelectionDAGLowering::visitRet(ReturnInst &I) {
1125 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001126 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001127 return;
1128 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001129
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001130 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001131 NewValues.push_back(getControlRoot());
1132 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001133 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001134 MVT::ValueType VT = RetOp.getValueType();
1135
Evan Cheng8e7d0562006-05-26 23:09:09 +00001136 // FIXME: C calling convention requires the return type to be promoted to
1137 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sandsb988bac2008-02-11 20:58:28 +00001138 if (MVT::isInteger(VT)) {
1139 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1140 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1141 VT = MinVT;
1142 }
1143
1144 unsigned NumParts = TLI.getNumRegisters(VT);
1145 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1146 SmallVector<SDOperand, 4> Parts(NumParts);
1147 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1148
1149 const Function *F = I.getParent()->getParent();
1150 if (F->paramHasAttr(0, ParamAttr::SExt))
1151 ExtendKind = ISD::SIGN_EXTEND;
1152 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1153 ExtendKind = ISD::ZERO_EXTEND;
1154
1155 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1156
1157 for (unsigned i = 0; i < NumParts; ++i) {
1158 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001159 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001160 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001161 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001162 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1163 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001164}
1165
Chris Lattner571e4342006-10-27 21:36:01 +00001166/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1167/// the current basic block, add it to ValueMap now so that we'll get a
1168/// CopyTo/FromReg.
1169void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1170 // No need to export constants.
1171 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1172
1173 // Already exported?
1174 if (FuncInfo.isExportedInst(V)) return;
1175
1176 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001177 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001178}
1179
Chris Lattner8c494ab2006-10-27 23:50:33 +00001180bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1181 const BasicBlock *FromBB) {
1182 // The operands of the setcc have to be in this block. We don't know
1183 // how to export them from some other block.
1184 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1185 // Can export from current BB.
1186 if (VI->getParent() == FromBB)
1187 return true;
1188
1189 // Is already exported, noop.
1190 return FuncInfo.isExportedInst(V);
1191 }
1192
1193 // If this is an argument, we can export it if the BB is the entry block or
1194 // if it is already exported.
1195 if (isa<Argument>(V)) {
1196 if (FromBB == &FromBB->getParent()->getEntryBlock())
1197 return true;
1198
1199 // Otherwise, can only export this if it is already exported.
1200 return FuncInfo.isExportedInst(V);
1201 }
1202
1203 // Otherwise, constants can always be exported.
1204 return true;
1205}
1206
Chris Lattner6a586c82006-10-29 21:01:20 +00001207static bool InBlock(const Value *V, const BasicBlock *BB) {
1208 if (const Instruction *I = dyn_cast<Instruction>(V))
1209 return I->getParent() == BB;
1210 return true;
1211}
1212
Chris Lattner571e4342006-10-27 21:36:01 +00001213/// FindMergedConditions - If Cond is an expression like
1214void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1215 MachineBasicBlock *TBB,
1216 MachineBasicBlock *FBB,
1217 MachineBasicBlock *CurBB,
1218 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001219 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001220 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001221
Reid Spencere4d87aa2006-12-23 06:05:41 +00001222 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1223 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001224 BOp->getParent() != CurBB->getBasicBlock() ||
1225 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1226 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001227 const BasicBlock *BB = CurBB->getBasicBlock();
1228
Reid Spencere4d87aa2006-12-23 06:05:41 +00001229 // If the leaf of the tree is a comparison, merge the condition into
1230 // the caseblock.
1231 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1232 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001233 // how to export them from some other block. If this is the first block
1234 // of the sequence, no exporting is needed.
1235 (CurBB == CurMBB ||
1236 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1237 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001238 BOp = cast<Instruction>(Cond);
1239 ISD::CondCode Condition;
1240 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1241 switch (IC->getPredicate()) {
1242 default: assert(0 && "Unknown icmp predicate opcode!");
1243 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1244 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1245 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1246 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1247 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1248 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1249 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1250 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1251 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1252 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1253 }
1254 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1255 ISD::CondCode FPC, FOC;
1256 switch (FC->getPredicate()) {
1257 default: assert(0 && "Unknown fcmp predicate opcode!");
1258 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1259 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1260 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1261 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1262 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1263 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1264 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1265 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1266 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1267 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1268 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1269 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1270 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1271 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1272 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1273 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1274 }
1275 if (FiniteOnlyFPMath())
1276 Condition = FOC;
1277 else
1278 Condition = FPC;
1279 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001280 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001281 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001282 }
1283
Chris Lattner571e4342006-10-27 21:36:01 +00001284 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001285 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001286 SwitchCases.push_back(CB);
1287 return;
1288 }
1289
1290 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001291 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001292 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001293 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001294 return;
1295 }
1296
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001297
1298 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001299 MachineFunction::iterator BBI = CurBB;
1300 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1301 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1302
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001303 if (Opc == Instruction::Or) {
1304 // Codegen X | Y as:
1305 // jmp_if_X TBB
1306 // jmp TmpBB
1307 // TmpBB:
1308 // jmp_if_Y TBB
1309 // jmp FBB
1310 //
Chris Lattner571e4342006-10-27 21:36:01 +00001311
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001312 // Emit the LHS condition.
1313 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1314
1315 // Emit the RHS condition into TmpBB.
1316 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1317 } else {
1318 assert(Opc == Instruction::And && "Unknown merge op!");
1319 // Codegen X & Y as:
1320 // jmp_if_X TmpBB
1321 // jmp FBB
1322 // TmpBB:
1323 // jmp_if_Y TBB
1324 // jmp FBB
1325 //
1326 // This requires creation of TmpBB after CurBB.
1327
1328 // Emit the LHS condition.
1329 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1330
1331 // Emit the RHS condition into TmpBB.
1332 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1333 }
Chris Lattner571e4342006-10-27 21:36:01 +00001334}
1335
Chris Lattnerdf19f272006-10-31 22:37:42 +00001336/// If the set of cases should be emitted as a series of branches, return true.
1337/// If we should emit this as a bunch of and/or'd together conditions, return
1338/// false.
1339static bool
1340ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1341 if (Cases.size() != 2) return true;
1342
Chris Lattner0ccb5002006-10-31 23:06:00 +00001343 // If this is two comparisons of the same values or'd or and'd together, they
1344 // will get folded into a single comparison, so don't emit two blocks.
1345 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1346 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1347 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1348 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1349 return false;
1350 }
1351
Chris Lattnerdf19f272006-10-31 22:37:42 +00001352 return true;
1353}
1354
Chris Lattner1c08c712005-01-07 07:47:53 +00001355void SelectionDAGLowering::visitBr(BranchInst &I) {
1356 // Update machine-CFG edges.
1357 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001358
1359 // Figure out which block is immediately after the current one.
1360 MachineBasicBlock *NextBlock = 0;
1361 MachineFunction::iterator BBI = CurMBB;
1362 if (++BBI != CurMBB->getParent()->end())
1363 NextBlock = BBI;
1364
1365 if (I.isUnconditional()) {
1366 // If this is not a fall-through branch, emit the branch.
1367 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001368 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001369 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001370
Chris Lattner57ab6592006-10-24 17:57:59 +00001371 // Update machine-CFG edges.
1372 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner57ab6592006-10-24 17:57:59 +00001373 return;
1374 }
1375
1376 // If this condition is one of the special cases we handle, do special stuff
1377 // now.
1378 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001379 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001380
1381 // If this is a series of conditions that are or'd or and'd together, emit
1382 // this as a sequence of branches instead of setcc's with and/or operations.
1383 // For example, instead of something like:
1384 // cmp A, B
1385 // C = seteq
1386 // cmp D, E
1387 // F = setle
1388 // or C, F
1389 // jnz foo
1390 // Emit:
1391 // cmp A, B
1392 // je foo
1393 // cmp D, E
1394 // jle foo
1395 //
1396 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1397 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001398 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001399 BOp->getOpcode() == Instruction::Or)) {
1400 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001401 // If the compares in later blocks need to use values not currently
1402 // exported from this block, export them now. This block should always
1403 // be the first entry.
1404 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1405
Chris Lattnerdf19f272006-10-31 22:37:42 +00001406 // Allow some cases to be rejected.
1407 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001408 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1409 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1410 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1411 }
1412
1413 // Emit the branch for this block.
1414 visitSwitchCase(SwitchCases[0]);
1415 SwitchCases.erase(SwitchCases.begin());
1416 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001417 }
1418
Chris Lattner0ccb5002006-10-31 23:06:00 +00001419 // Okay, we decided not to do this, remove any inserted MBB's and clear
1420 // SwitchCases.
1421 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1422 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1423
Chris Lattnerdf19f272006-10-31 22:37:42 +00001424 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001425 }
1426 }
Chris Lattner24525952006-10-24 18:07:37 +00001427
1428 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001429 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001430 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001431 // Use visitSwitchCase to actually insert the fast branch sequence for this
1432 // cond branch.
1433 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001434}
1435
Nate Begemanf15485a2006-03-27 01:32:24 +00001436/// visitSwitchCase - Emits the necessary code to represent a single node in
1437/// the binary search tree resulting from lowering a switch instruction.
1438void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001439 SDOperand Cond;
1440 SDOperand CondLHS = getValue(CB.CmpLHS);
1441
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001442 // Build the setcc now.
1443 if (CB.CmpMHS == NULL) {
1444 // Fold "(X == true)" to X and "(X == false)" to !X to
1445 // handle common cases produced by branch lowering.
1446 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1447 Cond = CondLHS;
1448 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1449 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1450 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1451 } else
1452 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1453 } else {
1454 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001455
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001456 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1457 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1458
1459 SDOperand CmpOp = getValue(CB.CmpMHS);
1460 MVT::ValueType VT = CmpOp.getValueType();
1461
1462 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1463 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1464 } else {
1465 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1466 Cond = DAG.getSetCC(MVT::i1, SUB,
1467 DAG.getConstant(High-Low, VT), ISD::SETULE);
1468 }
1469
1470 }
1471
Nate Begemanf15485a2006-03-27 01:32:24 +00001472 // Set NextBlock to be the MBB immediately after the current one, if any.
1473 // This is used to avoid emitting unnecessary branches to the next block.
1474 MachineBasicBlock *NextBlock = 0;
1475 MachineFunction::iterator BBI = CurMBB;
1476 if (++BBI != CurMBB->getParent()->end())
1477 NextBlock = BBI;
1478
1479 // If the lhs block is the next block, invert the condition so that we can
1480 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001481 if (CB.TrueBB == NextBlock) {
1482 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001483 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1484 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1485 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001486 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001487 DAG.getBasicBlock(CB.TrueBB));
1488 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001489 DAG.setRoot(BrCond);
1490 else
1491 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001492 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001493 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001494 CurMBB->addSuccessor(CB.TrueBB);
1495 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001496}
1497
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001498/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001499void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001500 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001501 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001502 MVT::ValueType PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001503 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001504 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1505 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1506 Table, Index));
1507 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001508}
1509
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001510/// visitJumpTableHeader - This function emits necessary code to produce index
1511/// in the JumpTable from switch case.
1512void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1513 SelectionDAGISel::JumpTableHeader &JTH) {
1514 // Subtract the lowest switch case value from the value being switched on
1515 // and conditional branch to default mbb if the result is greater than the
1516 // difference between smallest and largest cases.
1517 SDOperand SwitchOp = getValue(JTH.SValue);
1518 MVT::ValueType VT = SwitchOp.getValueType();
1519 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1520 DAG.getConstant(JTH.First, VT));
1521
1522 // The SDNode we just created, which holds the value being switched on
1523 // minus the the smallest case value, needs to be copied to a virtual
1524 // register so it can be used as an index into the jump table in a
1525 // subsequent basic block. This value may be smaller or larger than the
1526 // target's pointer type, and therefore require extension or truncating.
Dan Gohman7f321562007-06-25 16:23:39 +00001527 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001528 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1529 else
1530 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1531
1532 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001533 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001534 JT.Reg = JumpTableReg;
1535
1536 // Emit the range check for the jump table, and branch to the default
1537 // block for the switch statement if the value being switched on exceeds
1538 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001539 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001540 DAG.getConstant(JTH.Last-JTH.First,VT),
1541 ISD::SETUGT);
1542
1543 // Set NextBlock to be the MBB immediately after the current one, if any.
1544 // This is used to avoid emitting unnecessary branches to the next block.
1545 MachineBasicBlock *NextBlock = 0;
1546 MachineFunction::iterator BBI = CurMBB;
1547 if (++BBI != CurMBB->getParent()->end())
1548 NextBlock = BBI;
1549
1550 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1551 DAG.getBasicBlock(JT.Default));
1552
1553 if (JT.MBB == NextBlock)
1554 DAG.setRoot(BrCond);
1555 else
1556 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001557 DAG.getBasicBlock(JT.MBB)));
1558
1559 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001560}
1561
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001562/// visitBitTestHeader - This function emits necessary code to produce value
1563/// suitable for "bit tests"
1564void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1565 // Subtract the minimum value
1566 SDOperand SwitchOp = getValue(B.SValue);
1567 MVT::ValueType VT = SwitchOp.getValueType();
1568 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1569 DAG.getConstant(B.First, VT));
1570
1571 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001572 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001573 DAG.getConstant(B.Range, VT),
1574 ISD::SETUGT);
1575
1576 SDOperand ShiftOp;
Dan Gohman7f321562007-06-25 16:23:39 +00001577 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001578 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1579 else
1580 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1581
1582 // Make desired shift
1583 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1584 DAG.getConstant(1, TLI.getPointerTy()),
1585 ShiftOp);
1586
1587 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001588 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001589 B.Reg = SwitchReg;
1590
1591 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1592 DAG.getBasicBlock(B.Default));
1593
1594 // Set NextBlock to be the MBB immediately after the current one, if any.
1595 // This is used to avoid emitting unnecessary branches to the next block.
1596 MachineBasicBlock *NextBlock = 0;
1597 MachineFunction::iterator BBI = CurMBB;
1598 if (++BBI != CurMBB->getParent()->end())
1599 NextBlock = BBI;
1600
1601 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1602 if (MBB == NextBlock)
1603 DAG.setRoot(BrRange);
1604 else
1605 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1606 DAG.getBasicBlock(MBB)));
1607
1608 CurMBB->addSuccessor(B.Default);
1609 CurMBB->addSuccessor(MBB);
1610
1611 return;
1612}
1613
1614/// visitBitTestCase - this function produces one "bit test"
1615void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1616 unsigned Reg,
1617 SelectionDAGISel::BitTestCase &B) {
1618 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001619 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001620
1621 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1622 SwitchVal,
1623 DAG.getConstant(B.Mask,
1624 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001625 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001626 DAG.getConstant(0, TLI.getPointerTy()),
1627 ISD::SETNE);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001628 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001629 AndCmp, DAG.getBasicBlock(B.TargetBB));
1630
1631 // Set NextBlock to be the MBB immediately after the current one, if any.
1632 // This is used to avoid emitting unnecessary branches to the next block.
1633 MachineBasicBlock *NextBlock = 0;
1634 MachineFunction::iterator BBI = CurMBB;
1635 if (++BBI != CurMBB->getParent()->end())
1636 NextBlock = BBI;
1637
1638 if (NextMBB == NextBlock)
1639 DAG.setRoot(BrAnd);
1640 else
1641 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1642 DAG.getBasicBlock(NextMBB)));
1643
1644 CurMBB->addSuccessor(B.TargetBB);
1645 CurMBB->addSuccessor(NextMBB);
1646
1647 return;
1648}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001649
Jim Laskeyb180aa12007-02-21 22:53:45 +00001650void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1651 // Retrieve successors.
1652 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001653 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001654
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001655 if (isa<InlineAsm>(I.getCalledValue()))
1656 visitInlineAsm(&I);
1657 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001658 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001659
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001660 // If the value of the invoke is used outside of its defining block, make it
1661 // available as a virtual register.
1662 if (!I.use_empty()) {
1663 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1664 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001665 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001666 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001667
1668 // Drop into normal successor.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001669 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001670 DAG.getBasicBlock(Return)));
1671
1672 // Update successor info
1673 CurMBB->addSuccessor(Return);
1674 CurMBB->addSuccessor(LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001675}
1676
1677void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1678}
1679
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001680/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001681/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001682bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001683 CaseRecVector& WorkList,
1684 Value* SV,
1685 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001686 Case& BackCase = *(CR.Range.second-1);
1687
1688 // Size is the number of Cases represented by this range.
1689 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001690 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001691 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001692
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001693 // Get the MachineFunction which holds the current MBB. This is used when
1694 // inserting any additional MBBs necessary to represent the switch.
1695 MachineFunction *CurMF = CurMBB->getParent();
1696
1697 // Figure out which block is immediately after the current one.
1698 MachineBasicBlock *NextBlock = 0;
1699 MachineFunction::iterator BBI = CR.CaseBB;
1700
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001701 if (++BBI != CurMBB->getParent()->end())
1702 NextBlock = BBI;
1703
1704 // TODO: If any two of the cases has the same destination, and if one value
1705 // is the same as the other, but has one bit unset that the other has set,
1706 // use bit manipulation to do two compares at once. For example:
1707 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1708
1709 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001710 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001711 // The last case block won't fall through into 'NextBlock' if we emit the
1712 // branches in this order. See if rearranging a case value would help.
1713 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001714 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001715 std::swap(*I, BackCase);
1716 break;
1717 }
1718 }
1719 }
1720
1721 // Create a CaseBlock record representing a conditional branch to
1722 // the Case's target mbb if the value being switched on SV is equal
1723 // to C.
1724 MachineBasicBlock *CurBlock = CR.CaseBB;
1725 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1726 MachineBasicBlock *FallThrough;
1727 if (I != E-1) {
1728 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1729 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1730 } else {
1731 // If the last case doesn't match, go to the default block.
1732 FallThrough = Default;
1733 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001734
1735 Value *RHS, *LHS, *MHS;
1736 ISD::CondCode CC;
1737 if (I->High == I->Low) {
1738 // This is just small small case range :) containing exactly 1 case
1739 CC = ISD::SETEQ;
1740 LHS = SV; RHS = I->High; MHS = NULL;
1741 } else {
1742 CC = ISD::SETLE;
1743 LHS = I->Low; MHS = SV; RHS = I->High;
1744 }
1745 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1746 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001747
1748 // If emitting the first comparison, just call visitSwitchCase to emit the
1749 // code into the current block. Otherwise, push the CaseBlock onto the
1750 // vector to be later processed by SDISel, and insert the node's MBB
1751 // before the next MBB.
1752 if (CurBlock == CurMBB)
1753 visitSwitchCase(CB);
1754 else
1755 SwitchCases.push_back(CB);
1756
1757 CurBlock = FallThrough;
1758 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001759
1760 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001761}
1762
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001763static inline bool areJTsAllowed(const TargetLowering &TLI) {
1764 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1765 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1766}
1767
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001768/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001769bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001770 CaseRecVector& WorkList,
1771 Value* SV,
1772 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001773 Case& FrontCase = *CR.Range.first;
1774 Case& BackCase = *(CR.Range.second-1);
1775
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001776 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1777 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1778
1779 uint64_t TSize = 0;
1780 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1781 I!=E; ++I)
1782 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001783
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001784 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001785 return false;
1786
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001787 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1788 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001789 return false;
1790
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001791 DOUT << "Lowering jump table\n"
1792 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001793 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001794
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001795 // Get the MachineFunction which holds the current MBB. This is used when
1796 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001797 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001798
1799 // Figure out which block is immediately after the current one.
1800 MachineBasicBlock *NextBlock = 0;
1801 MachineFunction::iterator BBI = CR.CaseBB;
1802
1803 if (++BBI != CurMBB->getParent()->end())
1804 NextBlock = BBI;
1805
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001806 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1807
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001808 // Create a new basic block to hold the code for loading the address
1809 // of the jump table, and jumping to it. Update successor information;
1810 // we will either branch to the default case for the switch, or the jump
1811 // table.
1812 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1813 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1814 CR.CaseBB->addSuccessor(Default);
1815 CR.CaseBB->addSuccessor(JumpTableBB);
1816
1817 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001818 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001819 // a case statement, push the case's BB onto the vector, otherwise, push
1820 // the default BB.
1821 std::vector<MachineBasicBlock*> DestBBs;
1822 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001823 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1824 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1825 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1826
1827 if ((Low <= TEI) && (TEI <= High)) {
1828 DestBBs.push_back(I->BB);
1829 if (TEI==High)
1830 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001831 } else {
1832 DestBBs.push_back(Default);
1833 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001834 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001835
1836 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001837 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001838 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1839 E = DestBBs.end(); I != E; ++I) {
1840 if (!SuccsHandled[(*I)->getNumber()]) {
1841 SuccsHandled[(*I)->getNumber()] = true;
1842 JumpTableBB->addSuccessor(*I);
1843 }
1844 }
1845
1846 // Create a jump table index for this jump table, or return an existing
1847 // one.
1848 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1849
1850 // Set the jump table information so that we can codegen it as a second
1851 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001852 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001853 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1854 (CR.CaseBB == CurMBB));
1855 if (CR.CaseBB == CurMBB)
1856 visitJumpTableHeader(JT, JTH);
1857
1858 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001859
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001860 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001861}
1862
1863/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1864/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001865bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001866 CaseRecVector& WorkList,
1867 Value* SV,
1868 MachineBasicBlock* Default) {
1869 // Get the MachineFunction which holds the current MBB. This is used when
1870 // inserting any additional MBBs necessary to represent the switch.
1871 MachineFunction *CurMF = CurMBB->getParent();
1872
1873 // Figure out which block is immediately after the current one.
1874 MachineBasicBlock *NextBlock = 0;
1875 MachineFunction::iterator BBI = CR.CaseBB;
1876
1877 if (++BBI != CurMBB->getParent()->end())
1878 NextBlock = BBI;
1879
1880 Case& FrontCase = *CR.Range.first;
1881 Case& BackCase = *(CR.Range.second-1);
1882 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1883
1884 // Size is the number of Cases represented by this range.
1885 unsigned Size = CR.Range.second - CR.Range.first;
1886
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001887 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1888 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001889 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001890 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001891
1892 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1893 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001894 uint64_t TSize = 0;
1895 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1896 I!=E; ++I)
1897 TSize += I->size();
1898
1899 uint64_t LSize = FrontCase.size();
1900 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001901 DOUT << "Selecting best pivot: \n"
1902 << "First: " << First << ", Last: " << Last <<"\n"
1903 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001904 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001905 J!=E; ++I, ++J) {
1906 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1907 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001908 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001909 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1910 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001911 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001912 // Should always split in some non-trivial place
1913 DOUT <<"=>Step\n"
1914 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1915 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1916 << "Metric: " << Metric << "\n";
1917 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001918 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001919 FMetric = Metric;
1920 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001921 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001922
1923 LSize += J->size();
1924 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001925 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001926 if (areJTsAllowed(TLI)) {
1927 // If our case is dense we *really* should handle it earlier!
1928 assert((FMetric > 0) && "Should handle dense range earlier!");
1929 } else {
1930 Pivot = CR.Range.first + Size/2;
1931 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001932
1933 CaseRange LHSR(CR.Range.first, Pivot);
1934 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001935 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001936 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1937
1938 // We know that we branch to the LHS if the Value being switched on is
1939 // less than the Pivot value, C. We use this to optimize our binary
1940 // tree a bit, by recognizing that if SV is greater than or equal to the
1941 // LHS's Case Value, and that Case Value is exactly one less than the
1942 // Pivot's Value, then we can branch directly to the LHS's Target,
1943 // rather than creating a leaf node for it.
1944 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001945 LHSR.first->High == CR.GE &&
1946 cast<ConstantInt>(C)->getSExtValue() ==
1947 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1948 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001949 } else {
1950 TrueBB = new MachineBasicBlock(LLVMBB);
1951 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1952 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1953 }
1954
1955 // Similar to the optimization above, if the Value being switched on is
1956 // known to be less than the Constant CR.LT, and the current Case Value
1957 // is CR.LT - 1, then we can branch directly to the target block for
1958 // the current Case Value, rather than emitting a RHS leaf node for it.
1959 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001960 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1961 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1962 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001963 } else {
1964 FalseBB = new MachineBasicBlock(LLVMBB);
1965 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1966 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1967 }
1968
1969 // Create a CaseBlock record representing a conditional branch to
1970 // the LHS node if the value being switched on SV is less than C.
1971 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001972 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1973 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001974
1975 if (CR.CaseBB == CurMBB)
1976 visitSwitchCase(CB);
1977 else
1978 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001979
1980 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001981}
1982
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001983/// handleBitTestsSwitchCase - if current case range has few destination and
1984/// range span less, than machine word bitwidth, encode case range into series
1985/// of masks and emit bit tests with these masks.
1986bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1987 CaseRecVector& WorkList,
1988 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00001989 MachineBasicBlock* Default){
Dan Gohmanb55757e2007-05-18 17:52:13 +00001990 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001991
1992 Case& FrontCase = *CR.Range.first;
1993 Case& BackCase = *(CR.Range.second-1);
1994
1995 // Get the MachineFunction which holds the current MBB. This is used when
1996 // inserting any additional MBBs necessary to represent the switch.
1997 MachineFunction *CurMF = CurMBB->getParent();
1998
1999 unsigned numCmps = 0;
2000 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2001 I!=E; ++I) {
2002 // Single case counts one, case range - two.
2003 if (I->Low == I->High)
2004 numCmps +=1;
2005 else
2006 numCmps +=2;
2007 }
2008
2009 // Count unique destinations
2010 SmallSet<MachineBasicBlock*, 4> Dests;
2011 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2012 Dests.insert(I->BB);
2013 if (Dests.size() > 3)
2014 // Don't bother the code below, if there are too much unique destinations
2015 return false;
2016 }
2017 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2018 << "Total number of comparisons: " << numCmps << "\n";
2019
2020 // Compute span of values.
2021 Constant* minValue = FrontCase.Low;
2022 Constant* maxValue = BackCase.High;
2023 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2024 cast<ConstantInt>(minValue)->getSExtValue();
2025 DOUT << "Compare range: " << range << "\n"
2026 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2027 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2028
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002029 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002030 (!(Dests.size() == 1 && numCmps >= 3) &&
2031 !(Dests.size() == 2 && numCmps >= 5) &&
2032 !(Dests.size() >= 3 && numCmps >= 6)))
2033 return false;
2034
2035 DOUT << "Emitting bit tests\n";
2036 int64_t lowBound = 0;
2037
2038 // Optimize the case where all the case values fit in a
2039 // word without having to subtract minValue. In this case,
2040 // we can optimize away the subtraction.
2041 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002042 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002043 range = cast<ConstantInt>(maxValue)->getSExtValue();
2044 } else {
2045 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2046 }
2047
2048 CaseBitsVector CasesBits;
2049 unsigned i, count = 0;
2050
2051 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2052 MachineBasicBlock* Dest = I->BB;
2053 for (i = 0; i < count; ++i)
2054 if (Dest == CasesBits[i].BB)
2055 break;
2056
2057 if (i == count) {
2058 assert((count < 3) && "Too much destinations to test!");
2059 CasesBits.push_back(CaseBits(0, Dest, 0));
2060 count++;
2061 }
2062
2063 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2064 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2065
2066 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002067 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002068 CasesBits[i].Bits++;
2069 }
2070
2071 }
2072 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2073
2074 SelectionDAGISel::BitTestInfo BTC;
2075
2076 // Figure out which block is immediately after the current one.
2077 MachineFunction::iterator BBI = CR.CaseBB;
2078 ++BBI;
2079
2080 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2081
2082 DOUT << "Cases:\n";
2083 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2084 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2085 << ", BB: " << CasesBits[i].BB << "\n";
2086
2087 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2088 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2089 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2090 CaseBB,
2091 CasesBits[i].BB));
2092 }
2093
2094 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002095 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002096 CR.CaseBB, Default, BTC);
2097
2098 if (CR.CaseBB == CurMBB)
2099 visitBitTestHeader(BTB);
2100
2101 BitTestCases.push_back(BTB);
2102
2103 return true;
2104}
2105
2106
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002107/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002108unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2109 const SwitchInst& SI) {
2110 unsigned numCmps = 0;
2111
2112 // Start with "simple" cases
2113 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2114 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2115 Cases.push_back(Case(SI.getSuccessorValue(i),
2116 SI.getSuccessorValue(i),
2117 SMBB));
2118 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002119 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002120
2121 // Merge case into clusters
2122 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002123 // Must recompute end() each iteration because it may be
2124 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002125 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002126 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2127 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2128 MachineBasicBlock* nextBB = J->BB;
2129 MachineBasicBlock* currentBB = I->BB;
2130
2131 // If the two neighboring cases go to the same destination, merge them
2132 // into a single case.
2133 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2134 I->High = J->High;
2135 J = Cases.erase(J);
2136 } else {
2137 I = J++;
2138 }
2139 }
2140
2141 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2142 if (I->Low != I->High)
2143 // A range counts double, since it requires two compares.
2144 ++numCmps;
2145 }
2146
2147 return numCmps;
2148}
2149
2150void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002151 // Figure out which block is immediately after the current one.
2152 MachineBasicBlock *NextBlock = 0;
2153 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002154
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002155 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002156
Nate Begemanf15485a2006-03-27 01:32:24 +00002157 // If there is only the default destination, branch to it if it is not the
2158 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002159 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002160 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002161
Nate Begemanf15485a2006-03-27 01:32:24 +00002162 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002163 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002164 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002165 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002166
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002167 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002168 return;
2169 }
2170
2171 // If there are any non-default case statements, create a vector of Cases
2172 // representing each one, and sort the vector so that we can efficiently
2173 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002174 CaseVector Cases;
2175 unsigned numCmps = Clusterify(Cases, SI);
2176 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2177 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002178
Nate Begemanf15485a2006-03-27 01:32:24 +00002179 // Get the Value to be switched on and default basic blocks, which will be
2180 // inserted into CaseBlock records, representing basic blocks in the binary
2181 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002182 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002183
Nate Begemanf15485a2006-03-27 01:32:24 +00002184 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002185 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002186 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2187
2188 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002189 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002190 CaseRec CR = WorkList.back();
2191 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002192
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002193 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2194 continue;
2195
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002196 // If the range has few cases (two or less) emit a series of specific
2197 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002198 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2199 continue;
2200
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002201 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002202 // target supports indirect branches, then emit a jump table rather than
2203 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002204 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2205 continue;
2206
2207 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2208 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2209 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002210 }
2211}
2212
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002213
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002214void SelectionDAGLowering::visitSub(User &I) {
2215 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002216 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002217 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002218 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2219 const VectorType *DestTy = cast<VectorType>(I.getType());
2220 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002221 if (ElTy->isFloatingPoint()) {
2222 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002223 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002224 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2225 if (CV == CNZ) {
2226 SDOperand Op2 = getValue(I.getOperand(1));
2227 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2228 return;
2229 }
Dan Gohman7f321562007-06-25 16:23:39 +00002230 }
2231 }
2232 }
2233 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002234 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002235 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002236 SDOperand Op2 = getValue(I.getOperand(1));
2237 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2238 return;
2239 }
Dan Gohman7f321562007-06-25 16:23:39 +00002240 }
2241
2242 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002243}
2244
Dan Gohman7f321562007-06-25 16:23:39 +00002245void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002246 SDOperand Op1 = getValue(I.getOperand(0));
2247 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002248
2249 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002250}
2251
Nate Begemane21ea612005-11-18 07:42:56 +00002252void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2253 SDOperand Op1 = getValue(I.getOperand(0));
2254 SDOperand Op2 = getValue(I.getOperand(1));
2255
Dan Gohman7f321562007-06-25 16:23:39 +00002256 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2257 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002258 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2259 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2260 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002261
Chris Lattner1c08c712005-01-07 07:47:53 +00002262 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2263}
2264
Reid Spencer45fb3f32006-11-20 01:22:35 +00002265void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002266 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2267 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2268 predicate = IC->getPredicate();
2269 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2270 predicate = ICmpInst::Predicate(IC->getPredicate());
2271 SDOperand Op1 = getValue(I.getOperand(0));
2272 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002273 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002274 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002275 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2276 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2277 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2278 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2279 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2280 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2281 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2282 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2283 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2284 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2285 default:
2286 assert(!"Invalid ICmp predicate value");
2287 Opcode = ISD::SETEQ;
2288 break;
2289 }
2290 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2291}
2292
2293void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002294 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2295 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2296 predicate = FC->getPredicate();
2297 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2298 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002299 SDOperand Op1 = getValue(I.getOperand(0));
2300 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002301 ISD::CondCode Condition, FOC, FPC;
2302 switch (predicate) {
2303 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2304 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2305 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2306 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2307 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2308 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2309 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2310 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2311 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2312 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2313 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2314 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2315 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2316 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2317 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2318 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2319 default:
2320 assert(!"Invalid FCmp predicate value");
2321 FOC = FPC = ISD::SETFALSE;
2322 break;
2323 }
2324 if (FiniteOnlyFPMath())
2325 Condition = FOC;
2326 else
2327 Condition = FPC;
2328 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002329}
2330
2331void SelectionDAGLowering::visitSelect(User &I) {
2332 SDOperand Cond = getValue(I.getOperand(0));
2333 SDOperand TrueVal = getValue(I.getOperand(1));
2334 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002335 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2336 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002337}
2338
Reid Spencer3da59db2006-11-27 01:05:10 +00002339
2340void SelectionDAGLowering::visitTrunc(User &I) {
2341 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2342 SDOperand N = getValue(I.getOperand(0));
2343 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2344 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2345}
2346
2347void SelectionDAGLowering::visitZExt(User &I) {
2348 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2349 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2350 SDOperand N = getValue(I.getOperand(0));
2351 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2352 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2353}
2354
2355void SelectionDAGLowering::visitSExt(User &I) {
2356 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2357 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2358 SDOperand N = getValue(I.getOperand(0));
2359 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2360 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2361}
2362
2363void SelectionDAGLowering::visitFPTrunc(User &I) {
2364 // FPTrunc is never a no-op cast, no need to check
2365 SDOperand N = getValue(I.getOperand(0));
2366 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002367 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002368}
2369
2370void SelectionDAGLowering::visitFPExt(User &I){
2371 // FPTrunc is never a no-op cast, no need to check
2372 SDOperand N = getValue(I.getOperand(0));
2373 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2374 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2375}
2376
2377void SelectionDAGLowering::visitFPToUI(User &I) {
2378 // FPToUI is never a no-op cast, no need to check
2379 SDOperand N = getValue(I.getOperand(0));
2380 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2381 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2382}
2383
2384void SelectionDAGLowering::visitFPToSI(User &I) {
2385 // FPToSI is never a no-op cast, no need to check
2386 SDOperand N = getValue(I.getOperand(0));
2387 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2388 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2389}
2390
2391void SelectionDAGLowering::visitUIToFP(User &I) {
2392 // UIToFP is never a no-op cast, no need to check
2393 SDOperand N = getValue(I.getOperand(0));
2394 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2395 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2396}
2397
2398void SelectionDAGLowering::visitSIToFP(User &I){
2399 // UIToFP is never a no-op cast, no need to check
2400 SDOperand N = getValue(I.getOperand(0));
2401 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2402 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2403}
2404
2405void SelectionDAGLowering::visitPtrToInt(User &I) {
2406 // What to do depends on the size of the integer and the size of the pointer.
2407 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002408 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002409 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002410 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002411 SDOperand Result;
2412 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2413 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2414 else
2415 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2416 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2417 setValue(&I, Result);
2418}
Chris Lattner1c08c712005-01-07 07:47:53 +00002419
Reid Spencer3da59db2006-11-27 01:05:10 +00002420void SelectionDAGLowering::visitIntToPtr(User &I) {
2421 // What to do depends on the size of the integer and the size of the pointer.
2422 // We can either truncate, zero extend, or no-op, accordingly.
2423 SDOperand N = getValue(I.getOperand(0));
2424 MVT::ValueType SrcVT = N.getValueType();
2425 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2426 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2427 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2428 else
2429 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2430 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2431}
2432
2433void SelectionDAGLowering::visitBitCast(User &I) {
2434 SDOperand N = getValue(I.getOperand(0));
2435 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002436
2437 // BitCast assures us that source and destination are the same size so this
2438 // is either a BIT_CONVERT or a no-op.
2439 if (DestVT != N.getValueType())
2440 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2441 else
2442 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002443}
2444
Chris Lattner2bbd8102006-03-29 00:11:43 +00002445void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002446 SDOperand InVec = getValue(I.getOperand(0));
2447 SDOperand InVal = getValue(I.getOperand(1));
2448 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2449 getValue(I.getOperand(2)));
2450
Dan Gohman7f321562007-06-25 16:23:39 +00002451 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2452 TLI.getValueType(I.getType()),
2453 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002454}
2455
Chris Lattner2bbd8102006-03-29 00:11:43 +00002456void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002457 SDOperand InVec = getValue(I.getOperand(0));
2458 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2459 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002460 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002461 TLI.getValueType(I.getType()), InVec, InIdx));
2462}
Chris Lattnerc7029802006-03-18 01:44:44 +00002463
Chris Lattner3e104b12006-04-08 04:15:24 +00002464void SelectionDAGLowering::visitShuffleVector(User &I) {
2465 SDOperand V1 = getValue(I.getOperand(0));
2466 SDOperand V2 = getValue(I.getOperand(1));
2467 SDOperand Mask = getValue(I.getOperand(2));
2468
Dan Gohman7f321562007-06-25 16:23:39 +00002469 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2470 TLI.getValueType(I.getType()),
2471 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002472}
2473
2474
Chris Lattner1c08c712005-01-07 07:47:53 +00002475void SelectionDAGLowering::visitGetElementPtr(User &I) {
2476 SDOperand N = getValue(I.getOperand(0));
2477 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002478
2479 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2480 OI != E; ++OI) {
2481 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002482 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002483 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002484 if (Field) {
2485 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002486 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002487 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002488 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002489 }
2490 Ty = StTy->getElementType(Field);
2491 } else {
2492 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002493
Chris Lattner7c0104b2005-11-09 04:45:33 +00002494 // If this is a constant subscript, handle it quickly.
2495 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002496 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002497 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002498 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002499 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2500 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002501 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002502 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002503
2504 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002505 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002506 SDOperand IdxN = getValue(Idx);
2507
2508 // If the index is smaller or larger than intptr_t, truncate or extend
2509 // it.
2510 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002511 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002512 } else if (IdxN.getValueType() > N.getValueType())
2513 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2514
2515 // If this is a multiply by a power of two, turn it into a shl
2516 // immediately. This is a very common case.
2517 if (isPowerOf2_64(ElementSize)) {
2518 unsigned Amt = Log2_64(ElementSize);
2519 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002520 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002521 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2522 continue;
2523 }
2524
Chris Lattner0bd48932008-01-17 07:00:52 +00002525 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002526 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2527 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002528 }
2529 }
2530 setValue(&I, N);
2531}
2532
2533void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2534 // If this is a fixed sized alloca in the entry block of the function,
2535 // allocate it statically on the stack.
2536 if (FuncInfo.StaticAllocaMap.count(&I))
2537 return; // getValue will auto-populate this.
2538
2539 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002540 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002541 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002542 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002543 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002544
2545 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002546 MVT::ValueType IntPtr = TLI.getPointerTy();
2547 if (IntPtr < AllocSize.getValueType())
2548 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2549 else if (IntPtr > AllocSize.getValueType())
2550 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002551
Chris Lattner68cd65e2005-01-22 23:04:37 +00002552 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002553 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002554
Evan Cheng45157792007-08-16 23:46:29 +00002555 // Handle alignment. If the requested alignment is less than or equal to
2556 // the stack alignment, ignore it. If the size is greater than or equal to
2557 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002558 unsigned StackAlign =
2559 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002560 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002561 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002562
2563 // Round the size of the allocation up to the stack alignment size
2564 // by add SA-1 to the size.
2565 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002566 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002567 // Mask out the low bits for alignment purposes.
2568 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002569 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002570
Chris Lattner0bd48932008-01-17 07:00:52 +00002571 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002572 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2573 MVT::Other);
2574 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002575 setValue(&I, DSA);
2576 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002577
2578 // Inform the Frame Information that we have just allocated a variable-sized
2579 // object.
2580 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2581}
2582
Chris Lattner1c08c712005-01-07 07:47:53 +00002583void SelectionDAGLowering::visitLoad(LoadInst &I) {
2584 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002585
Chris Lattnerd3948112005-01-17 22:19:26 +00002586 SDOperand Root;
2587 if (I.isVolatile())
2588 Root = getRoot();
2589 else {
2590 // Do not serialize non-volatile loads against each other.
2591 Root = DAG.getRoot();
2592 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002593
Evan Cheng466685d2006-10-09 20:57:25 +00002594 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002595 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002596}
2597
2598SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002599 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002600 bool isVolatile,
2601 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002602 SDOperand L =
2603 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2604 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002605
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002606 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002607 DAG.setRoot(L.getValue(1));
2608 else
2609 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002610
2611 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002612}
2613
2614
2615void SelectionDAGLowering::visitStore(StoreInst &I) {
2616 Value *SrcV = I.getOperand(0);
2617 SDOperand Src = getValue(SrcV);
2618 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002619 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002620 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002621}
2622
Chris Lattner0eade312006-03-24 02:22:33 +00002623/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2624/// node.
2625void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2626 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002627 bool HasChain = !I.doesNotAccessMemory();
2628 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2629
Chris Lattner0eade312006-03-24 02:22:33 +00002630 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002631 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002632 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2633 if (OnlyLoad) {
2634 // We don't need to serialize loads against other loads.
2635 Ops.push_back(DAG.getRoot());
2636 } else {
2637 Ops.push_back(getRoot());
2638 }
2639 }
Chris Lattner0eade312006-03-24 02:22:33 +00002640
2641 // Add the intrinsic ID as an integer operand.
2642 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2643
2644 // Add all operands of the call to the operand list.
2645 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2646 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002647 assert(TLI.isTypeLegal(Op.getValueType()) &&
2648 "Intrinsic uses a non-legal type?");
2649 Ops.push_back(Op);
2650 }
2651
2652 std::vector<MVT::ValueType> VTs;
2653 if (I.getType() != Type::VoidTy) {
2654 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00002655 if (MVT::isVector(VT)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002656 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002657 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2658
2659 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2660 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2661 }
2662
2663 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2664 VTs.push_back(VT);
2665 }
2666 if (HasChain)
2667 VTs.push_back(MVT::Other);
2668
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002669 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2670
Chris Lattner0eade312006-03-24 02:22:33 +00002671 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002672 SDOperand Result;
2673 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002674 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2675 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002676 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002677 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2678 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002679 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002680 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2681 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002682
Chris Lattnere58a7802006-04-02 03:41:14 +00002683 if (HasChain) {
2684 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2685 if (OnlyLoad)
2686 PendingLoads.push_back(Chain);
2687 else
2688 DAG.setRoot(Chain);
2689 }
Chris Lattner0eade312006-03-24 02:22:33 +00002690 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002691 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohman7f321562007-06-25 16:23:39 +00002692 MVT::ValueType VT = TLI.getValueType(PTy);
2693 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002694 }
2695 setValue(&I, Result);
2696 }
2697}
2698
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002699/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002700static GlobalVariable *ExtractTypeInfo (Value *V) {
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002701 V = IntrinsicInst::StripPointerCasts(V);
2702 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00002703 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002704 "TypeInfo must be a global variable or NULL");
2705 return GV;
2706}
2707
Duncan Sandsf4070822007-06-15 19:04:19 +00002708/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002709/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002710static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2711 MachineBasicBlock *MBB) {
2712 // Inform the MachineModuleInfo of the personality for this landing pad.
2713 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2714 assert(CE->getOpcode() == Instruction::BitCast &&
2715 isa<Function>(CE->getOperand(0)) &&
2716 "Personality should be a function");
2717 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2718
2719 // Gather all the type infos for this landing pad and pass them along to
2720 // MachineModuleInfo.
2721 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002722 unsigned N = I.getNumOperands();
2723
2724 for (unsigned i = N - 1; i > 2; --i) {
2725 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2726 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002727 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002728 assert (FirstCatch <= N && "Invalid filter length");
2729
2730 if (FirstCatch < N) {
2731 TyInfo.reserve(N - FirstCatch);
2732 for (unsigned j = FirstCatch; j < N; ++j)
2733 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2734 MMI->addCatchTypeInfo(MBB, TyInfo);
2735 TyInfo.clear();
2736 }
2737
Duncan Sands6590b042007-08-27 15:47:50 +00002738 if (!FilterLength) {
2739 // Cleanup.
2740 MMI->addCleanup(MBB);
2741 } else {
2742 // Filter.
2743 TyInfo.reserve(FilterLength - 1);
2744 for (unsigned j = i + 1; j < FirstCatch; ++j)
2745 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2746 MMI->addFilterTypeInfo(MBB, TyInfo);
2747 TyInfo.clear();
2748 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002749
2750 N = i;
2751 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002752 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002753
2754 if (N > 3) {
2755 TyInfo.reserve(N - 3);
2756 for (unsigned j = 3; j < N; ++j)
2757 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002758 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002759 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002760}
2761
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002762/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2763/// we want to emit this as a call to a named external function, return the name
2764/// otherwise lower it and return null.
2765const char *
2766SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2767 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002768 default:
2769 // By default, turn this into a target intrinsic node.
2770 visitTargetIntrinsic(I, Intrinsic);
2771 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002772 case Intrinsic::vastart: visitVAStart(I); return 0;
2773 case Intrinsic::vaend: visitVAEnd(I); return 0;
2774 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002775 case Intrinsic::returnaddress:
2776 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2777 getValue(I.getOperand(1))));
2778 return 0;
2779 case Intrinsic::frameaddress:
2780 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2781 getValue(I.getOperand(1))));
2782 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002783 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002784 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002785 break;
2786 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002787 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002788 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002789 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002790 case Intrinsic::memcpy_i64: {
2791 SDOperand Op1 = getValue(I.getOperand(1));
2792 SDOperand Op2 = getValue(I.getOperand(2));
2793 SDOperand Op3 = getValue(I.getOperand(3));
2794 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2795 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2796 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002797 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002798 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002799 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002800 case Intrinsic::memset_i64: {
2801 SDOperand Op1 = getValue(I.getOperand(1));
2802 SDOperand Op2 = getValue(I.getOperand(2));
2803 SDOperand Op3 = getValue(I.getOperand(3));
2804 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2805 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2806 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002807 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002808 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002809 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002810 case Intrinsic::memmove_i64: {
2811 SDOperand Op1 = getValue(I.getOperand(1));
2812 SDOperand Op2 = getValue(I.getOperand(2));
2813 SDOperand Op3 = getValue(I.getOperand(3));
2814 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2815
2816 // If the source and destination are known to not be aliases, we can
2817 // lower memmove as memcpy.
2818 uint64_t Size = -1ULL;
2819 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2820 Size = C->getValue();
2821 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2822 AliasAnalysis::NoAlias) {
2823 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2824 I.getOperand(1), 0, I.getOperand(2), 0));
2825 return 0;
2826 }
2827
2828 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2829 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002830 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002831 }
Chris Lattner86cb6432005-12-13 17:40:33 +00002832 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002833 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002834 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002835 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002836 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002837
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002838 Ops[0] = getRoot();
2839 Ops[1] = getValue(SPI.getLineValue());
2840 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002841
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002842 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002843 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002844 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2845
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002846 Ops[3] = DAG.getString(CompileUnit->getFileName());
2847 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002848
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002849 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002850 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002851
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002852 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002853 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002854 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002855 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002856 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002857 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2858 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002859 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00002860 DAG.getConstant(LabelID, MVT::i32),
2861 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002862 }
2863
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002864 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002865 }
2866 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002867 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002868 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002869 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2870 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00002871 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2872 DAG.getConstant(LabelID, MVT::i32),
2873 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002874 }
2875
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002876 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002877 }
2878 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002879 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002880 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002881 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002882 Value *SP = FSI.getSubprogram();
2883 if (SP && MMI->Verify(SP)) {
2884 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2885 // what (most?) gdb expects.
2886 DebugInfoDesc *DD = MMI->getDescFor(SP);
2887 assert(DD && "Not a debug information descriptor");
2888 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2889 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2890 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2891 CompileUnit->getFileName());
2892 // Record the source line but does create a label. It will be emitted
2893 // at asm emission time.
2894 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00002895 }
2896
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002897 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002898 }
2899 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002900 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002901 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00002902 Value *Variable = DI.getVariable();
2903 if (MMI && Variable && MMI->Verify(Variable))
2904 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2905 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002906 return 0;
2907 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002908
Jim Laskeyb180aa12007-02-21 22:53:45 +00002909 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002910 if (!CurMBB->isLandingPad()) {
2911 // FIXME: Mark exception register as live in. Hack for PR1508.
2912 unsigned Reg = TLI.getExceptionAddressRegister();
2913 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00002914 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002915 // Insert the EXCEPTIONADDR instruction.
2916 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2917 SDOperand Ops[1];
2918 Ops[0] = DAG.getRoot();
2919 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2920 setValue(&I, Op);
2921 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00002922 return 0;
2923 }
2924
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002925 case Intrinsic::eh_selector_i32:
2926 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002927 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002928 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2929 MVT::i32 : MVT::i64);
2930
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002931 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00002932 if (CurMBB->isLandingPad())
2933 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00002934 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00002935#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00002936 FuncInfo.CatchInfoLost.insert(&I);
2937#endif
Duncan Sands90291952007-07-06 09:18:59 +00002938 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2939 unsigned Reg = TLI.getExceptionSelectorRegister();
2940 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00002941 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002942
2943 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002944 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002945 SDOperand Ops[2];
2946 Ops[0] = getValue(I.getOperand(1));
2947 Ops[1] = getRoot();
2948 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2949 setValue(&I, Op);
2950 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002951 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002952 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00002953 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002954
2955 return 0;
2956 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002957
2958 case Intrinsic::eh_typeid_for_i32:
2959 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002960 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002961 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2962 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002963
Jim Laskey735b6f82007-02-22 15:38:06 +00002964 if (MMI) {
2965 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002966 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00002967
Jim Laskey735b6f82007-02-22 15:38:06 +00002968 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002969 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00002970 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00002971 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002972 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00002973 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002974
2975 return 0;
2976 }
2977
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002978 case Intrinsic::eh_return: {
2979 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2980
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002981 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002982 MMI->setCallsEHReturn(true);
2983 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2984 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002985 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002986 getValue(I.getOperand(1)),
2987 getValue(I.getOperand(2))));
2988 } else {
2989 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2990 }
2991
2992 return 0;
2993 }
2994
2995 case Intrinsic::eh_unwind_init: {
2996 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2997 MMI->setCallsUnwindInit(true);
2998 }
2999
3000 return 0;
3001 }
3002
3003 case Intrinsic::eh_dwarf_cfa: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003004 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3005 SDOperand CfaArg;
3006 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3007 CfaArg = DAG.getNode(ISD::TRUNCATE,
3008 TLI.getPointerTy(), getValue(I.getOperand(1)));
3009 else
3010 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3011 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003012
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003013 SDOperand Offset = DAG.getNode(ISD::ADD,
3014 TLI.getPointerTy(),
3015 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3016 TLI.getPointerTy()),
3017 CfaArg);
3018 setValue(&I, DAG.getNode(ISD::ADD,
3019 TLI.getPointerTy(),
3020 DAG.getNode(ISD::FRAMEADDR,
3021 TLI.getPointerTy(),
3022 DAG.getConstant(0,
3023 TLI.getPointerTy())),
3024 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003025 return 0;
3026 }
3027
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003028 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003029 setValue(&I, DAG.getNode(ISD::FSQRT,
3030 getValue(I.getOperand(1)).getValueType(),
3031 getValue(I.getOperand(1))));
3032 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003033 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003034 setValue(&I, DAG.getNode(ISD::FPOWI,
3035 getValue(I.getOperand(1)).getValueType(),
3036 getValue(I.getOperand(1)),
3037 getValue(I.getOperand(2))));
3038 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003039 case Intrinsic::sin:
3040 setValue(&I, DAG.getNode(ISD::FSIN,
3041 getValue(I.getOperand(1)).getValueType(),
3042 getValue(I.getOperand(1))));
3043 return 0;
3044 case Intrinsic::cos:
3045 setValue(&I, DAG.getNode(ISD::FCOS,
3046 getValue(I.getOperand(1)).getValueType(),
3047 getValue(I.getOperand(1))));
3048 return 0;
3049 case Intrinsic::pow:
3050 setValue(&I, DAG.getNode(ISD::FPOW,
3051 getValue(I.getOperand(1)).getValueType(),
3052 getValue(I.getOperand(1)),
3053 getValue(I.getOperand(2))));
3054 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003055 case Intrinsic::pcmarker: {
3056 SDOperand Tmp = getValue(I.getOperand(1));
3057 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3058 return 0;
3059 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003060 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003061 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003062 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3063 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3064 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003065 setValue(&I, Tmp);
3066 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003067 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003068 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003069 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003070 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003071 assert(0 && "part_select intrinsic not implemented");
3072 abort();
3073 }
3074 case Intrinsic::part_set: {
3075 // Currently not implemented: just abort
3076 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003077 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003078 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003079 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003080 setValue(&I, DAG.getNode(ISD::BSWAP,
3081 getValue(I.getOperand(1)).getValueType(),
3082 getValue(I.getOperand(1))));
3083 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003084 case Intrinsic::cttz: {
3085 SDOperand Arg = getValue(I.getOperand(1));
3086 MVT::ValueType Ty = Arg.getValueType();
3087 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003088 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003089 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003090 }
3091 case Intrinsic::ctlz: {
3092 SDOperand Arg = getValue(I.getOperand(1));
3093 MVT::ValueType Ty = Arg.getValueType();
3094 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003095 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003096 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003097 }
3098 case Intrinsic::ctpop: {
3099 SDOperand Arg = getValue(I.getOperand(1));
3100 MVT::ValueType Ty = Arg.getValueType();
3101 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003102 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003103 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003104 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003105 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003106 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003107 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3108 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003109 setValue(&I, Tmp);
3110 DAG.setRoot(Tmp.getValue(1));
3111 return 0;
3112 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003113 case Intrinsic::stackrestore: {
3114 SDOperand Tmp = getValue(I.getOperand(1));
3115 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003116 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003117 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003118 case Intrinsic::var_annotation:
3119 // Discard annotate attributes
3120 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003121
Duncan Sands36397f52007-07-27 12:58:54 +00003122 case Intrinsic::init_trampoline: {
3123 const Function *F =
3124 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3125
3126 SDOperand Ops[6];
3127 Ops[0] = getRoot();
3128 Ops[1] = getValue(I.getOperand(1));
3129 Ops[2] = getValue(I.getOperand(2));
3130 Ops[3] = getValue(I.getOperand(3));
3131 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3132 Ops[5] = DAG.getSrcValue(F);
3133
Duncan Sandsf7331b32007-09-11 14:10:23 +00003134 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3135 DAG.getNodeValueTypes(TLI.getPointerTy(),
3136 MVT::Other), 2,
3137 Ops, 6);
3138
3139 setValue(&I, Tmp);
3140 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003141 return 0;
3142 }
Gordon Henriksence224772008-01-07 01:30:38 +00003143
3144 case Intrinsic::gcroot:
3145 if (GCI) {
3146 Value *Alloca = I.getOperand(1);
3147 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3148
3149 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3150 GCI->addStackRoot(FI->getIndex(), TypeMap);
3151 }
3152 return 0;
3153
3154 case Intrinsic::gcread:
3155 case Intrinsic::gcwrite:
3156 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3157 return 0;
3158
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003159 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003160 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003161 return 0;
3162 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003163
3164 case Intrinsic::trap: {
3165 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3166 return 0;
3167 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003168 case Intrinsic::prefetch: {
3169 SDOperand Ops[4];
3170 Ops[0] = getRoot();
3171 Ops[1] = getValue(I.getOperand(1));
3172 Ops[2] = getValue(I.getOperand(2));
3173 Ops[3] = getValue(I.getOperand(3));
3174 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3175 return 0;
3176 }
3177
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003178 case Intrinsic::memory_barrier: {
3179 SDOperand Ops[6];
3180 Ops[0] = getRoot();
3181 for (int x = 1; x < 6; ++x)
3182 Ops[x] = getValue(I.getOperand(x));
3183
3184 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3185 return 0;
3186 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003187 case Intrinsic::atomic_lcs: {
3188 SDOperand Root = getRoot();
3189 SDOperand O3 = getValue(I.getOperand(3));
3190 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3191 getValue(I.getOperand(1)),
3192 getValue(I.getOperand(2)),
3193 O3, O3.getValueType());
3194 setValue(&I, L);
3195 DAG.setRoot(L.getValue(1));
3196 return 0;
3197 }
3198 case Intrinsic::atomic_las: {
3199 SDOperand Root = getRoot();
3200 SDOperand O2 = getValue(I.getOperand(2));
3201 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LAS, Root,
3202 getValue(I.getOperand(1)),
3203 O2, O2.getValueType());
3204 setValue(&I, L);
3205 DAG.setRoot(L.getValue(1));
3206 return 0;
3207 }
3208 case Intrinsic::atomic_swap: {
3209 SDOperand Root = getRoot();
3210 SDOperand O2 = getValue(I.getOperand(2));
3211 SDOperand L = DAG.getAtomic(ISD::ATOMIC_SWAP, Root,
3212 getValue(I.getOperand(1)),
3213 O2, O2.getValueType());
3214 setValue(&I, L);
3215 DAG.setRoot(L.getValue(1));
3216 return 0;
3217 }
3218
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003219 }
3220}
3221
3222
Duncan Sands6f74b482007-12-19 09:48:52 +00003223void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003224 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003225 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003226 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003227 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003228 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3229 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003230
Jim Laskey735b6f82007-02-22 15:38:06 +00003231 TargetLowering::ArgListTy Args;
3232 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003233 Args.reserve(CS.arg_size());
3234 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3235 i != e; ++i) {
3236 SDOperand ArgNode = getValue(*i);
3237 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003238
Duncan Sands6f74b482007-12-19 09:48:52 +00003239 unsigned attrInd = i - CS.arg_begin() + 1;
3240 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3241 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3242 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3243 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3244 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3245 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003246 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003247 Args.push_back(Entry);
3248 }
3249
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003250 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003251 // Insert a label before the invoke call to mark the try range. This can be
3252 // used to detect deletion of the invoke via the MachineModuleInfo.
3253 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003254 // Both PendingLoads and PendingExports must be flushed here;
3255 // this call might not return.
3256 (void)getRoot();
3257 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003258 DAG.getConstant(BeginLabel, MVT::i32),
3259 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003260 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003261
Jim Laskey735b6f82007-02-22 15:38:06 +00003262 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003263 TLI.LowerCallTo(getRoot(), CS.getType(),
3264 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003265 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003266 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003267 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003268 if (CS.getType() != Type::VoidTy)
3269 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003270 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003271
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003272 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003273 // Insert a label at the end of the invoke call to mark the try range. This
3274 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3275 EndLabel = MMI->NextLabelID();
3276 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003277 DAG.getConstant(EndLabel, MVT::i32),
3278 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003279
Duncan Sands6f74b482007-12-19 09:48:52 +00003280 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003281 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3282 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003283}
3284
3285
Chris Lattner1c08c712005-01-07 07:47:53 +00003286void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003287 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003288 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003289 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003290 if (unsigned IID = F->getIntrinsicID()) {
3291 RenameFn = visitIntrinsicCall(I, IID);
3292 if (!RenameFn)
3293 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003294 }
3295 }
3296
3297 // Check for well-known libc/libm calls. If the function is internal, it
3298 // can't be a library call.
3299 unsigned NameLen = F->getNameLen();
3300 if (!F->hasInternalLinkage() && NameLen) {
3301 const char *NameStr = F->getNameStart();
3302 if (NameStr[0] == 'c' &&
3303 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3304 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3305 if (I.getNumOperands() == 3 && // Basic sanity checks.
3306 I.getOperand(1)->getType()->isFloatingPoint() &&
3307 I.getType() == I.getOperand(1)->getType() &&
3308 I.getType() == I.getOperand(2)->getType()) {
3309 SDOperand LHS = getValue(I.getOperand(1));
3310 SDOperand RHS = getValue(I.getOperand(2));
3311 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3312 LHS, RHS));
3313 return;
3314 }
3315 } else if (NameStr[0] == 'f' &&
3316 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003317 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3318 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003319 if (I.getNumOperands() == 2 && // Basic sanity checks.
3320 I.getOperand(1)->getType()->isFloatingPoint() &&
3321 I.getType() == I.getOperand(1)->getType()) {
3322 SDOperand Tmp = getValue(I.getOperand(1));
3323 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3324 return;
3325 }
3326 } else if (NameStr[0] == 's' &&
3327 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003328 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3329 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003330 if (I.getNumOperands() == 2 && // Basic sanity checks.
3331 I.getOperand(1)->getType()->isFloatingPoint() &&
3332 I.getType() == I.getOperand(1)->getType()) {
3333 SDOperand Tmp = getValue(I.getOperand(1));
3334 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3335 return;
3336 }
3337 } else if (NameStr[0] == 'c' &&
3338 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003339 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3340 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003341 if (I.getNumOperands() == 2 && // Basic sanity checks.
3342 I.getOperand(1)->getType()->isFloatingPoint() &&
3343 I.getType() == I.getOperand(1)->getType()) {
3344 SDOperand Tmp = getValue(I.getOperand(1));
3345 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3346 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003347 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003348 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003349 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003350 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003351 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003352 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003353 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003354
Chris Lattner64e14b12005-01-08 22:48:57 +00003355 SDOperand Callee;
3356 if (!RenameFn)
3357 Callee = getValue(I.getOperand(0));
3358 else
3359 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003360
Duncan Sands6f74b482007-12-19 09:48:52 +00003361 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003362}
3363
Jim Laskey735b6f82007-02-22 15:38:06 +00003364
Dan Gohmanef5d1942008-03-11 21:11:25 +00003365void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003366 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003367 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3368 setValue(&I, Undef);
Chris Lattner6833b062008-04-28 07:16:35 +00003369 return;
Dan Gohman3dc34f62008-04-23 20:21:29 +00003370 }
Chris Lattner6833b062008-04-28 07:16:35 +00003371
3372 // To add support for individual return values with aggregate types,
3373 // we'd need a way to take a getresult index and determine which
3374 // values of the Call SDNode are associated with it.
3375 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3376 "Individual return values must not be aggregates!");
3377
3378 SDOperand Call = getValue(I.getOperand(0));
3379 setValue(&I, SDOperand(Call.Val, I.getIndex()));
Dan Gohmanef5d1942008-03-11 21:11:25 +00003380}
3381
3382
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003383/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3384/// this value and returns the result as a ValueVT value. This uses
3385/// Chain/Flag as the input and updates them for the output Chain/Flag.
3386/// If the Flag pointer is NULL, no flag is used.
3387SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner6833b062008-04-28 07:16:35 +00003388 SDOperand &Chain,
3389 SDOperand *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003390 // Assemble the legal parts into the final values.
3391 SmallVector<SDOperand, 4> Values(ValueVTs.size());
Chris Lattner6833b062008-04-28 07:16:35 +00003392 SmallVector<SDOperand, 8> Parts;
3393 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003394 // Copy the legal parts from the registers.
3395 MVT::ValueType ValueVT = ValueVTs[Value];
3396 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3397 MVT::ValueType RegisterVT = RegVTs[Value];
3398
Chris Lattner6833b062008-04-28 07:16:35 +00003399 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003400 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003401 SDOperand P;
3402 if (Flag == 0)
3403 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3404 else {
3405 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003406 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003407 }
3408 Chain = P.getValue(1);
Dan Gohman23ce5022008-04-25 18:27:55 +00003409 Parts[Part+i] = P;
3410 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003411
Dan Gohman23ce5022008-04-25 18:27:55 +00003412 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3413 ValueVT);
3414 Part += NumRegs;
3415 }
Chris Lattner6833b062008-04-28 07:16:35 +00003416
3417 if (ValueVTs.size() == 1)
3418 return Values[0];
3419
Dan Gohman23ce5022008-04-25 18:27:55 +00003420 return DAG.getNode(ISD::MERGE_VALUES,
3421 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3422 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003423}
3424
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003425/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3426/// specified value into the registers specified by this object. This uses
3427/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003428/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003429void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003430 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003431 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003432 unsigned NumRegs = Regs.size();
3433 SmallVector<SDOperand, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003434 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003435 MVT::ValueType ValueVT = ValueVTs[Value];
3436 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3437 MVT::ValueType RegisterVT = RegVTs[Value];
3438
3439 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3440 &Parts[Part], NumParts, RegisterVT);
3441 Part += NumParts;
3442 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003443
3444 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003445 SmallVector<SDOperand, 8> Chains(NumRegs);
3446 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003447 SDOperand Part;
3448 if (Flag == 0)
3449 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3450 else {
3451 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003452 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003453 }
3454 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003455 }
Chris Lattner6833b062008-04-28 07:16:35 +00003456
3457 if (NumRegs == 1)
3458 Chain = Chains[0];
3459 else
3460 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003461}
Chris Lattner864635a2006-02-22 22:37:12 +00003462
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003463/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3464/// operand list. This adds the code marker and includes the number of
3465/// values added into it.
3466void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003467 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00003468 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3469 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003470 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3471 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Dan Gohman23ce5022008-04-25 18:27:55 +00003472 MVT::ValueType RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003473 for (unsigned i = 0; i != NumRegs; ++i)
3474 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003475 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003476}
Chris Lattner864635a2006-02-22 22:37:12 +00003477
3478/// isAllocatableRegister - If the specified register is safe to allocate,
3479/// i.e. it isn't a stack pointer or some other special register, return the
3480/// register class for the register. Otherwise, return null.
3481static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003482isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003483 const TargetLowering &TLI,
3484 const TargetRegisterInfo *TRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003485 MVT::ValueType FoundVT = MVT::Other;
3486 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003487 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3488 E = TRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003489 MVT::ValueType ThisVT = MVT::Other;
3490
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003491 const TargetRegisterClass *RC = *RCI;
3492 // If none of the the value types for this register class are valid, we
3493 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003494 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3495 I != E; ++I) {
3496 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003497 // If we have already found this register in a different register class,
3498 // choose the one with the largest VT specified. For example, on
3499 // PowerPC, we favor f64 register classes over f32.
3500 if (FoundVT == MVT::Other ||
3501 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3502 ThisVT = *I;
3503 break;
3504 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003505 }
3506 }
3507
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003508 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003509
Chris Lattner864635a2006-02-22 22:37:12 +00003510 // NOTE: This isn't ideal. In particular, this might allocate the
3511 // frame pointer in functions that need it (due to them not being taken
3512 // out of allocation, because a variable sized allocation hasn't been seen
3513 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003514 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3515 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003516 if (*I == Reg) {
3517 // We found a matching register class. Keep looking at others in case
3518 // we find one with larger registers that this physreg is also in.
3519 FoundRC = RC;
3520 FoundVT = ThisVT;
3521 break;
3522 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003523 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003524 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003525}
3526
Chris Lattner4e4b5762006-02-01 18:59:47 +00003527
Chris Lattner0c583402007-04-28 20:49:53 +00003528namespace {
3529/// AsmOperandInfo - This contains information for each constraint that we are
3530/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003531struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3532 /// CallOperand - If this is the result output operand or a clobber
3533 /// this is null, otherwise it is the incoming operand to the CallInst.
3534 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003535 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003536
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003537 /// AssignedRegs - If this is a register or register class operand, this
3538 /// contains the set of register corresponding to the operand.
3539 RegsForValue AssignedRegs;
3540
Dan Gohman23ce5022008-04-25 18:27:55 +00003541 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003542 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003543 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003544
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003545 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3546 /// busy in OutputRegs/InputRegs.
3547 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3548 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003549 std::set<unsigned> &InputRegs,
3550 const TargetRegisterInfo &TRI) const {
3551 if (isOutReg) {
3552 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3553 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3554 }
3555 if (isInReg) {
3556 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3557 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3558 }
3559 }
3560
3561private:
3562 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3563 /// specified set.
3564 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3565 const TargetRegisterInfo &TRI) {
3566 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3567 Regs.insert(Reg);
3568 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3569 for (; *Aliases; ++Aliases)
3570 Regs.insert(*Aliases);
3571 }
Chris Lattner0c583402007-04-28 20:49:53 +00003572};
3573} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003574
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003575
Chris Lattner0fe71e92008-02-21 19:43:13 +00003576/// GetRegistersForValue - Assign registers (virtual or physical) for the
3577/// specified operand. We prefer to assign virtual registers, to allow the
3578/// register allocator handle the assignment process. However, if the asm uses
3579/// features that we can't model on machineinstrs, we have SDISel do the
3580/// allocation. This produces generally horrible, but correct, code.
3581///
3582/// OpInfo describes the operand.
3583/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3584/// or any explicitly clobbered registers.
3585/// Input and OutputRegs are the set of already allocated physical registers.
3586///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003587void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003588GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003589 std::set<unsigned> &OutputRegs,
3590 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003591 // Compute whether this value requires an input register, an output register,
3592 // or both.
3593 bool isOutReg = false;
3594 bool isInReg = false;
3595 switch (OpInfo.Type) {
3596 case InlineAsm::isOutput:
3597 isOutReg = true;
3598
3599 // If this is an early-clobber output, or if there is an input
3600 // constraint that matches this, we need to reserve the input register
3601 // so no other inputs allocate to it.
3602 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3603 break;
3604 case InlineAsm::isInput:
3605 isInReg = true;
3606 isOutReg = false;
3607 break;
3608 case InlineAsm::isClobber:
3609 isOutReg = true;
3610 isInReg = true;
3611 break;
3612 }
3613
3614
3615 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003616 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003617
3618 // If this is a constraint for a single physreg, or a constraint for a
3619 // register class, find it.
3620 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3621 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3622 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003623
3624 unsigned NumRegs = 1;
3625 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003626 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003627 MVT::ValueType RegVT;
3628 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3629
Chris Lattnerbf996f12007-04-30 17:29:31 +00003630
3631 // If this is a constraint for a specific physical register, like {r17},
3632 // assign it now.
3633 if (PhysReg.first) {
3634 if (OpInfo.ConstraintVT == MVT::Other)
3635 ValueVT = *PhysReg.second->vt_begin();
3636
3637 // Get the actual register value type. This is important, because the user
3638 // may have asked for (e.g.) the AX register in i32 type. We need to
3639 // remember that AX is actually i16 to get the right extension.
3640 RegVT = *PhysReg.second->vt_begin();
3641
3642 // This is a explicit reference to a physical register.
3643 Regs.push_back(PhysReg.first);
3644
3645 // If this is an expanded reference, add the rest of the regs to Regs.
3646 if (NumRegs != 1) {
3647 TargetRegisterClass::iterator I = PhysReg.second->begin();
3648 TargetRegisterClass::iterator E = PhysReg.second->end();
3649 for (; *I != PhysReg.first; ++I)
3650 assert(I != E && "Didn't find reg!");
3651
3652 // Already added the first reg.
3653 --NumRegs; ++I;
3654 for (; NumRegs; --NumRegs, ++I) {
3655 assert(I != E && "Ran out of registers to allocate!");
3656 Regs.push_back(*I);
3657 }
3658 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003659 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003660 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3661 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003662 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003663 }
3664
3665 // Otherwise, if this was a reference to an LLVM register class, create vregs
3666 // for this reference.
3667 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003668 const TargetRegisterClass *RC = PhysReg.second;
3669 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003670 // If this is an early clobber or tied register, our regalloc doesn't know
3671 // how to maintain the constraint. If it isn't, go ahead and create vreg
3672 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003673 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3674 // If there is some other early clobber and this is an input register,
3675 // then we are forced to pre-allocate the input reg so it doesn't
3676 // conflict with the earlyclobber.
3677 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003678 RegVT = *PhysReg.second->vt_begin();
3679
3680 if (OpInfo.ConstraintVT == MVT::Other)
3681 ValueVT = RegVT;
3682
3683 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00003684 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003685 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00003686 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00003687
Dan Gohman23ce5022008-04-25 18:27:55 +00003688 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003689 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003690 }
3691
3692 // Otherwise, we can't allocate it. Let the code below figure out how to
3693 // maintain these constraints.
3694 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3695
3696 } else {
3697 // This is a reference to a register class that doesn't directly correspond
3698 // to an LLVM register class. Allocate NumRegs consecutive, available,
3699 // registers from the class.
3700 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3701 OpInfo.ConstraintVT);
3702 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003703
Dan Gohman6f0d0242008-02-10 18:45:23 +00003704 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003705 unsigned NumAllocated = 0;
3706 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3707 unsigned Reg = RegClassRegs[i];
3708 // See if this register is available.
3709 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3710 (isInReg && InputRegs.count(Reg))) { // Already used.
3711 // Make sure we find consecutive registers.
3712 NumAllocated = 0;
3713 continue;
3714 }
3715
3716 // Check to see if this register is allocatable (i.e. don't give out the
3717 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003718 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00003719 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003720 if (!RC) { // Couldn't allocate this register.
3721 // Reset NumAllocated to make sure we return consecutive registers.
3722 NumAllocated = 0;
3723 continue;
3724 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003725 }
3726
3727 // Okay, this register is good, we can use it.
3728 ++NumAllocated;
3729
3730 // If we allocated enough consecutive registers, succeed.
3731 if (NumAllocated == NumRegs) {
3732 unsigned RegStart = (i-NumAllocated)+1;
3733 unsigned RegEnd = i+1;
3734 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003735 for (unsigned i = RegStart; i != RegEnd; ++i)
3736 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003737
Dan Gohman23ce5022008-04-25 18:27:55 +00003738 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003739 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003740 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003741 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003742 }
3743 }
3744
3745 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003746 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003747}
3748
3749
Chris Lattnerce7518c2006-01-26 22:24:51 +00003750/// visitInlineAsm - Handle a call to an InlineAsm object.
3751///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003752void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3753 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003754
Chris Lattner0c583402007-04-28 20:49:53 +00003755 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00003756 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003757
3758 SDOperand Chain = getRoot();
3759 SDOperand Flag;
3760
Chris Lattner4e4b5762006-02-01 18:59:47 +00003761 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003762
Chris Lattner0c583402007-04-28 20:49:53 +00003763 // Do a prepass over the constraints, canonicalizing them, and building up the
3764 // ConstraintOperands list.
3765 std::vector<InlineAsm::ConstraintInfo>
3766 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003767
3768 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3769 // constraint. If so, we can't let the register allocator allocate any input
3770 // registers, because it will not know to avoid the earlyclobbered output reg.
3771 bool SawEarlyClobber = false;
3772
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003773 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00003774 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00003775 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003776 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3777 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00003778
Chris Lattner0c583402007-04-28 20:49:53 +00003779 MVT::ValueType OpVT = MVT::Other;
3780
3781 // Compute the value type for each operand.
3782 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003783 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00003784 // Indirect outputs just consume an argument.
3785 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003786 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00003787 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003788 }
Chris Lattneracf8b012008-04-27 23:44:28 +00003789 // The return value of the call is this value. As such, there is no
3790 // corresponding argument.
3791 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3792 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3793 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3794 } else {
3795 assert(ResNo == 0 && "Asm only has one result!");
3796 OpVT = TLI.getValueType(CS.getType());
3797 }
3798 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003799 break;
3800 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003801 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003802 break;
3803 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003804 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003805 break;
3806 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003807
Chris Lattner0c583402007-04-28 20:49:53 +00003808 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003809 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00003810 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00003811 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3812 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003813 else {
3814 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3815 const Type *OpTy = OpInfo.CallOperandVal->getType();
3816 // If this is an indirect operand, the operand is a pointer to the
3817 // accessed type.
3818 if (OpInfo.isIndirect)
3819 OpTy = cast<PointerType>(OpTy)->getElementType();
3820
3821 // If OpTy is not a first-class value, it may be a struct/union that we
3822 // can tile with integers.
3823 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3824 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3825 switch (BitSize) {
3826 default: break;
3827 case 1:
3828 case 8:
3829 case 16:
3830 case 32:
3831 case 64:
3832 OpTy = IntegerType::get(BitSize);
3833 break;
3834 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003835 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003836
3837 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003838 }
3839 }
3840
3841 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003842
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003843 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00003844 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00003845
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003846 // Keep track of whether we see an earlyclobber.
3847 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003848
Chris Lattner0fe71e92008-02-21 19:43:13 +00003849 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00003850 if (!SawEarlyClobber &&
3851 OpInfo.Type == InlineAsm::isClobber &&
3852 OpInfo.ConstraintType == TargetLowering::C_Register) {
3853 // Note that we want to ignore things that we don't trick here, like
3854 // dirflag, fpsr, flags, etc.
3855 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3856 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3857 OpInfo.ConstraintVT);
3858 if (PhysReg.first || PhysReg.second) {
3859 // This is a register we know of.
3860 SawEarlyClobber = true;
3861 }
3862 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00003863
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003864 // If this is a memory input, and if the operand is not indirect, do what we
3865 // need to to provide an address for the memory input.
3866 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3867 !OpInfo.isIndirect) {
3868 assert(OpInfo.Type == InlineAsm::isInput &&
3869 "Can only indirectify direct input operands!");
3870
3871 // Memory operands really want the address of the value. If we don't have
3872 // an indirect input, put it in the constpool if we can, otherwise spill
3873 // it to a stack slot.
3874
3875 // If the operand is a float, integer, or vector constant, spill to a
3876 // constant pool entry to get its address.
3877 Value *OpVal = OpInfo.CallOperandVal;
3878 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3879 isa<ConstantVector>(OpVal)) {
3880 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3881 TLI.getPointerTy());
3882 } else {
3883 // Otherwise, create a stack slot and emit a store to it before the
3884 // asm.
3885 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00003886 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003887 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3888 MachineFunction &MF = DAG.getMachineFunction();
3889 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3890 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3891 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3892 OpInfo.CallOperand = StackSlot;
3893 }
3894
3895 // There is no longer a Value* corresponding to this operand.
3896 OpInfo.CallOperandVal = 0;
3897 // It is now an indirect operand.
3898 OpInfo.isIndirect = true;
3899 }
3900
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003901 // If this constraint is for a specific register, allocate it before
3902 // anything else.
3903 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3904 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00003905 }
Chris Lattner0c583402007-04-28 20:49:53 +00003906 ConstraintInfos.clear();
3907
3908
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003909 // Second pass - Loop over all of the operands, assigning virtual or physregs
3910 // to registerclass operands.
3911 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003912 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003913
3914 // C_Register operands have already been allocated, Other/Memory don't need
3915 // to be.
3916 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3917 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3918 }
3919
Chris Lattner0c583402007-04-28 20:49:53 +00003920 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3921 std::vector<SDOperand> AsmNodeOperands;
3922 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3923 AsmNodeOperands.push_back(
3924 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3925
Chris Lattner2cc2f662006-02-01 01:28:23 +00003926
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003927 // Loop over all of the inputs, copying the operand values into the
3928 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00003929 RegsForValue RetValRegs;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003930
Chris Lattner0c583402007-04-28 20:49:53 +00003931 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3932 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3933
3934 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003935 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00003936
Chris Lattner0c583402007-04-28 20:49:53 +00003937 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00003938 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00003939 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3940 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00003941 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003942 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00003943
Chris Lattner22873462006-02-27 23:45:39 +00003944 // Add information to the INLINEASM node to know about this output.
3945 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003946 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3947 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003948 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00003949 break;
3950 }
3951
Chris Lattner2a600be2007-04-28 21:01:43 +00003952 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00003953
Chris Lattner864635a2006-02-22 22:37:12 +00003954 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003955 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003956 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003957 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003958 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003959 exit(1);
3960 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003961
Chris Lattner0c583402007-04-28 20:49:53 +00003962 if (!OpInfo.isIndirect) {
3963 // This is the result value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00003964 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00003965 "Cannot have multiple output constraints yet!");
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003966 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003967 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00003968 } else {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003969 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00003970 OpInfo.CallOperandVal));
Chris Lattner2cc2f662006-02-01 01:28:23 +00003971 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003972
3973 // Add information to the INLINEASM node to know that this register is
3974 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003975 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3976 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003977 break;
3978 }
3979 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00003980 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00003981
Chris Lattner0c583402007-04-28 20:49:53 +00003982 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00003983 // If this is required to match an output register we have already set,
3984 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00003985 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00003986
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003987 // Scan until we find the definition we already emitted of this operand.
3988 // When we find it, create a RegsForValue operand.
3989 unsigned CurOp = 2; // The first operand.
3990 for (; OperandNo; --OperandNo) {
3991 // Advance to the next operand.
3992 unsigned NumOps =
3993 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00003994 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3995 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003996 "Skipped past definitions?");
3997 CurOp += (NumOps>>3)+1;
3998 }
3999
4000 unsigned NumOps =
4001 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004002 if ((NumOps & 7) == 2 /*REGDEF*/) {
4003 // Add NumOps>>3 registers to MatchedRegs.
4004 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004005 MatchedRegs.TLI = &TLI;
4006 MatchedRegs.ValueVTs.resize(1, InOperandVal.getValueType());
4007 MatchedRegs.RegVTs.resize(1, AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004008 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4009 unsigned Reg =
4010 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4011 MatchedRegs.Regs.push_back(Reg);
4012 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004013
Chris Lattner527fae12007-02-01 01:21:12 +00004014 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004015 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004016 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4017 break;
4018 } else {
4019 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004020 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4021 // Add information to the INLINEASM node to know about this input.
4022 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4023 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4024 TLI.getPointerTy()));
4025 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4026 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004027 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004028 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004029
Chris Lattner2a600be2007-04-28 21:01:43 +00004030 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004031 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004032 "Don't know how to handle indirect other inputs yet!");
4033
Chris Lattner48884cd2007-08-25 00:47:38 +00004034 std::vector<SDOperand> Ops;
4035 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4036 Ops, DAG);
4037 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004038 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004039 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004040 exit(1);
4041 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004042
4043 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004044 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004045 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4046 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004047 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004048 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004049 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004050 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004051 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4052 "Memory operands expect pointer values");
4053
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004054 // Add information to the INLINEASM node to know about this input.
4055 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004056 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4057 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004058 AsmNodeOperands.push_back(InOperandVal);
4059 break;
4060 }
4061
Chris Lattner2a600be2007-04-28 21:01:43 +00004062 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4063 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4064 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004065 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004066 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004067
4068 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004069 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4070 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004071
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004072 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004073
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004074 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4075 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004076 break;
4077 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004078 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004079 // Add the clobbered value to the operand list, so that the register
4080 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004081 if (!OpInfo.AssignedRegs.Regs.empty())
4082 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4083 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004084 break;
4085 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004086 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004087 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004088
4089 // Finish up input operands.
4090 AsmNodeOperands[0] = Chain;
4091 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4092
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004093 Chain = DAG.getNode(ISD::INLINEASM,
4094 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004095 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004096 Flag = Chain.getValue(1);
4097
Chris Lattner6656dd12006-01-31 02:03:41 +00004098 // If this asm returns a register value, copy the result from that register
4099 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004100 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004101 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3a508c92007-04-12 06:00:20 +00004102
4103 // If the result of the inline asm is a vector, it may have the wrong
4104 // width/num elts. Make sure to convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004105 // bit_convert.
4106 if (MVT::isVector(Val.getValueType())) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004107 const VectorType *VTy = cast<VectorType>(CS.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004108 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
Chris Lattner3a508c92007-04-12 06:00:20 +00004109
Dan Gohman7f321562007-06-25 16:23:39 +00004110 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004111 }
4112
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004113 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004114 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004115
Chris Lattner6656dd12006-01-31 02:03:41 +00004116 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4117
4118 // Process indirect outputs, first output all of the flagged copies out of
4119 // physregs.
4120 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004121 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004122 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004123 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004124 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004125 }
4126
4127 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004128 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004129 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004130 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004131 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004132 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004133 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004134 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4135 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004136 DAG.setRoot(Chain);
4137}
4138
4139
Chris Lattner1c08c712005-01-07 07:47:53 +00004140void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4141 SDOperand Src = getValue(I.getOperand(0));
4142
4143 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004144
4145 if (IntPtr < Src.getValueType())
4146 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4147 else if (IntPtr > Src.getValueType())
4148 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004149
4150 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004151 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004152 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004153 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004154
Reid Spencer47857812006-12-31 05:55:36 +00004155 TargetLowering::ArgListTy Args;
4156 TargetLowering::ArgListEntry Entry;
4157 Entry.Node = Src;
4158 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004159 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004160
4161 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004162 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4163 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004164 setValue(&I, Result.first); // Pointers always fit in registers
4165 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004166}
4167
4168void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004169 TargetLowering::ArgListTy Args;
4170 TargetLowering::ArgListEntry Entry;
4171 Entry.Node = getValue(I.getOperand(0));
4172 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004173 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00004174 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004175 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004176 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4177 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004178 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4179 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004180}
4181
Evan Chengff9b3732008-01-30 18:18:23 +00004182// EmitInstrWithCustomInserter - This method should be implemented by targets
4183// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004184// instructions are special in various ways, which require special support to
4185// insert. The specified MachineInstr is created but not inserted into any
4186// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004187MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004188 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004189 cerr << "If a target marks an instruction with "
4190 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004191 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004192 abort();
4193 return 0;
4194}
4195
Chris Lattner39ae3622005-01-09 00:00:49 +00004196void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004197 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4198 getValue(I.getOperand(1)),
4199 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004200}
4201
4202void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004203 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4204 getValue(I.getOperand(0)),
4205 DAG.getSrcValue(I.getOperand(0)));
4206 setValue(&I, V);
4207 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004208}
4209
4210void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004211 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4212 getValue(I.getOperand(1)),
4213 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004214}
4215
4216void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004217 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4218 getValue(I.getOperand(1)),
4219 getValue(I.getOperand(2)),
4220 DAG.getSrcValue(I.getOperand(1)),
4221 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004222}
4223
Chris Lattnerfdfded52006-04-12 16:20:43 +00004224/// TargetLowering::LowerArguments - This is the default LowerArguments
4225/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004226/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4227/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004228std::vector<SDOperand>
4229TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4230 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4231 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004232 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004233 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4234 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4235
4236 // Add one result value for each formal argument.
4237 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004238 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004239 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4240 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004241 MVT::ValueType VT = getValueType(I->getType());
Duncan Sands276dcbd2008-03-21 09:14:45 +00004242 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004243 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004244 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004245
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004246 if (F.paramHasAttr(j, ParamAttr::ZExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004247 Flags.setZExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004248 if (F.paramHasAttr(j, ParamAttr::SExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004249 Flags.setSExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004250 if (F.paramHasAttr(j, ParamAttr::InReg))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004251 Flags.setInReg();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004252 if (F.paramHasAttr(j, ParamAttr::StructRet))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004253 Flags.setSRet();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004254 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004255 Flags.setByVal();
Rafael Espindola594d37e2007-08-10 14:44:42 +00004256 const PointerType *Ty = cast<PointerType>(I->getType());
Duncan Sandsa41d7192008-01-13 21:19:59 +00004257 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004258 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004259 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004260 // For ByVal, alignment should be passed from FE. BE will guess if
4261 // this info is not there but there are cases it cannot get right.
4262 if (F.getParamAlignment(j))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004263 FrameAlign = F.getParamAlignment(j);
4264 Flags.setByValAlign(FrameAlign);
4265 Flags.setByValSize(FrameSize);
Rafael Espindola594d37e2007-08-10 14:44:42 +00004266 }
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004267 if (F.paramHasAttr(j, ParamAttr::Nest))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004268 Flags.setNest();
4269 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004270
4271 MVT::ValueType RegisterVT = getRegisterType(VT);
4272 unsigned NumRegs = getNumRegisters(VT);
4273 for (unsigned i = 0; i != NumRegs; ++i) {
4274 RetVals.push_back(RegisterVT);
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004275 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004276 if (NumRegs > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004277 MyFlags.setSplit();
Duncan Sandsb988bac2008-02-11 20:58:28 +00004278 // if it isn't first piece, alignment must be 1
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004279 else if (i > 0)
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004280 MyFlags.setOrigAlign(1);
4281 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004282 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004283 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004284
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004285 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004286
4287 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004288 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004289 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004290 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004291
4292 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4293 // allows exposing the loads that may be part of the argument access to the
4294 // first DAGCombiner pass.
4295 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4296
4297 // The number of results should match up, except that the lowered one may have
4298 // an extra flag result.
4299 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4300 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4301 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4302 && "Lowering produced unexpected number of results!");
4303 Result = TmpRes.Val;
4304
Dan Gohman27a70be2007-07-02 16:18:06 +00004305 unsigned NumArgRegs = Result->getNumValues() - 1;
4306 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004307
4308 // Set up the return result vector.
4309 Ops.clear();
4310 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004311 unsigned Idx = 1;
4312 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4313 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004314 MVT::ValueType VT = getValueType(I->getType());
Duncan Sandsb988bac2008-02-11 20:58:28 +00004315 MVT::ValueType PartVT = getRegisterType(VT);
4316
4317 unsigned NumParts = getNumRegisters(VT);
4318 SmallVector<SDOperand, 4> Parts(NumParts);
4319 for (unsigned j = 0; j != NumParts; ++j)
4320 Parts[j] = SDOperand(Result, i++);
4321
4322 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4323 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4324 AssertOp = ISD::AssertSext;
4325 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4326 AssertOp = ISD::AssertZext;
4327
4328 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
Chris Lattner4468c1f2008-03-09 09:38:46 +00004329 AssertOp));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004330 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004331 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004332 return Ops;
4333}
4334
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004335
4336/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4337/// implementation, which just inserts an ISD::CALL node, which is later custom
4338/// lowered by the target to something concrete. FIXME: When all targets are
4339/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4340std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004341TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4342 bool RetSExt, bool RetZExt, bool isVarArg,
4343 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004344 SDOperand Callee,
4345 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004346 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004347 Ops.push_back(Chain); // Op#0 - Chain
4348 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4349 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4350 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4351 Ops.push_back(Callee);
4352
4353 // Handle all of the outgoing arguments.
4354 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00004355 MVT::ValueType VT = getValueType(Args[i].Ty);
4356 SDOperand Op = Args[i].Node;
Duncan Sands276dcbd2008-03-21 09:14:45 +00004357 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004358 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004359 getTargetData()->getABITypeAlignment(Args[i].Ty);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004360
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004361 if (Args[i].isZExt)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004362 Flags.setZExt();
4363 if (Args[i].isSExt)
4364 Flags.setSExt();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004365 if (Args[i].isInReg)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004366 Flags.setInReg();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004367 if (Args[i].isSRet)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004368 Flags.setSRet();
Rafael Espindola21485be2007-08-20 15:18:24 +00004369 if (Args[i].isByVal) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004370 Flags.setByVal();
Rafael Espindola21485be2007-08-20 15:18:24 +00004371 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004372 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004373 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004374 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004375 // For ByVal, alignment should come from FE. BE will guess if this
4376 // info is not there but there are cases it cannot get right.
4377 if (Args[i].Alignment)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004378 FrameAlign = Args[i].Alignment;
4379 Flags.setByValAlign(FrameAlign);
4380 Flags.setByValSize(FrameSize);
Rafael Espindola21485be2007-08-20 15:18:24 +00004381 }
Duncan Sands36397f52007-07-27 12:58:54 +00004382 if (Args[i].isNest)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004383 Flags.setNest();
4384 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004385
Duncan Sandsb988bac2008-02-11 20:58:28 +00004386 MVT::ValueType PartVT = getRegisterType(VT);
4387 unsigned NumParts = getNumRegisters(VT);
4388 SmallVector<SDOperand, 4> Parts(NumParts);
4389 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4390
4391 if (Args[i].isSExt)
4392 ExtendKind = ISD::SIGN_EXTEND;
4393 else if (Args[i].isZExt)
4394 ExtendKind = ISD::ZERO_EXTEND;
4395
4396 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4397
4398 for (unsigned i = 0; i != NumParts; ++i) {
4399 // if it isn't first piece, alignment must be 1
Duncan Sands276dcbd2008-03-21 09:14:45 +00004400 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004401 if (NumParts > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004402 MyFlags.setSplit();
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004403 else if (i != 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004404 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004405
4406 Ops.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004407 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohman27a70be2007-07-02 16:18:06 +00004408 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004409 }
4410
Dan Gohmanef5d1942008-03-11 21:11:25 +00004411 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004412 // the potentially illegal return value types.
Dan Gohmanef5d1942008-03-11 21:11:25 +00004413 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4414 SmallVector<MVT::ValueType, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004415 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004416
Dan Gohman23ce5022008-04-25 18:27:55 +00004417 // Then we translate that to a list of legal types.
4418 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4419 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004420 MVT::ValueType RegisterVT = getRegisterType(VT);
4421 unsigned NumRegs = getNumRegisters(VT);
4422 for (unsigned i = 0; i != NumRegs; ++i)
4423 LoweredRetTys.push_back(RegisterVT);
4424 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004425
Dan Gohmanef5d1942008-03-11 21:11:25 +00004426 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004427
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004428 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004429 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004430 DAG.getVTList(&LoweredRetTys[0],
4431 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004432 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004433 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004434
4435 // Gather up the call result into a single value.
4436 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004437 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4438
4439 if (RetSExt)
4440 AssertOp = ISD::AssertSext;
4441 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004442 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004443
Dan Gohmanef5d1942008-03-11 21:11:25 +00004444 SmallVector<SDOperand, 4> ReturnValues;
4445 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004446 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4447 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004448 MVT::ValueType RegisterVT = getRegisterType(VT);
4449 unsigned NumRegs = getNumRegisters(VT);
4450 unsigned RegNoEnd = NumRegs + RegNo;
4451 SmallVector<SDOperand, 4> Results;
4452 for (; RegNo != RegNoEnd; ++RegNo)
4453 Results.push_back(Res.getValue(RegNo));
4454 SDOperand ReturnValue =
4455 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4456 AssertOp);
4457 ReturnValues.push_back(ReturnValue);
4458 }
4459 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4460 DAG.getNode(ISD::MERGE_VALUES,
4461 DAG.getVTList(&RetTys[0], RetTys.size()),
4462 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004463 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004464
4465 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004466}
4467
Chris Lattner50381b62005-05-14 05:50:48 +00004468SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004469 assert(0 && "LowerOperation not implemented for this target!");
4470 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004471 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004472}
4473
Nate Begeman0aed7842006-01-28 03:14:31 +00004474SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4475 SelectionDAG &DAG) {
4476 assert(0 && "CustomPromoteOperation not implemented for this target!");
4477 abort();
4478 return SDOperand();
4479}
4480
Chris Lattner7041ee32005-01-11 05:56:49 +00004481//===----------------------------------------------------------------------===//
4482// SelectionDAGISel code
4483//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004484
4485unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004486 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004487}
4488
Chris Lattner495a0b52005-08-17 06:37:43 +00004489void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004490 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004491 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004492 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004493}
Chris Lattner1c08c712005-01-07 07:47:53 +00004494
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004495
Chris Lattnerbad7f482006-10-28 19:22:10 +00004496
Chris Lattner1c08c712005-01-07 07:47:53 +00004497bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004498 // Get alias analysis for load/store combining.
4499 AA = &getAnalysis<AliasAnalysis>();
4500
Chris Lattner1c08c712005-01-07 07:47:53 +00004501 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004502 if (MF.getFunction()->hasCollector())
4503 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4504 else
4505 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004506 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004507 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004508
4509 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4510
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004511 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4512 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4513 // Mark landing pad.
4514 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004515
4516 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004517 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004518
Evan Chengad2070c2007-02-10 02:43:39 +00004519 // Add function live-ins to entry block live-in set.
4520 BasicBlock *EntryBB = &Fn.getEntryBlock();
4521 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004522 if (!RegInfo->livein_empty())
4523 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4524 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004525 BB->addLiveIn(I->first);
4526
Duncan Sandsf4070822007-06-15 19:04:19 +00004527#ifndef NDEBUG
4528 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4529 "Not all catch info was assigned to a landing pad!");
4530#endif
4531
Chris Lattner1c08c712005-01-07 07:47:53 +00004532 return true;
4533}
4534
Chris Lattner6833b062008-04-28 07:16:35 +00004535void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004536 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004537 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004538 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004539 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004540 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004541
Dan Gohman23ce5022008-04-25 18:27:55 +00004542 RegsForValue RFV(TLI, Reg, V->getType());
4543 SDOperand Chain = DAG.getEntryNode();
4544 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4545 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004546}
4547
Chris Lattner068a81e2005-01-17 17:15:02 +00004548void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004549LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004550 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004551 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004552 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004553 SDOperand OldRoot = SDL.DAG.getRoot();
4554 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004555
Chris Lattnerbf209482005-10-30 19:42:35 +00004556 unsigned a = 0;
4557 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4558 AI != E; ++AI, ++a)
4559 if (!AI->use_empty()) {
4560 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004561
Chris Lattnerbf209482005-10-30 19:42:35 +00004562 // If this argument is live outside of the entry block, insert a copy from
4563 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004564 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4565 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004566 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004567 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004568 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004569
Chris Lattnerbf209482005-10-30 19:42:35 +00004570 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004571 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004572 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004573}
4574
Duncan Sandsf4070822007-06-15 19:04:19 +00004575static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4576 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004577 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004578 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004579 // Apply the catch info to DestBB.
4580 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4581#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004582 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4583 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004584#endif
4585 }
4586}
4587
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004588/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004589/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004590static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4591 TargetLowering& TLI) {
4592 SDNode * Ret = NULL;
4593 SDOperand Terminator = DAG.getRoot();
4594
4595 // Find RET node.
4596 if (Terminator.getOpcode() == ISD::RET) {
4597 Ret = Terminator.Val;
4598 }
4599
4600 // Fix tail call attribute of CALL nodes.
4601 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4602 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4603 if (BI->getOpcode() == ISD::CALL) {
4604 SDOperand OpRet(Ret, 0);
4605 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4606 bool isMarkedTailCall =
4607 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4608 // If CALL node has tail call attribute set to true and the call is not
4609 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004610 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004611 // must correctly identify tail call optimizable calls.
4612 if (isMarkedTailCall &&
4613 (Ret==NULL ||
4614 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG))) {
4615 SmallVector<SDOperand, 32> Ops;
4616 unsigned idx=0;
4617 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4618 E=OpCall.Val->op_end(); I!=E; I++, idx++) {
4619 if (idx!=3)
4620 Ops.push_back(*I);
4621 else
4622 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4623 }
4624 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4625 }
4626 }
4627 }
4628}
4629
Chris Lattner1c08c712005-01-07 07:47:53 +00004630void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4631 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004632 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00004633 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004634
Chris Lattnerbf209482005-10-30 19:42:35 +00004635 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004636 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004637 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00004638
4639 BB = FuncInfo.MBBMap[LLVMBB];
4640 SDL.setCurrentBasicBlock(BB);
4641
Duncan Sandsf4070822007-06-15 19:04:19 +00004642 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004643
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004644 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004645 // Add a label to mark the beginning of the landing pad. Deletion of the
4646 // landing pad can thus be detected via the MachineModuleInfo.
4647 unsigned LabelID = MMI->addLandingPad(BB);
4648 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00004649 DAG.getConstant(LabelID, MVT::i32),
4650 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00004651
Evan Chenge47c3332007-06-27 18:45:32 +00004652 // Mark exception register as live in.
4653 unsigned Reg = TLI.getExceptionAddressRegister();
4654 if (Reg) BB->addLiveIn(Reg);
4655
4656 // Mark exception selector register as live in.
4657 Reg = TLI.getExceptionSelectorRegister();
4658 if (Reg) BB->addLiveIn(Reg);
4659
Duncan Sandsf4070822007-06-15 19:04:19 +00004660 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4661 // function and list of typeids logically belong to the invoke (or, if you
4662 // like, the basic block containing the invoke), and need to be associated
4663 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004664 // information is provided by an intrinsic (eh.selector) that can be moved
4665 // to unexpected places by the optimizers: if the unwind edge is critical,
4666 // then breaking it can result in the intrinsics being in the successor of
4667 // the landing pad, not the landing pad itself. This results in exceptions
4668 // not being caught because no typeids are associated with the invoke.
4669 // This may not be the only way things can go wrong, but it is the only way
4670 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004671 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4672
4673 if (Br && Br->isUnconditional()) { // Critical edge?
4674 BasicBlock::iterator I, E;
4675 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004676 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004677 break;
4678
4679 if (I == E)
4680 // No catch info found - try to extract some from the successor.
4681 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004682 }
4683 }
4684
Chris Lattner1c08c712005-01-07 07:47:53 +00004685 // Lower all of the non-terminator instructions.
4686 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4687 I != E; ++I)
4688 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004689
Chris Lattner1c08c712005-01-07 07:47:53 +00004690 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004691 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004692 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004693 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004694 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004695 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004696 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004697 }
4698
4699 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4700 // ensure constants are generated when needed. Remember the virtual registers
4701 // that need to be added to the Machine PHI nodes as input. We cannot just
4702 // directly add them, because expansion might result in multiple MBB's for one
4703 // BB. As such, the start of the BB might correspond to a different MBB than
4704 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004705 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004706 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004707
4708 // Emit constants only once even if used by multiple PHI nodes.
4709 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004710
Chris Lattner8c494ab2006-10-27 23:50:33 +00004711 // Vector bool would be better, but vector<bool> is really slow.
4712 std::vector<unsigned char> SuccsHandled;
4713 if (TI->getNumSuccessors())
4714 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4715
Dan Gohman532dc2e2007-07-09 20:59:04 +00004716 // Check successor nodes' PHI nodes that expect a constant to be available
4717 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004718 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4719 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004720 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004721 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004722
Chris Lattner8c494ab2006-10-27 23:50:33 +00004723 // If this terminator has multiple identical successors (common for
4724 // switches), only handle each succ once.
4725 unsigned SuccMBBNo = SuccMBB->getNumber();
4726 if (SuccsHandled[SuccMBBNo]) continue;
4727 SuccsHandled[SuccMBBNo] = true;
4728
4729 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004730 PHINode *PN;
4731
4732 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4733 // nodes and Machine PHI nodes, but the incoming operands have not been
4734 // emitted yet.
4735 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004736 (PN = dyn_cast<PHINode>(I)); ++I) {
4737 // Ignore dead phi's.
4738 if (PN->use_empty()) continue;
4739
4740 unsigned Reg;
4741 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004742
Chris Lattner8c494ab2006-10-27 23:50:33 +00004743 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4744 unsigned &RegOut = ConstantsOut[C];
4745 if (RegOut == 0) {
4746 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004747 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00004748 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004749 Reg = RegOut;
4750 } else {
4751 Reg = FuncInfo.ValueMap[PHIOp];
4752 if (Reg == 0) {
4753 assert(isa<AllocaInst>(PHIOp) &&
4754 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4755 "Didn't codegen value into a register!??");
4756 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004757 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00004758 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004759 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004760
4761 // Remember that this register needs to added to the machine PHI node as
4762 // the input for this MBB.
4763 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004764 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004765 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004766 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4767 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004768 }
4769 ConstantsOut.clear();
4770
4771 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004772 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004773
Nate Begemanf15485a2006-03-27 01:32:24 +00004774 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004775 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004776 SwitchCases.clear();
4777 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004778 JTCases.clear();
4779 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004780 BitTestCases.clear();
4781 BitTestCases = SDL.BitTestCases;
4782
Chris Lattnera651cf62005-01-17 19:43:36 +00004783 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004784 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004785
4786 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4787 // with correct tailcall attribute so that the target can rely on the tailcall
4788 // attribute indicating whether the call is really eligible for tail call
4789 // optimization.
4790 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00004791}
4792
Nate Begemanf15485a2006-03-27 01:32:24 +00004793void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00004794 DOUT << "Lowered selection DAG:\n";
4795 DEBUG(DAG.dump());
4796
Chris Lattneraf21d552005-10-10 16:47:10 +00004797 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004798 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004799
Dan Gohman417e11b2007-10-08 15:12:17 +00004800 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004801 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004802
Chris Lattner1c08c712005-01-07 07:47:53 +00004803 // Second step, hack on the DAG until it only uses operations and types that
4804 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00004805#if 0 // Enable this some day.
4806 DAG.LegalizeTypes();
4807 // Someday even later, enable a dag combine pass here.
4808#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00004809 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004810
Bill Wendling832171c2006-12-07 20:04:42 +00004811 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004812 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004813
Chris Lattneraf21d552005-10-10 16:47:10 +00004814 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004815 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004816
Dan Gohman417e11b2007-10-08 15:12:17 +00004817 DOUT << "Optimized legalized selection DAG:\n";
4818 DEBUG(DAG.dump());
4819
Evan Chenga9c20912006-01-21 02:32:06 +00004820 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004821
Chris Lattnera33ef482005-03-30 01:10:47 +00004822 // Third, instruction select all of the operations to machine code, adding the
4823 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004824 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004825
Bill Wendling832171c2006-12-07 20:04:42 +00004826 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004827 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004828}
Chris Lattner1c08c712005-01-07 07:47:53 +00004829
Nate Begemanf15485a2006-03-27 01:32:24 +00004830void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4831 FunctionLoweringInfo &FuncInfo) {
4832 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4833 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004834 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004835 CurDAG = &DAG;
4836
4837 // First step, lower LLVM code to some DAG. This DAG may use operations and
4838 // types that are not supported by the target.
4839 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4840
4841 // Second step, emit the lowered DAG as machine code.
4842 CodeGenAndEmitDAG(DAG);
4843 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004844
4845 DOUT << "Total amount of phi nodes to update: "
4846 << PHINodesToUpdate.size() << "\n";
4847 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4848 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4849 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00004850
Chris Lattnera33ef482005-03-30 01:10:47 +00004851 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004852 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004853 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004854 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4855 MachineInstr *PHI = PHINodesToUpdate[i].first;
4856 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4857 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004858 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4859 false));
4860 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00004861 }
4862 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004863 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004864
4865 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4866 // Lower header first, if it wasn't already lowered
4867 if (!BitTestCases[i].Emitted) {
4868 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4869 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004870 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004871 // Set the current basic block to the mbb we wish to insert the code into
4872 BB = BitTestCases[i].Parent;
4873 HSDL.setCurrentBasicBlock(BB);
4874 // Emit the code
4875 HSDL.visitBitTestHeader(BitTestCases[i]);
4876 HSDAG.setRoot(HSDL.getRoot());
4877 CodeGenAndEmitDAG(HSDAG);
4878 }
4879
4880 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4881 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4882 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004883 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004884 // Set the current basic block to the mbb we wish to insert the code into
4885 BB = BitTestCases[i].Cases[j].ThisBB;
4886 BSDL.setCurrentBasicBlock(BB);
4887 // Emit the code
4888 if (j+1 != ej)
4889 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4890 BitTestCases[i].Reg,
4891 BitTestCases[i].Cases[j]);
4892 else
4893 BSDL.visitBitTestCase(BitTestCases[i].Default,
4894 BitTestCases[i].Reg,
4895 BitTestCases[i].Cases[j]);
4896
4897
4898 BSDAG.setRoot(BSDL.getRoot());
4899 CodeGenAndEmitDAG(BSDAG);
4900 }
4901
4902 // Update PHI Nodes
4903 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4904 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4905 MachineBasicBlock *PHIBB = PHI->getParent();
4906 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4907 "This is not a machine PHI node that we are updating!");
4908 // This is "default" BB. We have two jumps to it. From "header" BB and
4909 // from last "case" BB.
4910 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004911 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4912 false));
4913 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
4914 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4915 false));
4916 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
4917 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004918 }
4919 // One of "cases" BB.
4920 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4921 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4922 if (cBB->succ_end() !=
4923 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004924 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4925 false));
4926 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004927 }
4928 }
4929 }
4930 }
4931
Nate Begeman9453eea2006-04-23 06:26:20 +00004932 // If the JumpTable record is filled in, then we need to emit a jump table.
4933 // Updating the PHI nodes is tricky in this case, since we need to determine
4934 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004935 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4936 // Lower header first, if it wasn't already lowered
4937 if (!JTCases[i].first.Emitted) {
4938 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4939 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004940 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004941 // Set the current basic block to the mbb we wish to insert the code into
4942 BB = JTCases[i].first.HeaderBB;
4943 HSDL.setCurrentBasicBlock(BB);
4944 // Emit the code
4945 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4946 HSDAG.setRoot(HSDL.getRoot());
4947 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004948 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004949
4950 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4951 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004952 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00004953 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004954 BB = JTCases[i].second.MBB;
4955 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004956 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004957 JSDL.visitJumpTable(JTCases[i].second);
4958 JSDAG.setRoot(JSDL.getRoot());
4959 CodeGenAndEmitDAG(JSDAG);
4960
Nate Begeman37efe672006-04-22 18:53:45 +00004961 // Update PHI Nodes
4962 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4963 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4964 MachineBasicBlock *PHIBB = PHI->getParent();
4965 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4966 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004967 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004968 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004969 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4970 false));
4971 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00004972 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004973 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00004974 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004975 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4976 false));
4977 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00004978 }
4979 }
Nate Begeman37efe672006-04-22 18:53:45 +00004980 }
4981
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004982 // If the switch block involved a branch to one of the actual successors, we
4983 // need to update PHI nodes in that block.
4984 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4985 MachineInstr *PHI = PHINodesToUpdate[i].first;
4986 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4987 "This is not a machine PHI node that we are updating!");
4988 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004989 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4990 false));
4991 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004992 }
4993 }
4994
Nate Begemanf15485a2006-03-27 01:32:24 +00004995 // If we generated any switch lowering information, build and codegen any
4996 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004997 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004998 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004999 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005000 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005001
Nate Begemanf15485a2006-03-27 01:32:24 +00005002 // Set the current basic block to the mbb we wish to insert the code into
5003 BB = SwitchCases[i].ThisBB;
5004 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005005
Nate Begemanf15485a2006-03-27 01:32:24 +00005006 // Emit the code
5007 SDL.visitSwitchCase(SwitchCases[i]);
5008 SDAG.setRoot(SDL.getRoot());
5009 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005010
5011 // Handle any PHI nodes in successors of this chunk, as if we were coming
5012 // from the original BB before switch expansion. Note that PHI nodes can
5013 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5014 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005015 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005016 for (MachineBasicBlock::iterator Phi = BB->begin();
5017 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5018 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5019 for (unsigned pn = 0; ; ++pn) {
5020 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5021 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005022 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5023 second, false));
5024 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005025 break;
5026 }
5027 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005028 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005029
5030 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005031 if (BB == SwitchCases[i].FalseBB)
5032 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005033
5034 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005035 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005036 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005037 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005038 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005039 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005040}
Evan Chenga9c20912006-01-21 02:32:06 +00005041
Jim Laskey13ec7022006-08-01 14:21:23 +00005042
Evan Chenga9c20912006-01-21 02:32:06 +00005043//===----------------------------------------------------------------------===//
5044/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5045/// target node in the graph.
5046void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5047 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005048
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005049 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005050
5051 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005052 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005053 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005054 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005055
Jim Laskey9ff542f2006-08-01 18:29:48 +00005056 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005057 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005058
5059 if (ViewSUnitDAGs) SL->viewGraph();
5060
Evan Chengcccf1232006-02-04 06:49:00 +00005061 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005062}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005063
Chris Lattner03fc53c2006-03-06 00:22:00 +00005064
Jim Laskey9ff542f2006-08-01 18:29:48 +00005065HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5066 return new HazardRecognizer();
5067}
5068
Chris Lattner75548062006-10-11 03:58:02 +00005069//===----------------------------------------------------------------------===//
5070// Helper functions used by the generated instruction selector.
5071//===----------------------------------------------------------------------===//
5072// Calls to these methods are generated by tblgen.
5073
5074/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5075/// the dag combiner simplified the 255, we still want to match. RHS is the
5076/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5077/// specified in the .td file (e.g. 255).
5078bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005079 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005080 const APInt &ActualMask = RHS->getAPIntValue();
5081 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005082
5083 // If the actual mask exactly matches, success!
5084 if (ActualMask == DesiredMask)
5085 return true;
5086
5087 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005088 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005089 return false;
5090
5091 // Otherwise, the DAG Combiner may have proven that the value coming in is
5092 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005093 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005094 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005095 return true;
5096
5097 // TODO: check to see if missing bits are just not demanded.
5098
5099 // Otherwise, this pattern doesn't match.
5100 return false;
5101}
5102
5103/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5104/// the dag combiner simplified the 255, we still want to match. RHS is the
5105/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5106/// specified in the .td file (e.g. 255).
5107bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005108 int64_t DesiredMaskS) const {
5109 const APInt &ActualMask = RHS->getAPIntValue();
5110 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005111
5112 // If the actual mask exactly matches, success!
5113 if (ActualMask == DesiredMask)
5114 return true;
5115
5116 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005117 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005118 return false;
5119
5120 // Otherwise, the DAG Combiner may have proven that the value coming in is
5121 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005122 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005123
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005124 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005125 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005126
5127 // If all the missing bits in the or are already known to be set, match!
5128 if ((NeededMask & KnownOne) == NeededMask)
5129 return true;
5130
5131 // TODO: check to see if missing bits are just not demanded.
5132
5133 // Otherwise, this pattern doesn't match.
5134 return false;
5135}
5136
Jim Laskey9ff542f2006-08-01 18:29:48 +00005137
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005138/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5139/// by tblgen. Others should not call it.
5140void SelectionDAGISel::
5141SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5142 std::vector<SDOperand> InOps;
5143 std::swap(InOps, Ops);
5144
5145 Ops.push_back(InOps[0]); // input chain.
5146 Ops.push_back(InOps[1]); // input asm string.
5147
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005148 unsigned i = 2, e = InOps.size();
5149 if (InOps[e-1].getValueType() == MVT::Flag)
5150 --e; // Don't process a flag operand if it is here.
5151
5152 while (i != e) {
5153 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5154 if ((Flags & 7) != 4 /*MEM*/) {
5155 // Just skip over this operand, copying the operands verbatim.
5156 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5157 i += (Flags >> 3) + 1;
5158 } else {
5159 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5160 // Otherwise, this is a memory operand. Ask the target to select it.
5161 std::vector<SDOperand> SelOps;
5162 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005163 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005164 exit(1);
5165 }
5166
5167 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00005168 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005169 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005170 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005171 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5172 i += 2;
5173 }
5174 }
5175
5176 // Add the flag input back if present.
5177 if (e != InOps.size())
5178 Ops.push_back(InOps.back());
5179}
Devang Patel794fd752007-05-01 21:15:47 +00005180
Devang Patel19974732007-05-03 01:11:54 +00005181char SelectionDAGISel::ID = 0;