blob: 5f1c942e9601d36426b122154d921b35005d926d [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000027#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000032#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000035#include "llvm/Target/MRegisterInfo.h"
Chris Lattner3f7927c2006-11-29 01:12:32 +000036#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattnerda8abb02005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000057#else
Chris Lattner5e46a192006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000059#endif
60
Jim Laskeyeb577ba2006-08-02 12:30:23 +000061
62//===---------------------------------------------------------------------===//
63///
64/// RegisterScheduler class - Track the registration of instruction schedulers.
65///
66//===---------------------------------------------------------------------===//
67MachinePassRegistry RegisterScheduler::Registry;
68
69//===---------------------------------------------------------------------===//
70///
71/// ISHeuristic command line option for instruction schedulers.
72///
73//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000074namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey9ff542f2006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner864635a2006-02-22 22:37:12 +000086namespace {
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000092 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
94 /// to.
95 std::vector<unsigned> Regs;
96
97 /// RegVT - The value type of each register.
98 ///
99 MVT::ValueType RegVT;
100
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
104
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
109 Regs.push_back(Reg);
110 }
111 RegsForValue(const std::vector<unsigned> &regs,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114 }
115
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000121
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000128
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000134 };
135}
Evan Cheng4ef10862006-01-23 07:01:07 +0000136
Chris Lattner1c08c712005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 /// for the target.
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 SelectionDAG *DAG,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
145
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
148 } else {
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
152 }
153 }
154
155
156 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000161 TargetLowering &TLI;
162 Function &Fn;
163 MachineFunction &MF;
164 SSARegMap *RegMap;
165
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000174 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000175
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
180
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183 }
Chris Lattner571e4342006-10-27 21:36:01 +0000184
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
189 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000190
Chris Lattner3c384492006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner1c08c712005-01-07 07:47:53 +0000193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
197 }
198 };
199}
200
201/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000202/// PHI nodes or outside of the basic block that defines it, or used by a
203/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000204static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattnerbf209482005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000216/// entry block, return true. This includes arguments used by switches, since
217/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000218static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner1c08c712005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattnerbf209482005-10-30 19:42:35 +0000230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 AI != E; ++AI)
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
236
Chris Lattner1c08c712005-01-07 07:47:53 +0000237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
239 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000246 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000247 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000248 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000249
Reid Spencerb83eb642006-10-20 07:07:24 +0000250 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000251 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000252 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000253 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000254 }
255
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000256 for (; BB != EB; ++BB)
257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000258 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
259 if (!isa<AllocaInst>(I) ||
260 !StaticAllocaMap.count(cast<AllocaInst>(I)))
261 InitializeRegForValue(I);
262
263 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
264 // also creates the initial PHI MachineInstrs, though none of the input
265 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000266 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000267 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
268 MBBMap[BB] = MBB;
269 MF.getBasicBlockList().push_back(MBB);
270
271 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
272 // appropriate.
273 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000274 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
275 if (PN->use_empty()) continue;
276
277 MVT::ValueType VT = TLI.getValueType(PN->getType());
278 unsigned NumElements;
279 if (VT != MVT::Vector)
280 NumElements = TLI.getNumElements(VT);
281 else {
282 MVT::ValueType VT1,VT2;
283 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +0000284 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +0000285 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000286 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000287 unsigned PHIReg = ValueMap[PN];
288 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000289 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner8c494ab2006-10-27 23:50:33 +0000290 for (unsigned i = 0; i != NumElements; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000291 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000292 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000293 }
294}
295
Chris Lattner3c384492006-03-16 19:51:18 +0000296/// CreateRegForValue - Allocate the appropriate number of virtual registers of
297/// the correctly promoted or expanded types. Assign these registers
298/// consecutive vreg numbers and return the first assigned number.
299unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
300 MVT::ValueType VT = TLI.getValueType(V->getType());
301
302 // The number of multiples of registers that we need, to, e.g., split up
303 // a <2 x int64> -> 4 x i32 registers.
304 unsigned NumVectorRegs = 1;
305
Reid Spencerac9dcb92007-02-15 03:39:18 +0000306 // If this is a vector type, figure out what type it will decompose into
Chris Lattner3c384492006-03-16 19:51:18 +0000307 // and how many of the elements it will use.
308 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000309 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner3c384492006-03-16 19:51:18 +0000310 unsigned NumElts = PTy->getNumElements();
311 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
312
313 // Divide the input until we get to a supported size. This will always
314 // end with a scalar if the target doesn't support vectors.
315 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
316 NumElts >>= 1;
317 NumVectorRegs <<= 1;
318 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000319 if (NumElts == 1)
320 VT = EltTy;
321 else
322 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000323 }
324
325 // The common case is that we will only create one register for this
326 // value. If we have that case, create and return the virtual register.
327 unsigned NV = TLI.getNumElements(VT);
328 if (NV == 1) {
329 // If we are promoting this value, pick the next largest supported type.
330 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
331 unsigned Reg = MakeReg(PromotedType);
332 // If this is a vector of supported or promoted types (e.g. 4 x i16),
333 // create all of the registers.
334 for (unsigned i = 1; i != NumVectorRegs; ++i)
335 MakeReg(PromotedType);
336 return Reg;
337 }
338
339 // If this value is represented with multiple target registers, make sure
340 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng9f877882006-12-13 20:57:08 +0000341 VT = TLI.getTypeToExpandTo(VT);
342 unsigned R = MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000343 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng9f877882006-12-13 20:57:08 +0000344 MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000345 return R;
346}
Chris Lattner1c08c712005-01-07 07:47:53 +0000347
348//===----------------------------------------------------------------------===//
349/// SelectionDAGLowering - This is the common target-independent lowering
350/// implementation that is parameterized by a TargetLowering object.
351/// Also, targets can overload any lowering method.
352///
353namespace llvm {
354class SelectionDAGLowering {
355 MachineBasicBlock *CurMBB;
356
Chris Lattner0da331f2007-02-04 01:31:47 +0000357 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000358
Chris Lattnerd3948112005-01-17 22:19:26 +0000359 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
360 /// them up and then emit token factor nodes when possible. This allows us to
361 /// get simple disambiguation between loads without worrying about alias
362 /// analysis.
363 std::vector<SDOperand> PendingLoads;
364
Nate Begemanf15485a2006-03-27 01:32:24 +0000365 /// Case - A pair of values to record the Value for a switch case, and the
366 /// case's target basic block.
367 typedef std::pair<Constant*, MachineBasicBlock*> Case;
368 typedef std::vector<Case>::iterator CaseItr;
369 typedef std::pair<CaseItr, CaseItr> CaseRange;
370
371 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
372 /// of conditional branches.
373 struct CaseRec {
374 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
375 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
376
377 /// CaseBB - The MBB in which to emit the compare and branch
378 MachineBasicBlock *CaseBB;
379 /// LT, GE - If nonzero, we know the current case value must be less-than or
380 /// greater-than-or-equal-to these Constants.
381 Constant *LT;
382 Constant *GE;
383 /// Range - A pair of iterators representing the range of case values to be
384 /// processed at this point in the binary search tree.
385 CaseRange Range;
386 };
387
388 /// The comparison function for sorting Case values.
389 struct CaseCmp {
390 bool operator () (const Case& C1, const Case& C2) {
Reid Spencer47857812006-12-31 05:55:36 +0000391 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
Chris Lattnerae4f99d2007-02-13 20:09:07 +0000392 return cast<const ConstantInt>(C1.first)->getSExtValue() <
393 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000394 }
395 };
396
Chris Lattner1c08c712005-01-07 07:47:53 +0000397public:
398 // TLI - This is information that describes the available target features we
399 // need for lowering. This indicates when operations are unavailable,
400 // implemented with a libcall, etc.
401 TargetLowering &TLI;
402 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000403 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000404
Nate Begemanf15485a2006-03-27 01:32:24 +0000405 /// SwitchCases - Vector of CaseBlock structures used to communicate
406 /// SwitchInst code generation information.
407 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000408 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000409
Chris Lattner1c08c712005-01-07 07:47:53 +0000410 /// FuncInfo - Information about the function as a whole.
411 ///
412 FunctionLoweringInfo &FuncInfo;
413
414 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000415 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000416 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000417 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000418 }
419
Chris Lattnera651cf62005-01-17 19:43:36 +0000420 /// getRoot - Return the current virtual root of the Selection DAG.
421 ///
422 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000423 if (PendingLoads.empty())
424 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000425
Chris Lattnerd3948112005-01-17 22:19:26 +0000426 if (PendingLoads.size() == 1) {
427 SDOperand Root = PendingLoads[0];
428 DAG.setRoot(Root);
429 PendingLoads.clear();
430 return Root;
431 }
432
433 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000434 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
435 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000436 PendingLoads.clear();
437 DAG.setRoot(Root);
438 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000439 }
440
Chris Lattner571e4342006-10-27 21:36:01 +0000441 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
442
Chris Lattner1c08c712005-01-07 07:47:53 +0000443 void visit(Instruction &I) { visit(I.getOpcode(), I); }
444
445 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000446 // Note: this doesn't use InstVisitor, because it has to work with
447 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000448 switch (Opcode) {
449 default: assert(0 && "Unknown instruction type encountered!");
450 abort();
451 // Build the switch statement using the Instruction.def file.
452#define HANDLE_INST(NUM, OPCODE, CLASS) \
453 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
454#include "llvm/Instruction.def"
455 }
456 }
457
458 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
459
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000460 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000461 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000462 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000463
464 SDOperand getIntPtrConstant(uint64_t Val) {
465 return DAG.getConstant(Val, TLI.getPointerTy());
466 }
467
Chris Lattner199862b2006-03-16 19:57:50 +0000468 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000469
Chris Lattner0da331f2007-02-04 01:31:47 +0000470 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000471 SDOperand &N = NodeMap[V];
472 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000473 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000474 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000475
Chris Lattner864635a2006-02-22 22:37:12 +0000476 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
477 MVT::ValueType VT,
478 bool OutReg, bool InReg,
479 std::set<unsigned> &OutputRegs,
480 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000481
Chris Lattner571e4342006-10-27 21:36:01 +0000482 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
483 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
484 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000485 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000486 void ExportFromCurrentBlock(Value *V);
Jim Laskey735b6f82007-02-22 15:38:06 +0000487 void LowerCallTo(CallInst &I, SDOperand Callee, unsigned OpIdx);
488
Chris Lattner1c08c712005-01-07 07:47:53 +0000489 // Terminator instructions.
490 void visitRet(ReturnInst &I);
491 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000492 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000493 void visitUnreachable(UnreachableInst &I) { /* noop */ }
494
Nate Begemanf15485a2006-03-27 01:32:24 +0000495 // Helper for visitSwitch
496 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000497 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000498
Chris Lattner1c08c712005-01-07 07:47:53 +0000499 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000500 void visitInvoke(InvokeInst &I);
501 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000502
Reid Spencer24d6da52007-01-21 00:29:26 +0000503 void visitScalarBinary(User &I, unsigned OpCode);
504 void visitVectorBinary(User &I, unsigned OpCode);
505 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000506 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000507 void visitAdd(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000508 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000509 visitVectorBinary(I, ISD::VADD);
510 else if (I.getType()->isFloatingPoint())
511 visitScalarBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000512 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000513 visitScalarBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000514 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000515 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000516 void visitMul(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000517 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000518 visitVectorBinary(I, ISD::VMUL);
519 else if (I.getType()->isFloatingPoint())
520 visitScalarBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000521 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000522 visitScalarBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000523 }
Reid Spencer24d6da52007-01-21 00:29:26 +0000524 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
525 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
526 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
527 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
528 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
529 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
530 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
531 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
532 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
533 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000534 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
535 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000536 void visitICmp(User &I);
537 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000538 // Visit the conversion instructions
539 void visitTrunc(User &I);
540 void visitZExt(User &I);
541 void visitSExt(User &I);
542 void visitFPTrunc(User &I);
543 void visitFPExt(User &I);
544 void visitFPToUI(User &I);
545 void visitFPToSI(User &I);
546 void visitUIToFP(User &I);
547 void visitSIToFP(User &I);
548 void visitPtrToInt(User &I);
549 void visitIntToPtr(User &I);
550 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000551
Chris Lattner2bbd8102006-03-29 00:11:43 +0000552 void visitExtractElement(User &I);
553 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000554 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000555
Chris Lattner1c08c712005-01-07 07:47:53 +0000556 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000557 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000558
559 void visitMalloc(MallocInst &I);
560 void visitFree(FreeInst &I);
561 void visitAlloca(AllocaInst &I);
562 void visitLoad(LoadInst &I);
563 void visitStore(StoreInst &I);
564 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
565 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000566 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000567 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000568 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000569
Chris Lattner1c08c712005-01-07 07:47:53 +0000570 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000571 void visitVAArg(VAArgInst &I);
572 void visitVAEnd(CallInst &I);
573 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000574
Chris Lattner7041ee32005-01-11 05:56:49 +0000575 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000576
577 void visitUserOp1(Instruction &I) {
578 assert(0 && "UserOp1 should not exist at instruction selection time!");
579 abort();
580 }
581 void visitUserOp2(Instruction &I) {
582 assert(0 && "UserOp2 should not exist at instruction selection time!");
583 abort();
584 }
585};
586} // end namespace llvm
587
Chris Lattner199862b2006-03-16 19:57:50 +0000588SDOperand SelectionDAGLowering::getValue(const Value *V) {
589 SDOperand &N = NodeMap[V];
590 if (N.Val) return N;
591
592 const Type *VTy = V->getType();
593 MVT::ValueType VT = TLI.getValueType(VTy);
594 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
595 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
596 visit(CE->getOpcode(), *CE);
Chris Lattner0da331f2007-02-04 01:31:47 +0000597 SDOperand N1 = NodeMap[V];
598 assert(N1.Val && "visit didn't populate the ValueMap!");
599 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +0000600 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
601 return N = DAG.getGlobalAddress(GV, VT);
602 } else if (isa<ConstantPointerNull>(C)) {
603 return N = DAG.getConstant(0, TLI.getPointerTy());
604 } else if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000605 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +0000606 return N = DAG.getNode(ISD::UNDEF, VT);
607
Chris Lattnerb2827b02006-03-19 00:52:58 +0000608 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000609 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +0000610 unsigned NumElements = PTy->getNumElements();
611 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
612
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000613 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000614 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
615
616 // Create a VConstant node with generic Vector type.
617 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
618 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000619 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
620 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000621 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
622 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000623 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner199862b2006-03-16 19:57:50 +0000624 unsigned NumElements = PTy->getNumElements();
625 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000626
627 // Now that we know the number and type of the elements, push a
628 // Constant or ConstantFP node onto the ops list for each element of
629 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000630 SmallVector<SDOperand, 8> Ops;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000631 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000632 for (unsigned i = 0; i != NumElements; ++i)
633 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000634 } else {
635 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
636 SDOperand Op;
637 if (MVT::isFloatingPoint(PVT))
638 Op = DAG.getConstantFP(0, PVT);
639 else
640 Op = DAG.getConstant(0, PVT);
641 Ops.assign(NumElements, Op);
642 }
643
Chris Lattnerb2827b02006-03-19 00:52:58 +0000644 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000645 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
646 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner0da331f2007-02-04 01:31:47 +0000647 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
648 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000649 } else {
650 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000651 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000652 }
653 }
654
655 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
656 std::map<const AllocaInst*, int>::iterator SI =
657 FuncInfo.StaticAllocaMap.find(AI);
658 if (SI != FuncInfo.StaticAllocaMap.end())
659 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
660 }
661
Chris Lattner9f24ad72007-02-04 01:35:11 +0000662 DenseMap<const Value*, unsigned>::iterator VMI =
Chris Lattner199862b2006-03-16 19:57:50 +0000663 FuncInfo.ValueMap.find(V);
664 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
665
666 unsigned InReg = VMI->second;
667
668 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000669 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000670 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000671 // Source must be expanded. This input value is actually coming from the
672 // register pair VMI->second and VMI->second+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000673 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
674 unsigned NumVals = TLI.getNumElements(VT);
675 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
676 if (NumVals == 1)
677 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
678 else {
679 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
680 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
681 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
682 }
683 } else {
684 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
685 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
686 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
687 N = MVT::isFloatingPoint(VT)
688 ? DAG.getNode(ISD::FP_ROUND, VT, N)
689 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000690 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000691 } else {
692 // Otherwise, if this is a vector, make it available as a generic vector
693 // here.
694 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000695 const VectorType *PTy = cast<VectorType>(VTy);
696 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000697 PTyLegalElementVT);
698
699 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000700 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000701 if (PTyElementVT == PTyLegalElementVT) {
702 // If the value types are legal, just VBUILD the CopyFromReg nodes.
703 for (unsigned i = 0; i != NE; ++i)
704 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
705 PTyElementVT));
706 } else if (PTyElementVT < PTyLegalElementVT) {
707 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
708 for (unsigned i = 0; i != NE; ++i) {
709 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
710 PTyElementVT);
711 if (MVT::isFloatingPoint(PTyElementVT))
712 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
713 else
714 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
715 Ops.push_back(Op);
716 }
717 } else {
718 // If the register was expanded, use BUILD_PAIR.
719 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
720 for (unsigned i = 0; i != NE/2; ++i) {
721 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
722 PTyElementVT);
723 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
724 PTyElementVT);
725 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
726 }
727 }
728
729 Ops.push_back(DAG.getConstant(NE, MVT::i32));
730 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000731 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000732
733 // Finally, use a VBIT_CONVERT to make this available as the appropriate
734 // vector type.
735 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
736 DAG.getConstant(PTy->getNumElements(),
737 MVT::i32),
738 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000739 }
740
741 return N;
742}
743
744
Chris Lattner1c08c712005-01-07 07:47:53 +0000745void SelectionDAGLowering::visitRet(ReturnInst &I) {
746 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000747 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000748 return;
749 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000750 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000751 NewValues.push_back(getRoot());
752 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
753 SDOperand RetOp = getValue(I.getOperand(i));
754
755 // If this is an integer return value, we need to promote it ourselves to
756 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
757 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000758 // FIXME: C calling convention requires the return type to be promoted to
759 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000760 if (MVT::isInteger(RetOp.getValueType()) &&
761 RetOp.getValueType() < MVT::i64) {
762 MVT::ValueType TmpVT;
763 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
764 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
765 else
766 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000767 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencerbcca3402007-01-03 16:49:33 +0000768 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000769 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
770 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer47857812006-12-31 05:55:36 +0000771 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
772 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000773 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000774 }
775 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000776 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000777 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000778 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
779 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000780}
781
Chris Lattner571e4342006-10-27 21:36:01 +0000782/// ExportFromCurrentBlock - If this condition isn't known to be exported from
783/// the current basic block, add it to ValueMap now so that we'll get a
784/// CopyTo/FromReg.
785void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
786 // No need to export constants.
787 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
788
789 // Already exported?
790 if (FuncInfo.isExportedInst(V)) return;
791
792 unsigned Reg = FuncInfo.InitializeRegForValue(V);
793 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
794}
795
Chris Lattner8c494ab2006-10-27 23:50:33 +0000796bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
797 const BasicBlock *FromBB) {
798 // The operands of the setcc have to be in this block. We don't know
799 // how to export them from some other block.
800 if (Instruction *VI = dyn_cast<Instruction>(V)) {
801 // Can export from current BB.
802 if (VI->getParent() == FromBB)
803 return true;
804
805 // Is already exported, noop.
806 return FuncInfo.isExportedInst(V);
807 }
808
809 // If this is an argument, we can export it if the BB is the entry block or
810 // if it is already exported.
811 if (isa<Argument>(V)) {
812 if (FromBB == &FromBB->getParent()->getEntryBlock())
813 return true;
814
815 // Otherwise, can only export this if it is already exported.
816 return FuncInfo.isExportedInst(V);
817 }
818
819 // Otherwise, constants can always be exported.
820 return true;
821}
822
Chris Lattner6a586c82006-10-29 21:01:20 +0000823static bool InBlock(const Value *V, const BasicBlock *BB) {
824 if (const Instruction *I = dyn_cast<Instruction>(V))
825 return I->getParent() == BB;
826 return true;
827}
828
Chris Lattner571e4342006-10-27 21:36:01 +0000829/// FindMergedConditions - If Cond is an expression like
830void SelectionDAGLowering::FindMergedConditions(Value *Cond,
831 MachineBasicBlock *TBB,
832 MachineBasicBlock *FBB,
833 MachineBasicBlock *CurBB,
834 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000835 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000836 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000837
Reid Spencere4d87aa2006-12-23 06:05:41 +0000838 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
839 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000840 BOp->getParent() != CurBB->getBasicBlock() ||
841 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
842 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000843 const BasicBlock *BB = CurBB->getBasicBlock();
844
Reid Spencere4d87aa2006-12-23 06:05:41 +0000845 // If the leaf of the tree is a comparison, merge the condition into
846 // the caseblock.
847 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
848 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000849 // how to export them from some other block. If this is the first block
850 // of the sequence, no exporting is needed.
851 (CurBB == CurMBB ||
852 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
853 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000854 BOp = cast<Instruction>(Cond);
855 ISD::CondCode Condition;
856 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
857 switch (IC->getPredicate()) {
858 default: assert(0 && "Unknown icmp predicate opcode!");
859 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
860 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
861 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
862 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
863 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
864 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
865 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
866 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
867 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
868 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
869 }
870 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
871 ISD::CondCode FPC, FOC;
872 switch (FC->getPredicate()) {
873 default: assert(0 && "Unknown fcmp predicate opcode!");
874 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
875 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
876 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
877 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
878 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
879 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
880 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
881 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
882 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
883 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
884 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
885 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
886 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
887 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
888 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
889 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
890 }
891 if (FiniteOnlyFPMath())
892 Condition = FOC;
893 else
894 Condition = FPC;
895 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +0000896 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000897 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000898 }
899
Chris Lattner571e4342006-10-27 21:36:01 +0000900 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
901 BOp->getOperand(1), TBB, FBB, CurBB);
902 SwitchCases.push_back(CB);
903 return;
904 }
905
906 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000907 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattner571e4342006-10-27 21:36:01 +0000908 TBB, FBB, CurBB);
909 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000910 return;
911 }
912
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000913
914 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000915 MachineFunction::iterator BBI = CurBB;
916 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
917 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
918
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000919 if (Opc == Instruction::Or) {
920 // Codegen X | Y as:
921 // jmp_if_X TBB
922 // jmp TmpBB
923 // TmpBB:
924 // jmp_if_Y TBB
925 // jmp FBB
926 //
Chris Lattner571e4342006-10-27 21:36:01 +0000927
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000928 // Emit the LHS condition.
929 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
930
931 // Emit the RHS condition into TmpBB.
932 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
933 } else {
934 assert(Opc == Instruction::And && "Unknown merge op!");
935 // Codegen X & Y as:
936 // jmp_if_X TmpBB
937 // jmp FBB
938 // TmpBB:
939 // jmp_if_Y TBB
940 // jmp FBB
941 //
942 // This requires creation of TmpBB after CurBB.
943
944 // Emit the LHS condition.
945 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
946
947 // Emit the RHS condition into TmpBB.
948 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
949 }
Chris Lattner571e4342006-10-27 21:36:01 +0000950}
951
Chris Lattnerdf19f272006-10-31 22:37:42 +0000952/// If the set of cases should be emitted as a series of branches, return true.
953/// If we should emit this as a bunch of and/or'd together conditions, return
954/// false.
955static bool
956ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
957 if (Cases.size() != 2) return true;
958
Chris Lattner0ccb5002006-10-31 23:06:00 +0000959 // If this is two comparisons of the same values or'd or and'd together, they
960 // will get folded into a single comparison, so don't emit two blocks.
961 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
962 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
963 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
964 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
965 return false;
966 }
967
Chris Lattnerdf19f272006-10-31 22:37:42 +0000968 return true;
969}
970
Chris Lattner1c08c712005-01-07 07:47:53 +0000971void SelectionDAGLowering::visitBr(BranchInst &I) {
972 // Update machine-CFG edges.
973 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000974
975 // Figure out which block is immediately after the current one.
976 MachineBasicBlock *NextBlock = 0;
977 MachineFunction::iterator BBI = CurMBB;
978 if (++BBI != CurMBB->getParent()->end())
979 NextBlock = BBI;
980
981 if (I.isUnconditional()) {
982 // If this is not a fall-through branch, emit the branch.
983 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000984 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000985 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000986
Chris Lattner57ab6592006-10-24 17:57:59 +0000987 // Update machine-CFG edges.
988 CurMBB->addSuccessor(Succ0MBB);
989
990 return;
991 }
992
993 // If this condition is one of the special cases we handle, do special stuff
994 // now.
995 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +0000996 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +0000997
998 // If this is a series of conditions that are or'd or and'd together, emit
999 // this as a sequence of branches instead of setcc's with and/or operations.
1000 // For example, instead of something like:
1001 // cmp A, B
1002 // C = seteq
1003 // cmp D, E
1004 // F = setle
1005 // or C, F
1006 // jnz foo
1007 // Emit:
1008 // cmp A, B
1009 // je foo
1010 // cmp D, E
1011 // jle foo
1012 //
1013 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1014 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001015 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001016 BOp->getOpcode() == Instruction::Or)) {
1017 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001018 // If the compares in later blocks need to use values not currently
1019 // exported from this block, export them now. This block should always
1020 // be the first entry.
1021 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1022
Chris Lattnerdf19f272006-10-31 22:37:42 +00001023 // Allow some cases to be rejected.
1024 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001025 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1026 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1027 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1028 }
1029
1030 // Emit the branch for this block.
1031 visitSwitchCase(SwitchCases[0]);
1032 SwitchCases.erase(SwitchCases.begin());
1033 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001034 }
1035
Chris Lattner0ccb5002006-10-31 23:06:00 +00001036 // Okay, we decided not to do this, remove any inserted MBB's and clear
1037 // SwitchCases.
1038 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1039 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1040
Chris Lattnerdf19f272006-10-31 22:37:42 +00001041 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001042 }
1043 }
Chris Lattner24525952006-10-24 18:07:37 +00001044
1045 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001046 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +00001047 Succ0MBB, Succ1MBB, CurMBB);
1048 // Use visitSwitchCase to actually insert the fast branch sequence for this
1049 // cond branch.
1050 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001051}
1052
Nate Begemanf15485a2006-03-27 01:32:24 +00001053/// visitSwitchCase - Emits the necessary code to represent a single node in
1054/// the binary search tree resulting from lowering a switch instruction.
1055void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001056 SDOperand Cond;
1057 SDOperand CondLHS = getValue(CB.CmpLHS);
1058
Chris Lattner571e4342006-10-27 21:36:01 +00001059 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1060 // handle common cases produced by branch lowering.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001061 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +00001062 Cond = CondLHS;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001063 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattner571e4342006-10-27 21:36:01 +00001064 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1065 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1066 } else
1067 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +00001068
1069 // Set NextBlock to be the MBB immediately after the current one, if any.
1070 // This is used to avoid emitting unnecessary branches to the next block.
1071 MachineBasicBlock *NextBlock = 0;
1072 MachineFunction::iterator BBI = CurMBB;
1073 if (++BBI != CurMBB->getParent()->end())
1074 NextBlock = BBI;
1075
1076 // If the lhs block is the next block, invert the condition so that we can
1077 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001078 if (CB.TrueBB == NextBlock) {
1079 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001080 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1081 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1082 }
1083 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001084 DAG.getBasicBlock(CB.TrueBB));
1085 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001086 DAG.setRoot(BrCond);
1087 else
1088 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001089 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001090 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001091 CurMBB->addSuccessor(CB.TrueBB);
1092 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001093}
1094
Nate Begeman37efe672006-04-22 18:53:45 +00001095void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001096 // Emit the code for the jump table
1097 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001098 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1099 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1100 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1101 Table, Index));
1102 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001103}
1104
Jim Laskeyb180aa12007-02-21 22:53:45 +00001105void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1106 // Retrieve successors.
1107 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1108 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1109
1110 // Mark landing pad so that it doesn't get deleted in branch folding.
1111 LandingPad->setIsLandingPad();
1112
1113 // Insert a label before the invoke call to mark the try range.
1114 // This can be used to detect deletion of the invoke via the
1115 // MachineModuleInfo.
1116 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1117 unsigned BeginLabel = MMI->NextLabelID();
1118 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1119 DAG.getConstant(BeginLabel, MVT::i32)));
1120
Jim Laskey735b6f82007-02-22 15:38:06 +00001121 LowerCallTo((CallInst&)I, getValue(I.getOperand(0)), 3);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001122
1123 // Insert a label before the invoke call to mark the try range.
1124 // This can be used to detect deletion of the invoke via the
1125 // MachineModuleInfo.
1126 unsigned EndLabel = MMI->NextLabelID();
1127 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1128 DAG.getConstant(EndLabel, MVT::i32)));
1129
1130 // Inform MachineModuleInfo of range.
1131 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1132
1133 // Drop into normal successor.
1134 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1135 DAG.getBasicBlock(Return)));
1136
1137 // Update successor info
1138 CurMBB->addSuccessor(Return);
1139 CurMBB->addSuccessor(LandingPad);
1140}
1141
1142void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1143}
1144
Nate Begemanf15485a2006-03-27 01:32:24 +00001145void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1146 // Figure out which block is immediately after the current one.
1147 MachineBasicBlock *NextBlock = 0;
1148 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001149
Nate Begemanf15485a2006-03-27 01:32:24 +00001150 if (++BBI != CurMBB->getParent()->end())
1151 NextBlock = BBI;
1152
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001153 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1154
Nate Begemanf15485a2006-03-27 01:32:24 +00001155 // If there is only the default destination, branch to it if it is not the
1156 // next basic block. Otherwise, just fall through.
1157 if (I.getNumOperands() == 2) {
1158 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001159
Nate Begemanf15485a2006-03-27 01:32:24 +00001160 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001161 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001162 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001163 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001164
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001165 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001166 return;
1167 }
1168
1169 // If there are any non-default case statements, create a vector of Cases
1170 // representing each one, and sort the vector so that we can efficiently
1171 // create a binary search tree from them.
1172 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001173
Nate Begemanf15485a2006-03-27 01:32:24 +00001174 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1175 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1176 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1177 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001178
Nate Begemanf15485a2006-03-27 01:32:24 +00001179 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1180
1181 // Get the Value to be switched on and default basic blocks, which will be
1182 // inserted into CaseBlock records, representing basic blocks in the binary
1183 // search tree.
1184 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001185
1186 // Get the MachineFunction which holds the current MBB. This is used during
1187 // emission of jump tables, and when inserting any additional MBBs necessary
1188 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001189 MachineFunction *CurMF = CurMBB->getParent();
1190 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001191
1192 // If the switch has few cases (two or less) emit a series of specific
1193 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001194 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001195 // TODO: If any two of the cases has the same destination, and if one value
1196 // is the same as the other, but has one bit unset that the other has set,
1197 // use bit manipulation to do two compares at once. For example:
1198 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1199
Chris Lattnerb3543432006-10-23 18:38:22 +00001200 // Rearrange the case blocks so that the last one falls through if possible.
1201 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1202 // The last case block won't fall through into 'NextBlock' if we emit the
1203 // branches in this order. See if rearranging a case value would help.
1204 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1205 if (Cases[i].second == NextBlock) {
1206 std::swap(Cases[i], Cases.back());
1207 break;
1208 }
1209 }
1210 }
1211
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001212 // Create a CaseBlock record representing a conditional branch to
1213 // the Case's target mbb if the value being switched on SV is equal
1214 // to C.
1215 MachineBasicBlock *CurBlock = CurMBB;
1216 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1217 MachineBasicBlock *FallThrough;
1218 if (i != e-1) {
1219 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1220 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1221 } else {
1222 // If the last case doesn't match, go to the default block.
1223 FallThrough = Default;
1224 }
1225
1226 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1227 Cases[i].second, FallThrough, CurBlock);
1228
1229 // If emitting the first comparison, just call visitSwitchCase to emit the
1230 // code into the current block. Otherwise, push the CaseBlock onto the
1231 // vector to be later processed by SDISel, and insert the node's MBB
1232 // before the next MBB.
1233 if (CurBlock == CurMBB)
1234 visitSwitchCase(CB);
1235 else
1236 SwitchCases.push_back(CB);
1237
1238 CurBlock = FallThrough;
1239 }
1240 return;
1241 }
Nate Begeman37efe672006-04-22 18:53:45 +00001242
Nate Begeman17c275f2006-05-08 16:51:36 +00001243 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1244 // target supports indirect branches, then emit a jump table rather than
1245 // lowering the switch to a binary tree of conditional branches.
Evan Cheng3d4ce112006-10-30 08:00:44 +00001246 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1247 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001248 Cases.size() > 5) {
Chris Lattner21840b12007-02-14 07:18:16 +00001249 uint64_t First =cast<ConstantInt>(Cases.front().first)->getSExtValue();
1250 uint64_t Last = cast<ConstantInt>(Cases.back().first)->getSExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001251 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1252
Nate Begeman17c275f2006-05-08 16:51:36 +00001253 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001254 // Create a new basic block to hold the code for loading the address
1255 // of the jump table, and jumping to it. Update successor information;
1256 // we will either branch to the default case for the switch, or the jump
1257 // table.
1258 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1259 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1260 CurMBB->addSuccessor(Default);
1261 CurMBB->addSuccessor(JumpTableBB);
1262
1263 // Subtract the lowest switch case value from the value being switched on
1264 // and conditional branch to default mbb if the result is greater than the
1265 // difference between smallest and largest cases.
1266 SDOperand SwitchOp = getValue(SV);
1267 MVT::ValueType VT = SwitchOp.getValueType();
1268 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1269 DAG.getConstant(First, VT));
1270
1271 // The SDNode we just created, which holds the value being switched on
1272 // minus the the smallest case value, needs to be copied to a virtual
1273 // register so it can be used as an index into the jump table in a
1274 // subsequent basic block. This value may be smaller or larger than the
1275 // target's pointer type, and therefore require extension or truncating.
1276 if (VT > TLI.getPointerTy())
1277 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1278 else
1279 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001280
Nate Begeman37efe672006-04-22 18:53:45 +00001281 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1282 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1283
1284 // Emit the range check for the jump table, and branch to the default
1285 // block for the switch statement if the value being switched on exceeds
1286 // the largest case in the switch.
1287 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1288 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1289 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1290 DAG.getBasicBlock(Default)));
1291
Nate Begemanf4360a42006-05-03 03:48:02 +00001292 // Build a vector of destination BBs, corresponding to each target
1293 // of the jump table. If the value of the jump table slot corresponds to
1294 // a case statement, push the case's BB onto the vector, otherwise, push
1295 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001296 std::vector<MachineBasicBlock*> DestBBs;
Chris Lattnerc661d612007-02-14 07:34:56 +00001297 int64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001298 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Chris Lattner21840b12007-02-14 07:18:16 +00001299 if (cast<ConstantInt>(ii->first)->getSExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001300 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001301 ++ii;
1302 } else {
1303 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001304 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001305
Chris Lattner8c494ab2006-10-27 23:50:33 +00001306 // Update successor info. Add one edge to each unique successor.
1307 // Vector bool would be better, but vector<bool> is really slow.
1308 std::vector<unsigned char> SuccsHandled;
1309 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1310
Chris Lattnerc66764c2006-09-10 06:36:57 +00001311 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner8c494ab2006-10-27 23:50:33 +00001312 E = DestBBs.end(); I != E; ++I) {
1313 if (!SuccsHandled[(*I)->getNumber()]) {
1314 SuccsHandled[(*I)->getNumber()] = true;
1315 JumpTableBB->addSuccessor(*I);
1316 }
1317 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001318
1319 // Create a jump table index for this jump table, or return an existing
1320 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001321 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1322
1323 // Set the jump table information so that we can codegen it as a second
1324 // MachineBasicBlock
1325 JT.Reg = JumpTableReg;
1326 JT.JTI = JTI;
1327 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001328 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001329 return;
1330 }
1331 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001332
1333 // Push the initial CaseRec onto the worklist
1334 std::vector<CaseRec> CaseVec;
1335 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1336
1337 while (!CaseVec.empty()) {
1338 // Grab a record representing a case range to process off the worklist
1339 CaseRec CR = CaseVec.back();
1340 CaseVec.pop_back();
1341
1342 // Size is the number of Cases represented by this range. If Size is 1,
1343 // then we are processing a leaf of the binary search tree. Otherwise,
1344 // we need to pick a pivot, and push left and right ranges onto the
1345 // worklist.
1346 unsigned Size = CR.Range.second - CR.Range.first;
1347
1348 if (Size == 1) {
1349 // Create a CaseBlock record representing a conditional branch to
1350 // the Case's target mbb if the value being switched on SV is equal
1351 // to C. Otherwise, branch to default.
1352 Constant *C = CR.Range.first->first;
1353 MachineBasicBlock *Target = CR.Range.first->second;
1354 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1355 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001356
Nate Begemanf15485a2006-03-27 01:32:24 +00001357 // If the MBB representing the leaf node is the current MBB, then just
1358 // call visitSwitchCase to emit the code into the current block.
1359 // Otherwise, push the CaseBlock onto the vector to be later processed
1360 // by SDISel, and insert the node's MBB before the next MBB.
1361 if (CR.CaseBB == CurMBB)
1362 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001363 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001364 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001365 } else {
1366 // split case range at pivot
1367 CaseItr Pivot = CR.Range.first + (Size / 2);
1368 CaseRange LHSR(CR.Range.first, Pivot);
1369 CaseRange RHSR(Pivot, CR.Range.second);
1370 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001371 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001372
Nate Begemanf15485a2006-03-27 01:32:24 +00001373 // We know that we branch to the LHS if the Value being switched on is
1374 // less than the Pivot value, C. We use this to optimize our binary
1375 // tree a bit, by recognizing that if SV is greater than or equal to the
1376 // LHS's Case Value, and that Case Value is exactly one less than the
1377 // Pivot's Value, then we can branch directly to the LHS's Target,
1378 // rather than creating a leaf node for it.
1379 if ((LHSR.second - LHSR.first) == 1 &&
1380 LHSR.first->first == CR.GE &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001381 cast<ConstantInt>(C)->getZExtValue() ==
1382 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001383 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001384 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001385 TrueBB = new MachineBasicBlock(LLVMBB);
1386 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1387 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001388 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001389
Nate Begemanf15485a2006-03-27 01:32:24 +00001390 // Similar to the optimization above, if the Value being switched on is
1391 // known to be less than the Constant CR.LT, and the current Case Value
1392 // is CR.LT - 1, then we can branch directly to the target block for
1393 // the current Case Value, rather than emitting a RHS leaf node for it.
1394 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001395 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1396 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001397 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001398 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001399 FalseBB = new MachineBasicBlock(LLVMBB);
1400 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1401 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001402 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001403
Nate Begemanf15485a2006-03-27 01:32:24 +00001404 // Create a CaseBlock record representing a conditional branch to
1405 // the LHS node if the value being switched on SV is less than C.
1406 // Otherwise, branch to LHS.
Chris Lattner21840b12007-02-14 07:18:16 +00001407 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, TrueBB, FalseBB,
1408 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001409
Nate Begemanf15485a2006-03-27 01:32:24 +00001410 if (CR.CaseBB == CurMBB)
1411 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001412 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001413 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001414 }
1415 }
1416}
1417
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001418void SelectionDAGLowering::visitSub(User &I) {
1419 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001420 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00001421 if (isa<VectorType>(Ty)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001422 visitVectorBinary(I, ISD::VSUB);
1423 } else if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00001424 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1425 if (CFP->isExactlyValue(-0.0)) {
1426 SDOperand Op2 = getValue(I.getOperand(1));
1427 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1428 return;
1429 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001430 visitScalarBinary(I, ISD::FSUB);
Reid Spencer1628cec2006-10-26 06:15:43 +00001431 } else
Reid Spencer24d6da52007-01-21 00:29:26 +00001432 visitScalarBinary(I, ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001433}
1434
Reid Spencer24d6da52007-01-21 00:29:26 +00001435void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001436 SDOperand Op1 = getValue(I.getOperand(0));
1437 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00001438
1439 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00001440}
1441
Reid Spencer24d6da52007-01-21 00:29:26 +00001442void
1443SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001444 assert(isa<VectorType>(I.getType()));
1445 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer24d6da52007-01-21 00:29:26 +00001446 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00001447
Reid Spencer24d6da52007-01-21 00:29:26 +00001448 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1449 getValue(I.getOperand(0)),
1450 getValue(I.getOperand(1)),
1451 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1452 Typ));
1453}
1454
1455void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1456 unsigned VectorOp) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001457 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +00001458 visitVectorBinary(I, VectorOp);
1459 else
1460 visitScalarBinary(I, ScalarOp);
Nate Begemane21ea612005-11-18 07:42:56 +00001461}
Chris Lattner2c49f272005-01-19 22:31:21 +00001462
Nate Begemane21ea612005-11-18 07:42:56 +00001463void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1464 SDOperand Op1 = getValue(I.getOperand(0));
1465 SDOperand Op2 = getValue(I.getOperand(1));
1466
Reid Spencer832254e2007-02-02 02:16:23 +00001467 if (TLI.getShiftAmountTy() < Op2.getValueType())
1468 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1469 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1470 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00001471
Chris Lattner1c08c712005-01-07 07:47:53 +00001472 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1473}
1474
Reid Spencer45fb3f32006-11-20 01:22:35 +00001475void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001476 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1477 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1478 predicate = IC->getPredicate();
1479 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1480 predicate = ICmpInst::Predicate(IC->getPredicate());
1481 SDOperand Op1 = getValue(I.getOperand(0));
1482 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00001483 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001484 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00001485 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1486 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1487 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1488 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1489 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1490 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1491 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1492 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1493 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1494 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1495 default:
1496 assert(!"Invalid ICmp predicate value");
1497 Opcode = ISD::SETEQ;
1498 break;
1499 }
1500 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1501}
1502
1503void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001504 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1505 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1506 predicate = FC->getPredicate();
1507 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1508 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00001509 SDOperand Op1 = getValue(I.getOperand(0));
1510 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001511 ISD::CondCode Condition, FOC, FPC;
1512 switch (predicate) {
1513 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1514 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1515 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1516 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1517 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1518 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1519 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1520 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1521 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1522 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1523 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1524 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1525 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1526 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1527 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1528 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1529 default:
1530 assert(!"Invalid FCmp predicate value");
1531 FOC = FPC = ISD::SETFALSE;
1532 break;
1533 }
1534 if (FiniteOnlyFPMath())
1535 Condition = FOC;
1536 else
1537 Condition = FPC;
1538 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00001539}
1540
1541void SelectionDAGLowering::visitSelect(User &I) {
1542 SDOperand Cond = getValue(I.getOperand(0));
1543 SDOperand TrueVal = getValue(I.getOperand(1));
1544 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencer9d6565a2007-02-15 02:26:10 +00001545 if (!isa<VectorType>(I.getType())) {
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001546 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1547 TrueVal, FalseVal));
1548 } else {
1549 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1550 *(TrueVal.Val->op_end()-2),
1551 *(TrueVal.Val->op_end()-1)));
1552 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001553}
1554
Reid Spencer3da59db2006-11-27 01:05:10 +00001555
1556void SelectionDAGLowering::visitTrunc(User &I) {
1557 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1558 SDOperand N = getValue(I.getOperand(0));
1559 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1560 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1561}
1562
1563void SelectionDAGLowering::visitZExt(User &I) {
1564 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1565 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1566 SDOperand N = getValue(I.getOperand(0));
1567 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1568 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1569}
1570
1571void SelectionDAGLowering::visitSExt(User &I) {
1572 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1573 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1574 SDOperand N = getValue(I.getOperand(0));
1575 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1576 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1577}
1578
1579void SelectionDAGLowering::visitFPTrunc(User &I) {
1580 // FPTrunc is never a no-op cast, no need to check
1581 SDOperand N = getValue(I.getOperand(0));
1582 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1583 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1584}
1585
1586void SelectionDAGLowering::visitFPExt(User &I){
1587 // FPTrunc is never a no-op cast, no need to check
1588 SDOperand N = getValue(I.getOperand(0));
1589 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1590 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1591}
1592
1593void SelectionDAGLowering::visitFPToUI(User &I) {
1594 // FPToUI is never a no-op cast, no need to check
1595 SDOperand N = getValue(I.getOperand(0));
1596 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1597 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1598}
1599
1600void SelectionDAGLowering::visitFPToSI(User &I) {
1601 // FPToSI is never a no-op cast, no need to check
1602 SDOperand N = getValue(I.getOperand(0));
1603 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1604 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1605}
1606
1607void SelectionDAGLowering::visitUIToFP(User &I) {
1608 // UIToFP is never a no-op cast, no need to check
1609 SDOperand N = getValue(I.getOperand(0));
1610 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1611 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1612}
1613
1614void SelectionDAGLowering::visitSIToFP(User &I){
1615 // UIToFP is never a no-op cast, no need to check
1616 SDOperand N = getValue(I.getOperand(0));
1617 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1618 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1619}
1620
1621void SelectionDAGLowering::visitPtrToInt(User &I) {
1622 // What to do depends on the size of the integer and the size of the pointer.
1623 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00001624 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001625 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001626 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001627 SDOperand Result;
1628 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1629 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1630 else
1631 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1632 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1633 setValue(&I, Result);
1634}
Chris Lattner1c08c712005-01-07 07:47:53 +00001635
Reid Spencer3da59db2006-11-27 01:05:10 +00001636void SelectionDAGLowering::visitIntToPtr(User &I) {
1637 // What to do depends on the size of the integer and the size of the pointer.
1638 // We can either truncate, zero extend, or no-op, accordingly.
1639 SDOperand N = getValue(I.getOperand(0));
1640 MVT::ValueType SrcVT = N.getValueType();
1641 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1642 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1643 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1644 else
1645 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1646 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1647}
1648
1649void SelectionDAGLowering::visitBitCast(User &I) {
1650 SDOperand N = getValue(I.getOperand(0));
1651 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001652 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001653 // This is a cast to a vector from something else.
1654 // Get information about the output vector.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001655 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001656 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1657 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1658 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1659 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00001660 return;
1661 }
1662 MVT::ValueType SrcVT = N.getValueType();
1663 if (SrcVT == MVT::Vector) {
1664 // This is a cast from a vctor to something else.
1665 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001666 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00001667 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001668 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001669
1670 // BitCast assures us that source and destination are the same size so this
1671 // is either a BIT_CONVERT or a no-op.
1672 if (DestVT != N.getValueType())
1673 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1674 else
1675 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00001676}
1677
Chris Lattner2bbd8102006-03-29 00:11:43 +00001678void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001679 SDOperand InVec = getValue(I.getOperand(0));
1680 SDOperand InVal = getValue(I.getOperand(1));
1681 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1682 getValue(I.getOperand(2)));
1683
Chris Lattner2332b9f2006-03-19 01:17:20 +00001684 SDOperand Num = *(InVec.Val->op_end()-2);
1685 SDOperand Typ = *(InVec.Val->op_end()-1);
1686 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1687 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001688}
1689
Chris Lattner2bbd8102006-03-29 00:11:43 +00001690void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001691 SDOperand InVec = getValue(I.getOperand(0));
1692 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1693 getValue(I.getOperand(1)));
1694 SDOperand Typ = *(InVec.Val->op_end()-1);
1695 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1696 TLI.getValueType(I.getType()), InVec, InIdx));
1697}
Chris Lattnerc7029802006-03-18 01:44:44 +00001698
Chris Lattner3e104b12006-04-08 04:15:24 +00001699void SelectionDAGLowering::visitShuffleVector(User &I) {
1700 SDOperand V1 = getValue(I.getOperand(0));
1701 SDOperand V2 = getValue(I.getOperand(1));
1702 SDOperand Mask = getValue(I.getOperand(2));
1703
1704 SDOperand Num = *(V1.Val->op_end()-2);
1705 SDOperand Typ = *(V2.Val->op_end()-1);
1706 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1707 V1, V2, Mask, Num, Typ));
1708}
1709
1710
Chris Lattner1c08c712005-01-07 07:47:53 +00001711void SelectionDAGLowering::visitGetElementPtr(User &I) {
1712 SDOperand N = getValue(I.getOperand(0));
1713 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001714
1715 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1716 OI != E; ++OI) {
1717 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001718 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001719 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001720 if (Field) {
1721 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00001722 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00001723 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001724 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001725 }
1726 Ty = StTy->getElementType(Field);
1727 } else {
1728 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001729
Chris Lattner7c0104b2005-11-09 04:45:33 +00001730 // If this is a constant subscript, handle it quickly.
1731 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001732 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00001733 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00001734 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001735 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1736 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001737 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001738
1739 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001740 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001741 SDOperand IdxN = getValue(Idx);
1742
1743 // If the index is smaller or larger than intptr_t, truncate or extend
1744 // it.
1745 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00001746 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001747 } else if (IdxN.getValueType() > N.getValueType())
1748 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1749
1750 // If this is a multiply by a power of two, turn it into a shl
1751 // immediately. This is a very common case.
1752 if (isPowerOf2_64(ElementSize)) {
1753 unsigned Amt = Log2_64(ElementSize);
1754 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001755 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001756 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1757 continue;
1758 }
1759
1760 SDOperand Scale = getIntPtrConstant(ElementSize);
1761 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1762 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001763 }
1764 }
1765 setValue(&I, N);
1766}
1767
1768void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1769 // If this is a fixed sized alloca in the entry block of the function,
1770 // allocate it statically on the stack.
1771 if (FuncInfo.StaticAllocaMap.count(&I))
1772 return; // getValue will auto-populate this.
1773
1774 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001775 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00001776 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00001777 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00001778 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001779
1780 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001781 MVT::ValueType IntPtr = TLI.getPointerTy();
1782 if (IntPtr < AllocSize.getValueType())
1783 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1784 else if (IntPtr > AllocSize.getValueType())
1785 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001786
Chris Lattner68cd65e2005-01-22 23:04:37 +00001787 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001788 getIntPtrConstant(TySize));
1789
1790 // Handle alignment. If the requested alignment is less than or equal to the
1791 // stack alignment, ignore it and round the size of the allocation up to the
1792 // stack alignment size. If the size is greater than the stack alignment, we
1793 // note this in the DYNAMIC_STACKALLOC node.
1794 unsigned StackAlign =
1795 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1796 if (Align <= StackAlign) {
1797 Align = 0;
1798 // Add SA-1 to the size.
1799 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1800 getIntPtrConstant(StackAlign-1));
1801 // Mask out the low bits for alignment purposes.
1802 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1803 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1804 }
1805
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001806 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001807 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1808 MVT::Other);
1809 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00001810 setValue(&I, DSA);
1811 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00001812
1813 // Inform the Frame Information that we have just allocated a variable-sized
1814 // object.
1815 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1816}
1817
Chris Lattner1c08c712005-01-07 07:47:53 +00001818void SelectionDAGLowering::visitLoad(LoadInst &I) {
1819 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001820
Chris Lattnerd3948112005-01-17 22:19:26 +00001821 SDOperand Root;
1822 if (I.isVolatile())
1823 Root = getRoot();
1824 else {
1825 // Do not serialize non-volatile loads against each other.
1826 Root = DAG.getRoot();
1827 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001828
Evan Cheng466685d2006-10-09 20:57:25 +00001829 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001830 Root, I.isVolatile()));
1831}
1832
1833SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001834 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001835 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001836 SDOperand L;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001837 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001838 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001839 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1840 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001841 } else {
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001842 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001843 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001844
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001845 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001846 DAG.setRoot(L.getValue(1));
1847 else
1848 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001849
1850 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001851}
1852
1853
1854void SelectionDAGLowering::visitStore(StoreInst &I) {
1855 Value *SrcV = I.getOperand(0);
1856 SDOperand Src = getValue(SrcV);
1857 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001858 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Cheng8b2794a2006-10-13 21:14:26 +00001859 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001860}
1861
Chris Lattner0eade312006-03-24 02:22:33 +00001862/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1863/// access memory and has no other side effects at all.
1864static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1865#define GET_NO_MEMORY_INTRINSICS
1866#include "llvm/Intrinsics.gen"
1867#undef GET_NO_MEMORY_INTRINSICS
1868 return false;
1869}
1870
Chris Lattnere58a7802006-04-02 03:41:14 +00001871// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1872// have any side-effects or if it only reads memory.
1873static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1874#define GET_SIDE_EFFECT_INFO
1875#include "llvm/Intrinsics.gen"
1876#undef GET_SIDE_EFFECT_INFO
1877 return false;
1878}
1879
Chris Lattner0eade312006-03-24 02:22:33 +00001880/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1881/// node.
1882void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1883 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001884 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001885 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001886
1887 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001888 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001889 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1890 if (OnlyLoad) {
1891 // We don't need to serialize loads against other loads.
1892 Ops.push_back(DAG.getRoot());
1893 } else {
1894 Ops.push_back(getRoot());
1895 }
1896 }
Chris Lattner0eade312006-03-24 02:22:33 +00001897
1898 // Add the intrinsic ID as an integer operand.
1899 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1900
1901 // Add all operands of the call to the operand list.
1902 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1903 SDOperand Op = getValue(I.getOperand(i));
1904
Reid Spencerac9dcb92007-02-15 03:39:18 +00001905 // If this is a vector type, force it to the right vector type.
Chris Lattner0eade312006-03-24 02:22:33 +00001906 if (Op.getValueType() == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001907 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattner0eade312006-03-24 02:22:33 +00001908 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1909
1910 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1911 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1912 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1913 }
1914
1915 assert(TLI.isTypeLegal(Op.getValueType()) &&
1916 "Intrinsic uses a non-legal type?");
1917 Ops.push_back(Op);
1918 }
1919
1920 std::vector<MVT::ValueType> VTs;
1921 if (I.getType() != Type::VoidTy) {
1922 MVT::ValueType VT = TLI.getValueType(I.getType());
1923 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001924 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00001925 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1926
1927 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1928 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1929 }
1930
1931 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1932 VTs.push_back(VT);
1933 }
1934 if (HasChain)
1935 VTs.push_back(MVT::Other);
1936
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001937 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1938
Chris Lattner0eade312006-03-24 02:22:33 +00001939 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001940 SDOperand Result;
1941 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001942 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1943 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001944 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001945 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1946 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001947 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001948 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1949 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001950
Chris Lattnere58a7802006-04-02 03:41:14 +00001951 if (HasChain) {
1952 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1953 if (OnlyLoad)
1954 PendingLoads.push_back(Chain);
1955 else
1956 DAG.setRoot(Chain);
1957 }
Chris Lattner0eade312006-03-24 02:22:33 +00001958 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001959 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattner0eade312006-03-24 02:22:33 +00001960 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1961 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1962 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1963 DAG.getValueType(EVT));
1964 }
1965 setValue(&I, Result);
1966 }
1967}
1968
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001969/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1970/// we want to emit this as a call to a named external function, return the name
1971/// otherwise lower it and return null.
1972const char *
1973SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1974 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001975 default:
1976 // By default, turn this into a target intrinsic node.
1977 visitTargetIntrinsic(I, Intrinsic);
1978 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001979 case Intrinsic::vastart: visitVAStart(I); return 0;
1980 case Intrinsic::vaend: visitVAEnd(I); return 0;
1981 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00001982 case Intrinsic::returnaddress:
1983 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
1984 getValue(I.getOperand(1))));
1985 return 0;
1986 case Intrinsic::frameaddress:
1987 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
1988 getValue(I.getOperand(1))));
1989 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001990 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001991 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001992 break;
1993 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001994 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001995 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001996 case Intrinsic::memcpy_i32:
1997 case Intrinsic::memcpy_i64:
1998 visitMemIntrinsic(I, ISD::MEMCPY);
1999 return 0;
2000 case Intrinsic::memset_i32:
2001 case Intrinsic::memset_i64:
2002 visitMemIntrinsic(I, ISD::MEMSET);
2003 return 0;
2004 case Intrinsic::memmove_i32:
2005 case Intrinsic::memmove_i64:
2006 visitMemIntrinsic(I, ISD::MEMMOVE);
2007 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002008
Chris Lattner86cb6432005-12-13 17:40:33 +00002009 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002010 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002011 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002012 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002013 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002014
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002015 Ops[0] = getRoot();
2016 Ops[1] = getValue(SPI.getLineValue());
2017 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002018
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002019 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002020 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002021 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2022
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002023 Ops[3] = DAG.getString(CompileUnit->getFileName());
2024 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002025
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002026 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002027 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002028
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002029 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002030 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002031 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002032 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002033 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002034 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2035 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002036 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002037 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002038 }
2039
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002040 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002041 }
2042 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002043 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002044 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002045 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2046 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002047 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002048 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002049 }
2050
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002051 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002052 }
2053 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002054 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002055 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002056 if (MMI && FSI.getSubprogram() &&
2057 MMI->Verify(FSI.getSubprogram())) {
2058 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002059 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002060 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002061 }
2062
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002063 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002064 }
2065 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002066 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002067 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002068 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002069 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002070 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002071 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002072 }
2073
2074 return 0;
2075 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002076
Jim Laskeyb180aa12007-02-21 22:53:45 +00002077 case Intrinsic::eh_exception: {
2078 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2079
Jim Laskey735b6f82007-02-22 15:38:06 +00002080 if (MMI) {
2081 // Add a label to mark the beginning of the landing pad. Deletion of the
2082 // landing pad can thus be detected via the MachineModuleInfo.
2083 unsigned LabelID = MMI->addLandingPad(CurMBB);
2084 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2085 DAG.getConstant(LabelID, MVT::i32)));
2086
2087 // Mark exception register as live in.
2088 unsigned Reg = TLI.getExceptionAddressRegister();
2089 if (Reg) CurMBB->addLiveIn(Reg);
2090
2091 // Insert the EXCEPTIONADDR instruction.
2092 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2093 SDOperand Ops[1];
2094 Ops[0] = DAG.getRoot();
2095 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2096 setValue(&I, Op);
2097 DAG.setRoot(Op.getValue(1));
2098 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002099 return 0;
2100 }
2101
2102 case Intrinsic::eh_handlers: {
2103 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2104
Jim Laskey735b6f82007-02-22 15:38:06 +00002105 if (MMI) {
2106 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002107 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2108 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2109 isa<Function>(CE->getOperand(0)) &&
2110 "Personality should be a function");
2111 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00002112
Jim Laskey735b6f82007-02-22 15:38:06 +00002113 // Gather all the type infos for this landing pad and pass them along to
2114 // MachineModuleInfo.
2115 std::vector<GlobalVariable *> TyInfo;
2116 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002117 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2118 if (CE && CE->getOpcode() == Instruction::BitCast &&
2119 isa<GlobalVariable>(CE->getOperand(0))) {
2120 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2121 } else {
2122 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2123 assert(CI && CI->getZExtValue() == 0 &&
2124 "TypeInfo must be a global variable typeinfo or NULL");
2125 TyInfo.push_back(NULL);
Jim Laskey735b6f82007-02-22 15:38:06 +00002126 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002127 }
2128 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2129
2130 // Mark exception selector register as live in.
2131 unsigned Reg = TLI.getExceptionSelectorRegister();
2132 if (Reg) CurMBB->addLiveIn(Reg);
2133
2134 // Insert the EHSELECTION instruction.
2135 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2136 SDOperand Ops[2];
2137 Ops[0] = getValue(I.getOperand(1));
2138 Ops[1] = getRoot();
2139 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2140 setValue(&I, Op);
2141 DAG.setRoot(Op.getValue(1));
2142 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002143
2144 return 0;
2145 }
2146
2147 case Intrinsic::eh_typeid_for: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002148 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeyb180aa12007-02-21 22:53:45 +00002149
Jim Laskey735b6f82007-02-22 15:38:06 +00002150 if (MMI) {
2151 // Find the type id for the given typeinfo.
2152 GlobalVariable *GV = NULL;
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002153 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2154 if (CE && CE->getOpcode() == Instruction::BitCast &&
2155 isa<GlobalVariable>(CE->getOperand(0))) {
2156 GV = cast<GlobalVariable>(CE->getOperand(0));
2157 } else {
2158 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2159 assert(CI && CI->getZExtValue() == 0 &&
2160 "TypeInfo must be a global variable typeinfo or NULL");
2161 GV = NULL;
Jim Laskey735b6f82007-02-22 15:38:06 +00002162 }
2163
2164 unsigned TypeID = MMI->getTypeIDFor(GV);
2165 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
2166 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002167
2168 return 0;
2169 }
2170
Reid Spencer0b118202006-01-16 21:12:35 +00002171 case Intrinsic::sqrt_f32:
2172 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002173 setValue(&I, DAG.getNode(ISD::FSQRT,
2174 getValue(I.getOperand(1)).getValueType(),
2175 getValue(I.getOperand(1))));
2176 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002177 case Intrinsic::powi_f32:
2178 case Intrinsic::powi_f64:
2179 setValue(&I, DAG.getNode(ISD::FPOWI,
2180 getValue(I.getOperand(1)).getValueType(),
2181 getValue(I.getOperand(1)),
2182 getValue(I.getOperand(2))));
2183 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002184 case Intrinsic::pcmarker: {
2185 SDOperand Tmp = getValue(I.getOperand(1));
2186 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2187 return 0;
2188 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002189 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002190 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002191 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2192 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2193 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002194 setValue(&I, Tmp);
2195 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002196 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002197 }
Nate Begemand88fc032006-01-14 03:14:10 +00002198 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00002199 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00002200 case Intrinsic::bswap_i64:
2201 setValue(&I, DAG.getNode(ISD::BSWAP,
2202 getValue(I.getOperand(1)).getValueType(),
2203 getValue(I.getOperand(1))));
2204 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002205 case Intrinsic::cttz_i8:
2206 case Intrinsic::cttz_i16:
2207 case Intrinsic::cttz_i32:
2208 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002209 setValue(&I, DAG.getNode(ISD::CTTZ,
2210 getValue(I.getOperand(1)).getValueType(),
2211 getValue(I.getOperand(1))));
2212 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002213 case Intrinsic::ctlz_i8:
2214 case Intrinsic::ctlz_i16:
2215 case Intrinsic::ctlz_i32:
2216 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002217 setValue(&I, DAG.getNode(ISD::CTLZ,
2218 getValue(I.getOperand(1)).getValueType(),
2219 getValue(I.getOperand(1))));
2220 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002221 case Intrinsic::ctpop_i8:
2222 case Intrinsic::ctpop_i16:
2223 case Intrinsic::ctpop_i32:
2224 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002225 setValue(&I, DAG.getNode(ISD::CTPOP,
2226 getValue(I.getOperand(1)).getValueType(),
2227 getValue(I.getOperand(1))));
2228 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00002229 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002230 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002231 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2232 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002233 setValue(&I, Tmp);
2234 DAG.setRoot(Tmp.getValue(1));
2235 return 0;
2236 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002237 case Intrinsic::stackrestore: {
2238 SDOperand Tmp = getValue(I.getOperand(1));
2239 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002240 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002241 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002242 case Intrinsic::prefetch:
2243 // FIXME: Currently discarding prefetches.
2244 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002245 }
2246}
2247
2248
Jim Laskey735b6f82007-02-22 15:38:06 +00002249void SelectionDAGLowering::LowerCallTo(CallInst &I,
2250 SDOperand Callee, unsigned OpIdx) {
2251 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2252 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2253
2254 TargetLowering::ArgListTy Args;
2255 TargetLowering::ArgListEntry Entry;
2256 Args.reserve(I.getNumOperands());
2257 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2258 Value *Arg = I.getOperand(i);
2259 SDOperand ArgNode = getValue(Arg);
2260 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2261 Entry.isSigned = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2262 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2263 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
2264 Args.push_back(Entry);
2265 }
2266
2267 std::pair<SDOperand,SDOperand> Result =
2268 TLI.LowerCallTo(getRoot(), I.getType(),
2269 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
2270 FTy->isVarArg(), I.getCallingConv(), I.isTailCall(),
2271 Callee, Args, DAG);
2272 if (I.getType() != Type::VoidTy)
2273 setValue(&I, Result.first);
2274 DAG.setRoot(Result.second);
2275}
2276
2277
Chris Lattner1c08c712005-01-07 07:47:53 +00002278void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002279 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002280 if (Function *F = I.getCalledFunction()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00002281 if (F->isDeclaration())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002282 if (unsigned IID = F->getIntrinsicID()) {
2283 RenameFn = visitIntrinsicCall(I, IID);
2284 if (!RenameFn)
2285 return;
2286 } else { // Not an LLVM intrinsic.
2287 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002288 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2289 if (I.getNumOperands() == 3 && // Basic sanity checks.
2290 I.getOperand(1)->getType()->isFloatingPoint() &&
2291 I.getType() == I.getOperand(1)->getType() &&
2292 I.getType() == I.getOperand(2)->getType()) {
2293 SDOperand LHS = getValue(I.getOperand(1));
2294 SDOperand RHS = getValue(I.getOperand(2));
2295 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2296 LHS, RHS));
2297 return;
2298 }
2299 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002300 if (I.getNumOperands() == 2 && // Basic sanity checks.
2301 I.getOperand(1)->getType()->isFloatingPoint() &&
2302 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002303 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002304 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2305 return;
2306 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002307 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002308 if (I.getNumOperands() == 2 && // Basic sanity checks.
2309 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002310 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002311 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002312 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2313 return;
2314 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002315 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002316 if (I.getNumOperands() == 2 && // Basic sanity checks.
2317 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002318 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002319 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002320 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2321 return;
2322 }
2323 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002324 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002325 } else if (isa<InlineAsm>(I.getOperand(0))) {
2326 visitInlineAsm(I);
2327 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002328 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002329
Chris Lattner64e14b12005-01-08 22:48:57 +00002330 SDOperand Callee;
2331 if (!RenameFn)
2332 Callee = getValue(I.getOperand(0));
2333 else
2334 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey735b6f82007-02-22 15:38:06 +00002335
2336 LowerCallTo(I, Callee, 1);
Chris Lattner1c08c712005-01-07 07:47:53 +00002337}
2338
Jim Laskey735b6f82007-02-22 15:38:06 +00002339
Chris Lattner864635a2006-02-22 22:37:12 +00002340SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002341 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002342 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2343 Chain = Val.getValue(1);
2344 Flag = Val.getValue(2);
2345
2346 // If the result was expanded, copy from the top part.
2347 if (Regs.size() > 1) {
2348 assert(Regs.size() == 2 &&
2349 "Cannot expand to more than 2 elts yet!");
2350 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002351 Chain = Hi.getValue(1);
2352 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002353 if (DAG.getTargetLoweringInfo().isLittleEndian())
2354 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2355 else
2356 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002357 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002358
Chris Lattnercf752aa2006-06-08 18:22:48 +00002359 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002360 // appropriate type.
2361 if (RegVT == ValueVT)
2362 return Val;
2363
Chris Lattnercf752aa2006-06-08 18:22:48 +00002364 if (MVT::isInteger(RegVT)) {
2365 if (ValueVT < RegVT)
2366 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2367 else
2368 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2369 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002370 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002371 }
Chris Lattner864635a2006-02-22 22:37:12 +00002372}
2373
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002374/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2375/// specified value into the registers specified by this object. This uses
2376/// Chain/Flag as the input and updates them for the output Chain/Flag.
2377void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002378 SDOperand &Chain, SDOperand &Flag,
2379 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002380 if (Regs.size() == 1) {
2381 // If there is a single register and the types differ, this must be
2382 // a promotion.
2383 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002384 if (MVT::isInteger(RegVT)) {
2385 if (RegVT < ValueVT)
2386 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2387 else
2388 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2389 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002390 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2391 }
2392 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2393 Flag = Chain.getValue(1);
2394 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002395 std::vector<unsigned> R(Regs);
2396 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2397 std::reverse(R.begin(), R.end());
2398
2399 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002400 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002401 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002402 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002403 Flag = Chain.getValue(1);
2404 }
2405 }
2406}
Chris Lattner864635a2006-02-22 22:37:12 +00002407
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002408/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2409/// operand list. This adds the code marker and includes the number of
2410/// values added into it.
2411void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002412 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002413 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2414 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2415 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2416}
Chris Lattner864635a2006-02-22 22:37:12 +00002417
2418/// isAllocatableRegister - If the specified register is safe to allocate,
2419/// i.e. it isn't a stack pointer or some other special register, return the
2420/// register class for the register. Otherwise, return null.
2421static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002422isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2423 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002424 MVT::ValueType FoundVT = MVT::Other;
2425 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002426 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2427 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002428 MVT::ValueType ThisVT = MVT::Other;
2429
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002430 const TargetRegisterClass *RC = *RCI;
2431 // If none of the the value types for this register class are valid, we
2432 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002433 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2434 I != E; ++I) {
2435 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002436 // If we have already found this register in a different register class,
2437 // choose the one with the largest VT specified. For example, on
2438 // PowerPC, we favor f64 register classes over f32.
2439 if (FoundVT == MVT::Other ||
2440 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2441 ThisVT = *I;
2442 break;
2443 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002444 }
2445 }
2446
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002447 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002448
Chris Lattner864635a2006-02-22 22:37:12 +00002449 // NOTE: This isn't ideal. In particular, this might allocate the
2450 // frame pointer in functions that need it (due to them not being taken
2451 // out of allocation, because a variable sized allocation hasn't been seen
2452 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002453 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2454 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002455 if (*I == Reg) {
2456 // We found a matching register class. Keep looking at others in case
2457 // we find one with larger registers that this physreg is also in.
2458 FoundRC = RC;
2459 FoundVT = ThisVT;
2460 break;
2461 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002462 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002463 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002464}
2465
2466RegsForValue SelectionDAGLowering::
2467GetRegistersForValue(const std::string &ConstrCode,
2468 MVT::ValueType VT, bool isOutReg, bool isInReg,
2469 std::set<unsigned> &OutputRegs,
2470 std::set<unsigned> &InputRegs) {
2471 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2472 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2473 std::vector<unsigned> Regs;
2474
2475 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2476 MVT::ValueType RegVT;
2477 MVT::ValueType ValueVT = VT;
2478
Chris Lattner2a821602006-11-02 01:41:49 +00002479 // If this is a constraint for a specific physical register, like {r17},
2480 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002481 if (PhysReg.first) {
2482 if (VT == MVT::Other)
2483 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002484
2485 // Get the actual register value type. This is important, because the user
2486 // may have asked for (e.g.) the AX register in i32 type. We need to
2487 // remember that AX is actually i16 to get the right extension.
2488 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002489
2490 // This is a explicit reference to a physical register.
2491 Regs.push_back(PhysReg.first);
2492
2493 // If this is an expanded reference, add the rest of the regs to Regs.
2494 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002495 TargetRegisterClass::iterator I = PhysReg.second->begin();
2496 TargetRegisterClass::iterator E = PhysReg.second->end();
2497 for (; *I != PhysReg.first; ++I)
2498 assert(I != E && "Didn't find reg!");
2499
2500 // Already added the first reg.
2501 --NumRegs; ++I;
2502 for (; NumRegs; --NumRegs, ++I) {
2503 assert(I != E && "Ran out of registers to allocate!");
2504 Regs.push_back(*I);
2505 }
2506 }
2507 return RegsForValue(Regs, RegVT, ValueVT);
2508 }
2509
Chris Lattner2a821602006-11-02 01:41:49 +00002510 // Otherwise, if this was a reference to an LLVM register class, create vregs
2511 // for this reference.
2512 std::vector<unsigned> RegClassRegs;
2513 if (PhysReg.second) {
2514 // If this is an early clobber or tied register, our regalloc doesn't know
2515 // how to maintain the constraint. If it isn't, go ahead and create vreg
2516 // and let the regalloc do the right thing.
2517 if (!isOutReg || !isInReg) {
2518 if (VT == MVT::Other)
2519 ValueVT = *PhysReg.second->vt_begin();
2520 RegVT = *PhysReg.second->vt_begin();
2521
2522 // Create the appropriate number of virtual registers.
2523 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2524 for (; NumRegs; --NumRegs)
2525 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2526
2527 return RegsForValue(Regs, RegVT, ValueVT);
2528 }
2529
2530 // Otherwise, we can't allocate it. Let the code below figure out how to
2531 // maintain these constraints.
2532 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2533
2534 } else {
2535 // This is a reference to a register class that doesn't directly correspond
2536 // to an LLVM register class. Allocate NumRegs consecutive, available,
2537 // registers from the class.
2538 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2539 }
Chris Lattner864635a2006-02-22 22:37:12 +00002540
2541 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2542 MachineFunction &MF = *CurMBB->getParent();
2543 unsigned NumAllocated = 0;
2544 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2545 unsigned Reg = RegClassRegs[i];
2546 // See if this register is available.
2547 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2548 (isInReg && InputRegs.count(Reg))) { // Already used.
2549 // Make sure we find consecutive registers.
2550 NumAllocated = 0;
2551 continue;
2552 }
2553
2554 // Check to see if this register is allocatable (i.e. don't give out the
2555 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002556 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002557 if (!RC) {
2558 // Make sure we find consecutive registers.
2559 NumAllocated = 0;
2560 continue;
2561 }
2562
2563 // Okay, this register is good, we can use it.
2564 ++NumAllocated;
2565
2566 // If we allocated enough consecutive
2567 if (NumAllocated == NumRegs) {
2568 unsigned RegStart = (i-NumAllocated)+1;
2569 unsigned RegEnd = i+1;
2570 // Mark all of the allocated registers used.
2571 for (unsigned i = RegStart; i != RegEnd; ++i) {
2572 unsigned Reg = RegClassRegs[i];
2573 Regs.push_back(Reg);
2574 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2575 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2576 }
2577
2578 return RegsForValue(Regs, *RC->vt_begin(), VT);
2579 }
2580 }
2581
2582 // Otherwise, we couldn't allocate enough registers for this.
2583 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002584}
2585
Chris Lattner367f1092007-01-29 23:45:14 +00002586/// getConstraintGenerality - Return an integer indicating how general CT is.
2587static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2588 switch (CT) {
2589 default: assert(0 && "Unknown constraint type!");
2590 case TargetLowering::C_Other:
2591 case TargetLowering::C_Unknown:
2592 return 0;
2593 case TargetLowering::C_Register:
2594 return 1;
2595 case TargetLowering::C_RegisterClass:
2596 return 2;
2597 case TargetLowering::C_Memory:
2598 return 3;
2599 }
2600}
2601
2602static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2603 const TargetLowering &TLI) {
2604 assert(!C.empty() && "Must have at least one constraint");
2605 if (C.size() == 1) return C[0];
2606
2607 std::string *Current = &C[0];
2608 // If we have multiple constraints, try to pick the most general one ahead
2609 // of time. This isn't a wonderful solution, but handles common cases.
2610 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0][0]);
2611 for (unsigned j = 1, e = C.size(); j != e; ++j) {
2612 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j][0]);
2613 if (getConstraintGenerality(ThisFlavor) >
2614 getConstraintGenerality(Flavor)) {
2615 // This constraint letter is more general than the previous one,
2616 // use it.
2617 Flavor = ThisFlavor;
2618 Current = &C[j];
2619 }
2620 }
2621 return *Current;
2622}
2623
Chris Lattner864635a2006-02-22 22:37:12 +00002624
Chris Lattnerce7518c2006-01-26 22:24:51 +00002625/// visitInlineAsm - Handle a call to an InlineAsm object.
2626///
2627void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2628 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2629
2630 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2631 MVT::Other);
2632
Chris Lattner2cc2f662006-02-01 01:28:23 +00002633 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002634 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002635
2636 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2637 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2638 /// if it is a def of that register.
2639 std::vector<SDOperand> AsmNodeOperands;
2640 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2641 AsmNodeOperands.push_back(AsmStr);
2642
2643 SDOperand Chain = getRoot();
2644 SDOperand Flag;
2645
Chris Lattner4e4b5762006-02-01 18:59:47 +00002646 // We fully assign registers here at isel time. This is not optimal, but
2647 // should work. For register classes that correspond to LLVM classes, we
2648 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2649 // over the constraints, collecting fixed registers that we know we can't use.
2650 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002651 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002652 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002653 std::string ConstraintCode =
2654 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner2223aea2006-02-02 00:25:23 +00002655
Chris Lattner1efa40f2006-02-22 00:56:39 +00002656 MVT::ValueType OpVT;
2657
2658 // Compute the value type for each operand and add it to ConstraintVTs.
2659 switch (Constraints[i].Type) {
2660 case InlineAsm::isOutput:
2661 if (!Constraints[i].isIndirectOutput) {
2662 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2663 OpVT = TLI.getValueType(I.getType());
2664 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002665 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002666 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2667 OpNum++; // Consumes a call operand.
2668 }
2669 break;
2670 case InlineAsm::isInput:
2671 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2672 OpNum++; // Consumes a call operand.
2673 break;
2674 case InlineAsm::isClobber:
2675 OpVT = MVT::Other;
2676 break;
2677 }
2678
2679 ConstraintVTs.push_back(OpVT);
2680
Chris Lattner864635a2006-02-22 22:37:12 +00002681 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2682 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002683
Chris Lattner864635a2006-02-22 22:37:12 +00002684 // Build a list of regs that this operand uses. This always has a single
2685 // element for promoted/expanded operands.
2686 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2687 false, false,
2688 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002689
2690 switch (Constraints[i].Type) {
2691 case InlineAsm::isOutput:
2692 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002693 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002694 // If this is an early-clobber output, it cannot be assigned to the same
2695 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002696 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002697 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002698 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002699 case InlineAsm::isInput:
2700 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002701 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002702 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002703 case InlineAsm::isClobber:
2704 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002705 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2706 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002707 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002708 }
2709 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002710
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002711 // Loop over all of the inputs, copying the operand values into the
2712 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002713 RegsForValue RetValRegs;
2714 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002715 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002716
Chris Lattner6656dd12006-01-31 02:03:41 +00002717 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002718 std::string ConstraintCode =
2719 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner1efa40f2006-02-22 00:56:39 +00002720
Chris Lattner2cc2f662006-02-01 01:28:23 +00002721 switch (Constraints[i].Type) {
2722 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002723 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2724 if (ConstraintCode.size() == 1) // not a physreg name.
2725 CTy = TLI.getConstraintType(ConstraintCode[0]);
2726
2727 if (CTy == TargetLowering::C_Memory) {
2728 // Memory output.
2729 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2730
2731 // Check that the operand (the address to store to) isn't a float.
2732 if (!MVT::isInteger(InOperandVal.getValueType()))
2733 assert(0 && "MATCH FAIL!");
2734
2735 if (!Constraints[i].isIndirectOutput)
2736 assert(0 && "MATCH FAIL!");
2737
2738 OpNum++; // Consumes a call operand.
2739
2740 // Extend/truncate to the right pointer type if needed.
2741 MVT::ValueType PtrType = TLI.getPointerTy();
2742 if (InOperandVal.getValueType() < PtrType)
2743 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2744 else if (InOperandVal.getValueType() > PtrType)
2745 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2746
2747 // Add information to the INLINEASM node to know about this output.
2748 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2749 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2750 AsmNodeOperands.push_back(InOperandVal);
2751 break;
2752 }
2753
2754 // Otherwise, this is a register output.
2755 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2756
Chris Lattner864635a2006-02-22 22:37:12 +00002757 // If this is an early-clobber output, or if there is an input
2758 // constraint that matches this, we need to reserve the input register
2759 // so no other inputs allocate to it.
2760 bool UsesInputRegister = false;
2761 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2762 UsesInputRegister = true;
2763
2764 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002765 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002766 RegsForValue Regs =
2767 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2768 true, UsesInputRegister,
2769 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00002770 if (Regs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00002771 cerr << "Couldn't allocate output reg for contraint '"
2772 << ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00002773 exit(1);
2774 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00002775
Chris Lattner2cc2f662006-02-01 01:28:23 +00002776 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002777 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002778 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002779 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002780 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002781 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002782 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2783 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002784 OpNum++; // Consumes a call operand.
2785 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002786
2787 // Add information to the INLINEASM node to know that this register is
2788 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002789 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002790 break;
2791 }
2792 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002793 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002794 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002795
Chris Lattner2223aea2006-02-02 00:25:23 +00002796 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2797 // If this is required to match an output register we have already set,
2798 // just use its register.
2799 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002800
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002801 // Scan until we find the definition we already emitted of this operand.
2802 // When we find it, create a RegsForValue operand.
2803 unsigned CurOp = 2; // The first operand.
2804 for (; OperandNo; --OperandNo) {
2805 // Advance to the next operand.
2806 unsigned NumOps =
2807 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002808 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2809 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002810 "Skipped past definitions?");
2811 CurOp += (NumOps>>3)+1;
2812 }
2813
2814 unsigned NumOps =
2815 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00002816 if ((NumOps & 7) == 2 /*REGDEF*/) {
2817 // Add NumOps>>3 registers to MatchedRegs.
2818 RegsForValue MatchedRegs;
2819 MatchedRegs.ValueVT = InOperandVal.getValueType();
2820 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2821 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2822 unsigned Reg =
2823 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2824 MatchedRegs.Regs.push_back(Reg);
2825 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002826
Chris Lattner527fae12007-02-01 01:21:12 +00002827 // Use the produced MatchedRegs object to
2828 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2829 TLI.getPointerTy());
2830 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2831 break;
2832 } else {
2833 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
2834 assert(0 && "matching constraints for memory operands unimp");
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002835 }
Chris Lattner2223aea2006-02-02 00:25:23 +00002836 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002837
2838 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2839 if (ConstraintCode.size() == 1) // not a physreg name.
2840 CTy = TLI.getConstraintType(ConstraintCode[0]);
2841
2842 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00002843 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2844 ConstraintCode[0], DAG);
2845 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00002846 cerr << "Invalid operand for inline asm constraint '"
2847 << ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00002848 exit(1);
2849 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002850
2851 // Add information to the INLINEASM node to know about this input.
2852 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2853 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2854 AsmNodeOperands.push_back(InOperandVal);
2855 break;
2856 } else if (CTy == TargetLowering::C_Memory) {
2857 // Memory input.
2858
2859 // Check that the operand isn't a float.
2860 if (!MVT::isInteger(InOperandVal.getValueType()))
2861 assert(0 && "MATCH FAIL!");
2862
2863 // Extend/truncate to the right pointer type if needed.
2864 MVT::ValueType PtrType = TLI.getPointerTy();
2865 if (InOperandVal.getValueType() < PtrType)
2866 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2867 else if (InOperandVal.getValueType() > PtrType)
2868 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2869
2870 // Add information to the INLINEASM node to know about this input.
2871 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2872 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2873 AsmNodeOperands.push_back(InOperandVal);
2874 break;
2875 }
2876
2877 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2878
2879 // Copy the input into the appropriate registers.
2880 RegsForValue InRegs =
2881 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2882 false, true, OutputRegs, InputRegs);
2883 // FIXME: should be match fail.
2884 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2885
Evan Chenga8441262006-06-15 08:11:54 +00002886 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002887
2888 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002889 break;
2890 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002891 case InlineAsm::isClobber: {
2892 RegsForValue ClobberedRegs =
2893 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2894 OutputRegs, InputRegs);
2895 // Add the clobbered value to the operand list, so that the register
2896 // allocator is aware that the physreg got clobbered.
2897 if (!ClobberedRegs.Regs.empty())
2898 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002899 break;
2900 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002901 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002902 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002903
2904 // Finish up input operands.
2905 AsmNodeOperands[0] = Chain;
2906 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2907
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002908 Chain = DAG.getNode(ISD::INLINEASM,
2909 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002910 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002911 Flag = Chain.getValue(1);
2912
Chris Lattner6656dd12006-01-31 02:03:41 +00002913 // If this asm returns a register value, copy the result from that register
2914 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002915 if (!RetValRegs.Regs.empty())
2916 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002917
Chris Lattner6656dd12006-01-31 02:03:41 +00002918 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2919
2920 // Process indirect outputs, first output all of the flagged copies out of
2921 // physregs.
2922 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002923 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002924 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002925 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2926 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002927 }
2928
2929 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002930 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002931 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002932 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002933 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002934 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002935 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002936 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2937 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002938 DAG.setRoot(Chain);
2939}
2940
2941
Chris Lattner1c08c712005-01-07 07:47:53 +00002942void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2943 SDOperand Src = getValue(I.getOperand(0));
2944
2945 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002946
2947 if (IntPtr < Src.getValueType())
2948 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2949 else if (IntPtr > Src.getValueType())
2950 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002951
2952 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002953 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002954 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2955 Src, getIntPtrConstant(ElementSize));
2956
Reid Spencer47857812006-12-31 05:55:36 +00002957 TargetLowering::ArgListTy Args;
2958 TargetLowering::ArgListEntry Entry;
2959 Entry.Node = Src;
2960 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2961 Entry.isSigned = false;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002962 Entry.isInReg = false;
2963 Entry.isSRet = false;
Reid Spencer47857812006-12-31 05:55:36 +00002964 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00002965
2966 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002967 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002968 DAG.getExternalSymbol("malloc", IntPtr),
2969 Args, DAG);
2970 setValue(&I, Result.first); // Pointers always fit in registers
2971 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002972}
2973
2974void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00002975 TargetLowering::ArgListTy Args;
2976 TargetLowering::ArgListEntry Entry;
2977 Entry.Node = getValue(I.getOperand(0));
2978 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2979 Entry.isSigned = false;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002980 Entry.isInReg = false;
2981 Entry.isSRet = false;
Reid Spencer47857812006-12-31 05:55:36 +00002982 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00002983 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002984 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00002985 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002986 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2987 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002988}
2989
Chris Lattner025c39b2005-08-26 20:54:47 +00002990// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2991// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2992// instructions are special in various ways, which require special support to
2993// insert. The specified MachineInstr is created but not inserted into any
2994// basic blocks, and the scheduler passes ownership of it to this method.
2995MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2996 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00002997 cerr << "If a target marks an instruction with "
2998 << "'usesCustomDAGSchedInserter', it must implement "
2999 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00003000 abort();
3001 return 0;
3002}
3003
Chris Lattner39ae3622005-01-09 00:00:49 +00003004void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003005 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3006 getValue(I.getOperand(1)),
3007 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00003008}
3009
3010void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003011 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3012 getValue(I.getOperand(0)),
3013 DAG.getSrcValue(I.getOperand(0)));
3014 setValue(&I, V);
3015 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00003016}
3017
3018void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003019 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3020 getValue(I.getOperand(1)),
3021 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003022}
3023
3024void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003025 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3026 getValue(I.getOperand(1)),
3027 getValue(I.getOperand(2)),
3028 DAG.getSrcValue(I.getOperand(1)),
3029 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003030}
3031
Evan Chengb15974a2006-12-12 07:27:38 +00003032/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3033/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3034static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3035 unsigned &i, SelectionDAG &DAG,
3036 TargetLowering &TLI) {
3037 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3038 return SDOperand(Arg, i++);
3039
3040 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3041 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3042 if (NumVals == 1) {
3043 return DAG.getNode(ISD::BIT_CONVERT, VT,
3044 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3045 } else if (NumVals == 2) {
3046 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3047 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3048 if (!TLI.isLittleEndian())
3049 std::swap(Lo, Hi);
3050 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3051 } else {
3052 // Value scalarized into many values. Unimp for now.
3053 assert(0 && "Cannot expand i64 -> i16 yet!");
3054 }
3055 return SDOperand();
3056}
3057
Chris Lattnerfdfded52006-04-12 16:20:43 +00003058/// TargetLowering::LowerArguments - This is the default LowerArguments
3059/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003060/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3061/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003062std::vector<SDOperand>
3063TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003064 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003065 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3066 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003067 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00003068 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3069 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3070
3071 // Add one result value for each formal argument.
3072 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00003073 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00003074 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3075 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003076 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00003077 bool isInReg = FTy->paramHasAttr(j, FunctionType::InRegAttribute);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003078 bool isSRet = FTy->paramHasAttr(j, FunctionType::StructRetAttribute);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003079 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003080 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003081 // Flags[31:27] -> OriginalAlignment
3082 // Flags[2] -> isSRet
3083 // Flags[1] -> isInReg
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003084 unsigned Flags = (isInReg << 1) | (isSRet << 2) | (OriginalAlignment << 27);
3085
Chris Lattnerfdfded52006-04-12 16:20:43 +00003086 switch (getTypeAction(VT)) {
3087 default: assert(0 && "Unknown type action!");
3088 case Legal:
3089 RetVals.push_back(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003090 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003091 break;
3092 case Promote:
3093 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003094 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003095 break;
3096 case Expand:
3097 if (VT != MVT::Vector) {
3098 // If this is a large integer, it needs to be broken up into small
3099 // integers. Figure out what the destination type is and how many small
3100 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00003101 MVT::ValueType NVT = getTypeToExpandTo(VT);
3102 unsigned NumVals = getNumElements(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003103 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003104 RetVals.push_back(NVT);
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003105 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003106 if (i == 1) Flags = (Flags & 0x07ffffff) | (1 << 27);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003107 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3108 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00003109 } else {
3110 // Otherwise, this is a vector type. We only support legal vectors
3111 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003112 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3113 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003114
Chris Lattnerfdfded52006-04-12 16:20:43 +00003115 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003116 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003117 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3118 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3119 RetVals.push_back(TVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003120 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003121 } else {
3122 assert(0 && "Don't support illegal by-val vector arguments yet!");
3123 }
3124 }
3125 break;
3126 }
3127 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00003128
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003129 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00003130
3131 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003132 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3133 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003134 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003135
3136 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003137
3138 // Set up the return result vector.
3139 Ops.clear();
3140 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00003141 unsigned Idx = 1;
3142 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3143 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003144 MVT::ValueType VT = getValueType(I->getType());
3145
3146 switch (getTypeAction(VT)) {
3147 default: assert(0 && "Unknown type action!");
3148 case Legal:
3149 Ops.push_back(SDOperand(Result, i++));
3150 break;
3151 case Promote: {
3152 SDOperand Op(Result, i++);
3153 if (MVT::isInteger(VT)) {
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003154 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3155 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3156 DAG.getValueType(VT));
3157 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3158 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3159 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003160 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3161 } else {
3162 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3163 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3164 }
3165 Ops.push_back(Op);
3166 break;
3167 }
3168 case Expand:
3169 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00003170 // If this is a large integer or a floating point node that needs to be
3171 // expanded, it needs to be reassembled from small integers. Figure out
3172 // what the source elt type is and how many small integers it is.
3173 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003174 } else {
3175 // Otherwise, this is a vector type. We only support legal vectors
3176 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003177 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Cheng020c41f2006-04-28 05:25:15 +00003178 unsigned NumElems = PTy->getNumElements();
3179 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003180
Chris Lattnerfdfded52006-04-12 16:20:43 +00003181 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003182 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003183 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00003184 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00003185 SDOperand N = SDOperand(Result, i++);
3186 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00003187 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3188 DAG.getConstant(NumElems, MVT::i32),
3189 DAG.getValueType(getValueType(EltTy)));
3190 Ops.push_back(N);
3191 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003192 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00003193 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003194 }
3195 }
3196 break;
3197 }
3198 }
3199 return Ops;
3200}
3201
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003202
Evan Chengb15974a2006-12-12 07:27:38 +00003203/// ExpandScalarCallArgs - Recursively expand call argument node by
3204/// bit_converting it or extract a pair of elements from the larger node.
3205static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003206 unsigned Flags,
Evan Chengb15974a2006-12-12 07:27:38 +00003207 SmallVector<SDOperand, 32> &Ops,
3208 SelectionDAG &DAG,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003209 TargetLowering &TLI,
3210 bool isFirst = true) {
3211
Evan Chengb15974a2006-12-12 07:27:38 +00003212 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003213 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003214 if (!isFirst)
3215 Flags = (Flags & 0x07ffffff) | (1 << 27);
Evan Chengb15974a2006-12-12 07:27:38 +00003216 Ops.push_back(Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003217 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Chengb15974a2006-12-12 07:27:38 +00003218 return;
3219 }
3220
3221 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3222 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3223 if (NumVals == 1) {
3224 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003225 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Chengb15974a2006-12-12 07:27:38 +00003226 } else if (NumVals == 2) {
3227 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3228 DAG.getConstant(0, TLI.getPointerTy()));
3229 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3230 DAG.getConstant(1, TLI.getPointerTy()));
3231 if (!TLI.isLittleEndian())
3232 std::swap(Lo, Hi);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003233 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3234 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Chengb15974a2006-12-12 07:27:38 +00003235 } else {
3236 // Value scalarized into many values. Unimp for now.
3237 assert(0 && "Cannot expand i64 -> i16 yet!");
3238 }
3239}
3240
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003241/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3242/// implementation, which just inserts an ISD::CALL node, which is later custom
3243/// lowered by the target to something concrete. FIXME: When all targets are
3244/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3245std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003246TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3247 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003248 unsigned CallingConv, bool isTailCall,
3249 SDOperand Callee,
3250 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003251 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003252 Ops.push_back(Chain); // Op#0 - Chain
3253 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3254 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3255 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3256 Ops.push_back(Callee);
3257
3258 // Handle all of the outgoing arguments.
3259 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003260 MVT::ValueType VT = getValueType(Args[i].Ty);
3261 SDOperand Op = Args[i].Node;
3262 bool isSigned = Args[i].isSigned;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003263 bool isInReg = Args[i].isInReg;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003264 bool isSRet = Args[i].isSRet;
3265 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003266 getTargetData()->getABITypeAlignment(Args[i].Ty);
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003267 // Flags[31:27] -> OriginalAlignment
3268 // Flags[2] -> isSRet
3269 // Flags[1] -> isInReg
3270 // Flags[0] -> isSigned
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003271 unsigned Flags = (isSRet << 2) | (isInReg << 1) | isSigned |
3272 (OriginalAlignment << 27);
3273
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003274 switch (getTypeAction(VT)) {
3275 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003276 case Legal:
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003277 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003278 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003279 break;
3280 case Promote:
3281 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00003282 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003283 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3284 } else {
3285 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3286 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3287 }
3288 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003289 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003290 break;
3291 case Expand:
3292 if (VT != MVT::Vector) {
3293 // If this is a large integer, it needs to be broken down into small
3294 // integers. Figure out what the source elt type is and how many small
3295 // integers it is.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003296 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003297 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003298 // Otherwise, this is a vector type. We only support legal vectors
3299 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003300 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00003301 unsigned NumElems = PTy->getNumElements();
3302 const Type *EltTy = PTy->getElementType();
3303
3304 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003305 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003306 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003307 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencerac9dcb92007-02-15 03:39:18 +00003308 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner1b8daae2006-05-17 20:43:21 +00003309 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3310 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003311 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003312 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003313 assert(0 && "Don't support illegal by-val vector call args yet!");
3314 abort();
3315 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003316 }
3317 break;
3318 }
3319 }
3320
3321 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003322 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003323
3324 if (RetTy != Type::VoidTy) {
3325 MVT::ValueType VT = getValueType(RetTy);
3326 switch (getTypeAction(VT)) {
3327 default: assert(0 && "Unknown type action!");
3328 case Legal:
3329 RetTys.push_back(VT);
3330 break;
3331 case Promote:
3332 RetTys.push_back(getTypeToTransformTo(VT));
3333 break;
3334 case Expand:
3335 if (VT != MVT::Vector) {
3336 // If this is a large integer, it needs to be reassembled from small
3337 // integers. Figure out what the source elt type is and how many small
3338 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00003339 MVT::ValueType NVT = getTypeToExpandTo(VT);
3340 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003341 for (unsigned i = 0; i != NumVals; ++i)
3342 RetTys.push_back(NVT);
3343 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003344 // Otherwise, this is a vector type. We only support legal vectors
3345 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003346 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerda098e72006-05-16 23:39:44 +00003347 unsigned NumElems = PTy->getNumElements();
3348 const Type *EltTy = PTy->getElementType();
3349
3350 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003351 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003352 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3353 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3354 RetTys.push_back(TVT);
3355 } else {
3356 assert(0 && "Don't support illegal by-val vector call results yet!");
3357 abort();
3358 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003359 }
3360 }
3361 }
3362
3363 RetTys.push_back(MVT::Other); // Always has a chain.
3364
3365 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003366 SDOperand Res = DAG.getNode(ISD::CALL,
3367 DAG.getVTList(&RetTys[0], RetTys.size()),
3368 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003369
3370 // This returns a pair of operands. The first element is the
3371 // return value for the function (if RetTy is not VoidTy). The second
3372 // element is the outgoing token chain.
3373 SDOperand ResVal;
3374 if (RetTys.size() != 1) {
3375 MVT::ValueType VT = getValueType(RetTy);
3376 if (RetTys.size() == 2) {
3377 ResVal = Res;
3378
3379 // If this value was promoted, truncate it down.
3380 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003381 if (VT == MVT::Vector) {
3382 // Insert a VBITCONVERT to convert from the packed result type to the
3383 // MVT::Vector type.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003384 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3385 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerda098e72006-05-16 23:39:44 +00003386
3387 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003388 // type. If so, convert to the vector type.
Chris Lattnerfea997a2007-02-01 04:55:59 +00003389 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerda098e72006-05-16 23:39:44 +00003390 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003391 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3392 // "N x PTyElementVT" MVT::Vector type.
3393 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003394 DAG.getConstant(NumElems, MVT::i32),
3395 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003396 } else {
3397 abort();
3398 }
3399 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00003400 unsigned AssertOp = ISD::AssertSext;
3401 if (!RetTyIsSigned)
3402 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003403 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3404 DAG.getValueType(VT));
3405 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3406 } else {
3407 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003408 if (getTypeAction(VT) == Expand)
3409 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3410 else
3411 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003412 }
3413 }
3414 } else if (RetTys.size() == 3) {
3415 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3416 Res.getValue(0), Res.getValue(1));
3417
3418 } else {
3419 assert(0 && "Case not handled yet!");
3420 }
3421 }
3422
3423 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3424}
3425
Chris Lattner50381b62005-05-14 05:50:48 +00003426SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003427 assert(0 && "LowerOperation not implemented for this target!");
3428 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003429 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003430}
3431
Nate Begeman0aed7842006-01-28 03:14:31 +00003432SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3433 SelectionDAG &DAG) {
3434 assert(0 && "CustomPromoteOperation not implemented for this target!");
3435 abort();
3436 return SDOperand();
3437}
3438
Evan Cheng74d0aa92006-02-15 21:59:04 +00003439/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003440/// operand.
3441static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003442 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003443 MVT::ValueType CurVT = VT;
3444 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3445 uint64_t Val = C->getValue() & 255;
3446 unsigned Shift = 8;
3447 while (CurVT != MVT::i8) {
3448 Val = (Val << Shift) | Val;
3449 Shift <<= 1;
3450 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003451 }
3452 return DAG.getConstant(Val, VT);
3453 } else {
3454 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3455 unsigned Shift = 8;
3456 while (CurVT != MVT::i8) {
3457 Value =
3458 DAG.getNode(ISD::OR, VT,
3459 DAG.getNode(ISD::SHL, VT, Value,
3460 DAG.getConstant(Shift, MVT::i8)), Value);
3461 Shift <<= 1;
3462 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003463 }
3464
3465 return Value;
3466 }
3467}
3468
Evan Cheng74d0aa92006-02-15 21:59:04 +00003469/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3470/// used when a memcpy is turned into a memset when the source is a constant
3471/// string ptr.
3472static SDOperand getMemsetStringVal(MVT::ValueType VT,
3473 SelectionDAG &DAG, TargetLowering &TLI,
3474 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003475 uint64_t Val = 0;
3476 unsigned MSB = getSizeInBits(VT) / 8;
3477 if (TLI.isLittleEndian())
3478 Offset = Offset + MSB - 1;
3479 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00003480 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00003481 Offset += TLI.isLittleEndian() ? -1 : 1;
3482 }
3483 return DAG.getConstant(Val, VT);
3484}
3485
Evan Cheng1db92f92006-02-14 08:22:34 +00003486/// getMemBasePlusOffset - Returns base and offset node for the
3487static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3488 SelectionDAG &DAG, TargetLowering &TLI) {
3489 MVT::ValueType VT = Base.getValueType();
3490 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3491}
3492
Evan Chengc4f8eee2006-02-14 20:12:38 +00003493/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003494/// to replace the memset / memcpy is below the threshold. It also returns the
3495/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003496static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3497 unsigned Limit, uint64_t Size,
3498 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003499 MVT::ValueType VT;
3500
3501 if (TLI.allowsUnalignedMemoryAccesses()) {
3502 VT = MVT::i64;
3503 } else {
3504 switch (Align & 7) {
3505 case 0:
3506 VT = MVT::i64;
3507 break;
3508 case 4:
3509 VT = MVT::i32;
3510 break;
3511 case 2:
3512 VT = MVT::i16;
3513 break;
3514 default:
3515 VT = MVT::i8;
3516 break;
3517 }
3518 }
3519
Evan Cheng80e89d72006-02-14 09:11:59 +00003520 MVT::ValueType LVT = MVT::i64;
3521 while (!TLI.isTypeLegal(LVT))
3522 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3523 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003524
Evan Cheng80e89d72006-02-14 09:11:59 +00003525 if (VT > LVT)
3526 VT = LVT;
3527
Evan Chengdea72452006-02-14 23:05:54 +00003528 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003529 while (Size != 0) {
3530 unsigned VTSize = getSizeInBits(VT) / 8;
3531 while (VTSize > Size) {
3532 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003533 VTSize >>= 1;
3534 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003535 assert(MVT::isInteger(VT));
3536
3537 if (++NumMemOps > Limit)
3538 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003539 MemOps.push_back(VT);
3540 Size -= VTSize;
3541 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003542
3543 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003544}
3545
Chris Lattner7041ee32005-01-11 05:56:49 +00003546void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003547 SDOperand Op1 = getValue(I.getOperand(1));
3548 SDOperand Op2 = getValue(I.getOperand(2));
3549 SDOperand Op3 = getValue(I.getOperand(3));
3550 SDOperand Op4 = getValue(I.getOperand(4));
3551 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3552 if (Align == 0) Align = 1;
3553
3554 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3555 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003556
3557 // Expand memset / memcpy to a series of load / store ops
3558 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003559 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003560 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003561 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003562 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003563 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3564 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003565 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003566 unsigned Offset = 0;
3567 for (unsigned i = 0; i < NumMemOps; i++) {
3568 MVT::ValueType VT = MemOps[i];
3569 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003570 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003571 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003572 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003573 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003574 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003575 Offset += VTSize;
3576 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003577 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003578 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003579 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003580 case ISD::MEMCPY: {
3581 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3582 Size->getValue(), Align, TLI)) {
3583 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003584 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003585 GlobalAddressSDNode *G = NULL;
3586 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003587 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003588
3589 if (Op2.getOpcode() == ISD::GlobalAddress)
3590 G = cast<GlobalAddressSDNode>(Op2);
3591 else if (Op2.getOpcode() == ISD::ADD &&
3592 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3593 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3594 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003595 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003596 }
3597 if (G) {
3598 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00003599 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00003600 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003601 if (!Str.empty()) {
3602 CopyFromStr = true;
3603 SrcOff += SrcDelta;
3604 }
3605 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003606 }
3607
Evan Chengc080d6f2006-02-15 01:54:51 +00003608 for (unsigned i = 0; i < NumMemOps; i++) {
3609 MVT::ValueType VT = MemOps[i];
3610 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003611 SDOperand Value, Chain, Store;
3612
Evan Chengcffbb512006-02-16 23:11:42 +00003613 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003614 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3615 Chain = getRoot();
3616 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003617 DAG.getStore(Chain, Value,
3618 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003619 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003620 } else {
3621 Value = DAG.getLoad(VT, getRoot(),
3622 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003623 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003624 Chain = Value.getValue(1);
3625 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003626 DAG.getStore(Chain, Value,
3627 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003628 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003629 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003630 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003631 SrcOff += VTSize;
3632 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003633 }
3634 }
3635 break;
3636 }
3637 }
3638
3639 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003640 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3641 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003642 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003643 }
3644 }
3645
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003646 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003647}
3648
Chris Lattner7041ee32005-01-11 05:56:49 +00003649//===----------------------------------------------------------------------===//
3650// SelectionDAGISel code
3651//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003652
3653unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3654 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3655}
3656
Chris Lattner495a0b52005-08-17 06:37:43 +00003657void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003658 // FIXME: we only modify the CFG to split critical edges. This
3659 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003660 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003661}
Chris Lattner1c08c712005-01-07 07:47:53 +00003662
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003663
Chris Lattner90323642006-05-05 21:17:49 +00003664/// OptimizeNoopCopyExpression - We have determined that the specified cast
3665/// instruction is a noop copy (e.g. it's casting from one pointer type to
3666/// another, int->uint, or int->sbyte on PPC.
3667///
3668/// Return true if any changes are made.
3669static bool OptimizeNoopCopyExpression(CastInst *CI) {
3670 BasicBlock *DefBB = CI->getParent();
3671
3672 /// InsertedCasts - Only insert a cast in each block once.
3673 std::map<BasicBlock*, CastInst*> InsertedCasts;
3674
3675 bool MadeChange = false;
3676 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3677 UI != E; ) {
3678 Use &TheUse = UI.getUse();
3679 Instruction *User = cast<Instruction>(*UI);
3680
3681 // Figure out which BB this cast is used in. For PHI's this is the
3682 // appropriate predecessor block.
3683 BasicBlock *UserBB = User->getParent();
3684 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3685 unsigned OpVal = UI.getOperandNo()/2;
3686 UserBB = PN->getIncomingBlock(OpVal);
3687 }
3688
3689 // Preincrement use iterator so we don't invalidate it.
3690 ++UI;
3691
3692 // If this user is in the same block as the cast, don't change the cast.
3693 if (UserBB == DefBB) continue;
3694
3695 // If we have already inserted a cast into this block, use it.
3696 CastInst *&InsertedCast = InsertedCasts[UserBB];
3697
3698 if (!InsertedCast) {
3699 BasicBlock::iterator InsertPt = UserBB->begin();
3700 while (isa<PHINode>(InsertPt)) ++InsertPt;
3701
3702 InsertedCast =
Reid Spencer7b06bd52006-12-13 00:50:17 +00003703 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3704 InsertPt);
Chris Lattner90323642006-05-05 21:17:49 +00003705 MadeChange = true;
3706 }
3707
3708 // Replace a use of the cast with a use of the new casat.
3709 TheUse = InsertedCast;
3710 }
3711
3712 // If we removed all uses, nuke the cast.
3713 if (CI->use_empty())
3714 CI->eraseFromParent();
3715
3716 return MadeChange;
3717}
3718
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003719/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3720/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003721static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3722 Instruction *GEPI, Value *Ptr,
3723 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003724 if (V) return V; // Already computed.
3725
Reid Spencer3da59db2006-11-27 01:05:10 +00003726 // Figure out the insertion point
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003727 BasicBlock::iterator InsertPt;
3728 if (BB == GEPI->getParent()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003729 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003730 InsertPt = GEPI;
3731 ++InsertPt;
3732 } else {
3733 // Otherwise, insert at the top of BB, after any PHI nodes
3734 InsertPt = BB->begin();
3735 while (isa<PHINode>(InsertPt)) ++InsertPt;
3736 }
3737
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003738 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3739 // BB so that there is only one value live across basic blocks (the cast
3740 // operand).
3741 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3742 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencer7b06bd52006-12-13 00:50:17 +00003743 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3744 "", InsertPt);
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003745
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003746 // Add the offset, cast it to the right type.
3747 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer3da59db2006-11-27 01:05:10 +00003748 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3749 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3750 "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003751}
3752
Chris Lattner90323642006-05-05 21:17:49 +00003753/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3754/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3755/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3756/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3757/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3758/// the constant add into a load or store instruction. Additionally, if a user
3759/// is a pointer-pointer cast, we look through it to find its users.
3760static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3761 Constant *PtrOffset, BasicBlock *DefBB,
3762 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003763 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003764 while (!RepPtr->use_empty()) {
3765 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003766
Reid Spencer3da59db2006-11-27 01:05:10 +00003767 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3768 // used for a Pointer-Pointer cast.
3769 if (isa<BitCastInst>(User)) {
Chris Lattner90323642006-05-05 21:17:49 +00003770 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003771
Chris Lattner90323642006-05-05 21:17:49 +00003772 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3773 // could invalidate an iterator.
3774 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3775 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003776 }
3777
Chris Lattner90323642006-05-05 21:17:49 +00003778 // If this is a load of the pointer, or a store through the pointer, emit
3779 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003780 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003781 if (isa<LoadInst>(User) ||
3782 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3783 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3784 User->getParent(), GEPI,
3785 Ptr, PtrOffset);
3786 } else {
3787 // If this use is not foldable into the addressing mode, use a version
3788 // emitted in the GEP block.
3789 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3790 Ptr, PtrOffset);
3791 }
3792
Chris Lattnerf0df8822006-05-06 09:10:37 +00003793 if (GEPI->getType() != RepPtr->getType()) {
3794 BasicBlock::iterator IP = NewVal;
3795 ++IP;
Reid Spencer3da59db2006-11-27 01:05:10 +00003796 // NewVal must be a GEP which must be pointer type, so BitCast
3797 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003798 }
Chris Lattner90323642006-05-05 21:17:49 +00003799 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003800 }
3801}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003802
Chris Lattner90323642006-05-05 21:17:49 +00003803
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003804/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3805/// selection, we want to be a bit careful about some things. In particular, if
3806/// we have a GEP instruction that is used in a different block than it is
3807/// defined, the addressing expression of the GEP cannot be folded into loads or
3808/// stores that use it. In this case, decompose the GEP and move constant
3809/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003810static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003811 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003812 // If this GEP is only used inside the block it is defined in, there is no
3813 // need to rewrite it.
3814 bool isUsedOutsideDefBB = false;
3815 BasicBlock *DefBB = GEPI->getParent();
3816 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3817 UI != E; ++UI) {
3818 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3819 isUsedOutsideDefBB = true;
3820 break;
3821 }
3822 }
Chris Lattner90323642006-05-05 21:17:49 +00003823 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003824
3825 // If this GEP has no non-zero constant indices, there is nothing we can do,
3826 // ignore it.
3827 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003828 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003829 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3830 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003831 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003832 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003833 hasConstantIndex = true;
3834 break;
3835 }
Chris Lattner90323642006-05-05 21:17:49 +00003836 } else {
3837 hasVariableIndex = true;
3838 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003839 }
Chris Lattner90323642006-05-05 21:17:49 +00003840
3841 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3842 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003843 /// The GEP operand must be a pointer, so must its result -> BitCast
3844 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner90323642006-05-05 21:17:49 +00003845 GEPI->getName(), GEPI);
3846 GEPI->replaceAllUsesWith(NC);
3847 GEPI->eraseFromParent();
3848 return true;
3849 }
3850
Chris Lattner3802c252005-12-11 09:05:13 +00003851 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003852 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3853 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003854
3855 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3856 // constant offset (which we now know is non-zero) and deal with it later.
3857 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003858 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer3da59db2006-11-27 01:05:10 +00003859 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003860 const Type *Ty = GEPI->getOperand(0)->getType();
3861
3862 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3863 E = GEPI->op_end(); OI != E; ++OI) {
3864 Value *Idx = *OI;
3865 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003866 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003867 if (Field)
Chris Lattnerb1919e22007-02-10 19:55:17 +00003868 ConstantOffset += TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003869 Ty = StTy->getElementType(Field);
3870 } else {
3871 Ty = cast<SequentialType>(Ty)->getElementType();
3872
3873 // Handle constant subscripts.
3874 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003875 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00003876 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003877 continue;
3878 }
3879
3880 // Ptr = Ptr + Idx * ElementSize;
3881
3882 // Cast Idx to UIntPtrTy if needed.
Reid Spencer7b06bd52006-12-13 00:50:17 +00003883 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003884
Owen Andersona69571c2006-05-03 01:29:57 +00003885 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003886 // Mask off bits that should not be set.
3887 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003888 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003889
3890 // Multiply by the element size and add to the base.
3891 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3892 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3893 }
3894 }
3895
3896 // Make sure that the offset fits in uintptr_t.
3897 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003898 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003899
3900 // Okay, we have now emitted all of the variable index parts to the BB that
3901 // the GEP is defined in. Loop over all of the using instructions, inserting
3902 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003903 // instruction to use the newly computed value, making GEPI dead. When the
3904 // user is a load or store instruction address, we emit the add into the user
3905 // block, otherwise we use a canonical version right next to the gep (these
3906 // won't be foldable as addresses, so we might as well share the computation).
3907
Chris Lattnerf0df8822006-05-06 09:10:37 +00003908 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003909 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003910
3911 // Finally, the GEP is dead, remove it.
3912 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003913
3914 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003915}
3916
Chris Lattnerbad7f482006-10-28 19:22:10 +00003917
3918/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3919/// successor if it will improve codegen. We only do this if the successor has
3920/// phi nodes (otherwise critical edges are ok). If there is already another
3921/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3922/// instead of introducing a new block.
3923static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3924 BasicBlock *TIBB = TI->getParent();
3925 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3926 assert(isa<PHINode>(Dest->begin()) &&
3927 "This should only be called if Dest has a PHI!");
3928
3929 /// TIPHIValues - This array is lazily computed to determine the values of
3930 /// PHIs in Dest that TI would provide.
3931 std::vector<Value*> TIPHIValues;
3932
3933 // Check to see if Dest has any blocks that can be used as a split edge for
3934 // this terminator.
3935 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3936 BasicBlock *Pred = *PI;
3937 // To be usable, the pred has to end with an uncond branch to the dest.
3938 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3939 if (!PredBr || !PredBr->isUnconditional() ||
3940 // Must be empty other than the branch.
3941 &Pred->front() != PredBr)
3942 continue;
3943
3944 // Finally, since we know that Dest has phi nodes in it, we have to make
3945 // sure that jumping to Pred will have the same affect as going to Dest in
3946 // terms of PHI values.
3947 PHINode *PN;
3948 unsigned PHINo = 0;
3949 bool FoundMatch = true;
3950 for (BasicBlock::iterator I = Dest->begin();
3951 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3952 if (PHINo == TIPHIValues.size())
3953 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3954
3955 // If the PHI entry doesn't work, we can't use this pred.
3956 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3957 FoundMatch = false;
3958 break;
3959 }
3960 }
3961
3962 // If we found a workable predecessor, change TI to branch to Succ.
3963 if (FoundMatch) {
3964 Dest->removePredecessor(TIBB);
3965 TI->setSuccessor(SuccNum, Pred);
3966 return;
3967 }
3968 }
3969
3970 SplitCriticalEdge(TI, SuccNum, P, true);
3971}
3972
3973
Chris Lattner1c08c712005-01-07 07:47:53 +00003974bool SelectionDAGISel::runOnFunction(Function &Fn) {
3975 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3976 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00003977 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00003978
Chris Lattner47e32e62006-10-28 17:04:37 +00003979 // First, split all critical edges.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003980 //
Chris Lattner7e598092006-05-05 01:04:50 +00003981 // In this pass we also look for GEP and cast instructions that are used
3982 // across basic blocks and rewrite them to improve basic-block-at-a-time
3983 // selection.
3984 //
Chris Lattner90323642006-05-05 21:17:49 +00003985 bool MadeChange = true;
3986 while (MadeChange) {
3987 MadeChange = false;
Evan Cheng15699fc2007-02-10 01:08:18 +00003988 for (Function::iterator FNI = Fn.begin(), E = Fn.end(); FNI != E; ++FNI) {
Chris Lattnerbad7f482006-10-28 19:22:10 +00003989 // Split all critical edges where the dest block has a PHI.
Evan Cheng15699fc2007-02-10 01:08:18 +00003990 TerminatorInst *BBTI = FNI->getTerminator();
Chris Lattner47e32e62006-10-28 17:04:37 +00003991 if (BBTI->getNumSuccessors() > 1) {
3992 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbad7f482006-10-28 19:22:10 +00003993 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3994 isCriticalEdge(BBTI, i, true))
3995 SplitEdgeNicely(BBTI, i, this);
Chris Lattner47e32e62006-10-28 17:04:37 +00003996 }
3997
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003998
Evan Cheng15699fc2007-02-10 01:08:18 +00003999 for (BasicBlock::iterator BBI = FNI->begin(), E = FNI->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00004000 Instruction *I = BBI++;
Chris Lattner3f7927c2006-11-29 01:12:32 +00004001
4002 if (CallInst *CI = dyn_cast<CallInst>(I)) {
4003 // If we found an inline asm expession, and if the target knows how to
4004 // lower it to normal LLVM code, do so now.
4005 if (isa<InlineAsm>(CI->getCalledValue()))
4006 if (const TargetAsmInfo *TAI =
4007 TLI.getTargetMachine().getTargetAsmInfo()) {
4008 if (TAI->ExpandInlineAsm(CI))
Evan Cheng15699fc2007-02-10 01:08:18 +00004009 BBI = FNI->begin();
Chris Lattner3f7927c2006-11-29 01:12:32 +00004010 }
4011 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00004012 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00004013 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00004014 // If the source of the cast is a constant, then this should have
4015 // already been constant folded. The only reason NOT to constant fold
4016 // it is if something (e.g. LSR) was careful to place the constant
4017 // evaluation in a block other than then one that uses it (e.g. to hoist
4018 // the address of globals out of a loop). If this is the case, we don't
4019 // want to forward-subst the cast.
4020 if (isa<Constant>(CI->getOperand(0)))
4021 continue;
4022
Chris Lattner7e598092006-05-05 01:04:50 +00004023 // If this is a noop copy, sink it into user blocks to reduce the number
4024 // of virtual registers that must be created and coallesced.
4025 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
4026 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
4027
4028 // This is an fp<->int conversion?
4029 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
4030 continue;
4031
4032 // If this is an extension, it will be a zero or sign extension, which
4033 // isn't a noop.
4034 if (SrcVT < DstVT) continue;
4035
4036 // If these values will be promoted, find out what they will be promoted
4037 // to. This helps us consider truncates on PPC as noop copies when they
4038 // are.
4039 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
4040 SrcVT = TLI.getTypeToTransformTo(SrcVT);
4041 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
4042 DstVT = TLI.getTypeToTransformTo(DstVT);
4043
4044 // If, after promotion, these are the same types, this is a noop copy.
4045 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00004046 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00004047 }
4048 }
Chris Lattner36b708f2005-08-18 17:35:14 +00004049 }
Chris Lattner90323642006-05-05 21:17:49 +00004050 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00004051
Chris Lattner1c08c712005-01-07 07:47:53 +00004052 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4053
4054 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4055 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004056
Evan Chengad2070c2007-02-10 02:43:39 +00004057 // Add function live-ins to entry block live-in set.
4058 BasicBlock *EntryBB = &Fn.getEntryBlock();
4059 BB = FuncInfo.MBBMap[EntryBB];
4060 if (!MF.livein_empty())
4061 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4062 E = MF.livein_end(); I != E; ++I)
4063 BB->addLiveIn(I->first);
4064
Chris Lattner1c08c712005-01-07 07:47:53 +00004065 return true;
4066}
4067
Chris Lattner571e4342006-10-27 21:36:01 +00004068SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4069 unsigned Reg) {
4070 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004071 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004072 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004073 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004074
4075 // If this type is not legal, we must make sure to not create an invalid
4076 // register use.
4077 MVT::ValueType SrcVT = Op.getValueType();
4078 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004079 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00004080 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004081 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00004082 // Handle copies from generic vectors to registers.
4083 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +00004084 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner70c2a612006-03-31 02:06:56 +00004085 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004086
Chris Lattner70c2a612006-03-31 02:06:56 +00004087 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4088 // MVT::Vector type.
4089 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4090 DAG.getConstant(NE, MVT::i32),
4091 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00004092
Chris Lattner70c2a612006-03-31 02:06:56 +00004093 // Loop over all of the elements of the resultant vector,
4094 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4095 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004096 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00004097 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00004098 for (unsigned i = 0; i != NE; ++i) {
4099 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004100 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004101 if (PTyElementVT == PTyLegalElementVT) {
4102 // Elements are legal.
4103 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4104 } else if (PTyLegalElementVT > PTyElementVT) {
4105 // Elements are promoted.
4106 if (MVT::isFloatingPoint(PTyLegalElementVT))
4107 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4108 else
4109 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4110 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4111 } else {
4112 // Elements are expanded.
4113 // The src value is expanded into multiple registers.
4114 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004115 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004116 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004117 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004118 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4119 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4120 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00004121 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004122 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4123 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00004124 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004125 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00004126 if (MVT::isFloatingPoint(SrcVT))
4127 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4128 else
Chris Lattnerfab08872005-09-02 00:19:37 +00004129 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00004130 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004131 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00004132 DestVT = TLI.getTypeToExpandTo(SrcVT);
4133 unsigned NumVals = TLI.getNumElements(SrcVT);
4134 if (NumVals == 1)
4135 return DAG.getCopyToReg(getRoot(), Reg,
4136 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4137 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004138 // The src value is expanded into multiple registers.
4139 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004140 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004141 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004142 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00004143 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004144 return DAG.getCopyToReg(Op, Reg+1, Hi);
4145 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004146}
4147
Chris Lattner068a81e2005-01-17 17:15:02 +00004148void SelectionDAGISel::
Evan Cheng15699fc2007-02-10 01:08:18 +00004149LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner068a81e2005-01-17 17:15:02 +00004150 std::vector<SDOperand> &UnorderedChains) {
4151 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004152 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004153 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004154 SDOperand OldRoot = SDL.DAG.getRoot();
4155 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004156
Chris Lattnerbf209482005-10-30 19:42:35 +00004157 unsigned a = 0;
4158 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4159 AI != E; ++AI, ++a)
4160 if (!AI->use_empty()) {
4161 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004162
Chris Lattnerbf209482005-10-30 19:42:35 +00004163 // If this argument is live outside of the entry block, insert a copy from
4164 // whereever we got it to the vreg that other BB's will reference it as.
4165 if (FuncInfo.ValueMap.count(AI)) {
4166 SDOperand Copy =
Chris Lattner571e4342006-10-27 21:36:01 +00004167 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattnerbf209482005-10-30 19:42:35 +00004168 UnorderedChains.push_back(Copy);
4169 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004170 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004171
Chris Lattnerbf209482005-10-30 19:42:35 +00004172 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004173 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004174 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004175}
4176
Chris Lattner1c08c712005-01-07 07:47:53 +00004177void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4178 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004179 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00004180 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004181
4182 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00004183
Chris Lattnerbf209482005-10-30 19:42:35 +00004184 // Lower any arguments needed in this block if this is the entry block.
4185 if (LLVMBB == &LLVMBB->getParent()->front())
4186 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00004187
4188 BB = FuncInfo.MBBMap[LLVMBB];
4189 SDL.setCurrentBasicBlock(BB);
4190
4191 // Lower all of the non-terminator instructions.
4192 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4193 I != E; ++I)
4194 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00004195
Chris Lattner1c08c712005-01-07 07:47:53 +00004196 // Ensure that all instructions which are used outside of their defining
4197 // blocks are available as virtual registers.
4198 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00004199 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004200 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004201 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00004202 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004203 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004204 }
4205
4206 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4207 // ensure constants are generated when needed. Remember the virtual registers
4208 // that need to be added to the Machine PHI nodes as input. We cannot just
4209 // directly add them, because expansion might result in multiple MBB's for one
4210 // BB. As such, the start of the BB might correspond to a different MBB than
4211 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004212 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004213 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004214
4215 // Emit constants only once even if used by multiple PHI nodes.
4216 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004217
Chris Lattner8c494ab2006-10-27 23:50:33 +00004218 // Vector bool would be better, but vector<bool> is really slow.
4219 std::vector<unsigned char> SuccsHandled;
4220 if (TI->getNumSuccessors())
4221 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4222
Chris Lattner1c08c712005-01-07 07:47:53 +00004223 // Check successor nodes PHI nodes that expect a constant to be available from
4224 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004225 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4226 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004227 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004228 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004229
Chris Lattner8c494ab2006-10-27 23:50:33 +00004230 // If this terminator has multiple identical successors (common for
4231 // switches), only handle each succ once.
4232 unsigned SuccMBBNo = SuccMBB->getNumber();
4233 if (SuccsHandled[SuccMBBNo]) continue;
4234 SuccsHandled[SuccMBBNo] = true;
4235
4236 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004237 PHINode *PN;
4238
4239 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4240 // nodes and Machine PHI nodes, but the incoming operands have not been
4241 // emitted yet.
4242 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004243 (PN = dyn_cast<PHINode>(I)); ++I) {
4244 // Ignore dead phi's.
4245 if (PN->use_empty()) continue;
4246
4247 unsigned Reg;
4248 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004249
Chris Lattner8c494ab2006-10-27 23:50:33 +00004250 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4251 unsigned &RegOut = ConstantsOut[C];
4252 if (RegOut == 0) {
4253 RegOut = FuncInfo.CreateRegForValue(C);
4254 UnorderedChains.push_back(
4255 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004256 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004257 Reg = RegOut;
4258 } else {
4259 Reg = FuncInfo.ValueMap[PHIOp];
4260 if (Reg == 0) {
4261 assert(isa<AllocaInst>(PHIOp) &&
4262 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4263 "Didn't codegen value into a register!??");
4264 Reg = FuncInfo.CreateRegForValue(PHIOp);
4265 UnorderedChains.push_back(
4266 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004267 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004268 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004269
4270 // Remember that this register needs to added to the machine PHI node as
4271 // the input for this MBB.
4272 MVT::ValueType VT = TLI.getValueType(PN->getType());
4273 unsigned NumElements;
4274 if (VT != MVT::Vector)
4275 NumElements = TLI.getNumElements(VT);
4276 else {
4277 MVT::ValueType VT1,VT2;
4278 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +00004279 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +00004280 VT1, VT2);
4281 }
4282 for (unsigned i = 0, e = NumElements; i != e; ++i)
4283 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4284 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004285 }
4286 ConstantsOut.clear();
4287
Chris Lattnerddb870b2005-01-13 17:59:43 +00004288 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004289 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004290 SDOperand Root = SDL.getRoot();
4291 if (Root.getOpcode() != ISD::EntryToken) {
4292 unsigned i = 0, e = UnorderedChains.size();
4293 for (; i != e; ++i) {
4294 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4295 if (UnorderedChains[i].Val->getOperand(0) == Root)
4296 break; // Don't add the root if we already indirectly depend on it.
4297 }
4298
4299 if (i == e)
4300 UnorderedChains.push_back(Root);
4301 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004302 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4303 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004304 }
4305
Chris Lattner1c08c712005-01-07 07:47:53 +00004306 // Lower the terminator after the copies are emitted.
4307 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004308
Nate Begemanf15485a2006-03-27 01:32:24 +00004309 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004310 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004311 SwitchCases.clear();
4312 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00004313 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00004314
Chris Lattnera651cf62005-01-17 19:43:36 +00004315 // Make sure the root of the DAG is up-to-date.
4316 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004317}
4318
Nate Begemanf15485a2006-03-27 01:32:24 +00004319void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004320 // Get alias analysis for load/store combining.
4321 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4322
Chris Lattneraf21d552005-10-10 16:47:10 +00004323 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004324 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004325
Bill Wendling832171c2006-12-07 20:04:42 +00004326 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004327 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004328
Chris Lattner1c08c712005-01-07 07:47:53 +00004329 // Second step, hack on the DAG until it only uses operations and types that
4330 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004331 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004332
Bill Wendling832171c2006-12-07 20:04:42 +00004333 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004334 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004335
Chris Lattneraf21d552005-10-10 16:47:10 +00004336 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004337 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004338
Evan Chenga9c20912006-01-21 02:32:06 +00004339 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004340
Chris Lattnera33ef482005-03-30 01:10:47 +00004341 // Third, instruction select all of the operations to machine code, adding the
4342 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004343 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004344
Bill Wendling832171c2006-12-07 20:04:42 +00004345 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004346 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004347}
Chris Lattner1c08c712005-01-07 07:47:53 +00004348
Nate Begemanf15485a2006-03-27 01:32:24 +00004349void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4350 FunctionLoweringInfo &FuncInfo) {
4351 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4352 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004353 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004354 CurDAG = &DAG;
4355
4356 // First step, lower LLVM code to some DAG. This DAG may use operations and
4357 // types that are not supported by the target.
4358 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4359
4360 // Second step, emit the lowered DAG as machine code.
4361 CodeGenAndEmitDAG(DAG);
4362 }
4363
Chris Lattnera33ef482005-03-30 01:10:47 +00004364 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004365 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00004366 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004367 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4368 MachineInstr *PHI = PHINodesToUpdate[i].first;
4369 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4370 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004371 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004372 PHI->addMachineBasicBlockOperand(BB);
4373 }
4374 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004375 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004376
Nate Begeman9453eea2006-04-23 06:26:20 +00004377 // If the JumpTable record is filled in, then we need to emit a jump table.
4378 // Updating the PHI nodes is tricky in this case, since we need to determine
4379 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00004380 if (JT.Reg) {
4381 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004382 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begeman37efe672006-04-22 18:53:45 +00004383 CurDAG = &SDAG;
4384 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00004385 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00004386 // Set the current basic block to the mbb we wish to insert the code into
4387 BB = JT.MBB;
4388 SDL.setCurrentBasicBlock(BB);
4389 // Emit the code
4390 SDL.visitJumpTable(JT);
4391 SDAG.setRoot(SDL.getRoot());
4392 CodeGenAndEmitDAG(SDAG);
4393 // Update PHI Nodes
4394 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4395 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4396 MachineBasicBlock *PHIBB = PHI->getParent();
4397 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4398 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00004399 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004400 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004401 PHI->addMachineBasicBlockOperand(RangeBB);
4402 }
4403 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004404 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004405 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004406 }
4407 }
4408 return;
4409 }
4410
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004411 // If the switch block involved a branch to one of the actual successors, we
4412 // need to update PHI nodes in that block.
4413 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4414 MachineInstr *PHI = PHINodesToUpdate[i].first;
4415 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4416 "This is not a machine PHI node that we are updating!");
4417 if (BB->isSuccessor(PHI->getParent())) {
4418 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4419 PHI->addMachineBasicBlockOperand(BB);
4420 }
4421 }
4422
Nate Begemanf15485a2006-03-27 01:32:24 +00004423 // If we generated any switch lowering information, build and codegen any
4424 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004425 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004426 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004427 CurDAG = &SDAG;
4428 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004429
Nate Begemanf15485a2006-03-27 01:32:24 +00004430 // Set the current basic block to the mbb we wish to insert the code into
4431 BB = SwitchCases[i].ThisBB;
4432 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004433
Nate Begemanf15485a2006-03-27 01:32:24 +00004434 // Emit the code
4435 SDL.visitSwitchCase(SwitchCases[i]);
4436 SDAG.setRoot(SDL.getRoot());
4437 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004438
4439 // Handle any PHI nodes in successors of this chunk, as if we were coming
4440 // from the original BB before switch expansion. Note that PHI nodes can
4441 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4442 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004443 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004444 for (MachineBasicBlock::iterator Phi = BB->begin();
4445 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4446 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4447 for (unsigned pn = 0; ; ++pn) {
4448 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4449 if (PHINodesToUpdate[pn].first == Phi) {
4450 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4451 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4452 break;
4453 }
4454 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004455 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004456
4457 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004458 if (BB == SwitchCases[i].FalseBB)
4459 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004460
4461 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004462 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004463 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004464 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004465 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004466 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004467}
Evan Chenga9c20912006-01-21 02:32:06 +00004468
Jim Laskey13ec7022006-08-01 14:21:23 +00004469
Evan Chenga9c20912006-01-21 02:32:06 +00004470//===----------------------------------------------------------------------===//
4471/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4472/// target node in the graph.
4473void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4474 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004475
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004476 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004477
4478 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004479 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004480 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004481 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004482
Jim Laskey9ff542f2006-08-01 18:29:48 +00004483 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004484 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004485 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004486}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004487
Chris Lattner03fc53c2006-03-06 00:22:00 +00004488
Jim Laskey9ff542f2006-08-01 18:29:48 +00004489HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4490 return new HazardRecognizer();
4491}
4492
Chris Lattner75548062006-10-11 03:58:02 +00004493//===----------------------------------------------------------------------===//
4494// Helper functions used by the generated instruction selector.
4495//===----------------------------------------------------------------------===//
4496// Calls to these methods are generated by tblgen.
4497
4498/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4499/// the dag combiner simplified the 255, we still want to match. RHS is the
4500/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4501/// specified in the .td file (e.g. 255).
4502bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4503 int64_t DesiredMaskS) {
4504 uint64_t ActualMask = RHS->getValue();
4505 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4506
4507 // If the actual mask exactly matches, success!
4508 if (ActualMask == DesiredMask)
4509 return true;
4510
4511 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4512 if (ActualMask & ~DesiredMask)
4513 return false;
4514
4515 // Otherwise, the DAG Combiner may have proven that the value coming in is
4516 // either already zero or is not demanded. Check for known zero input bits.
4517 uint64_t NeededMask = DesiredMask & ~ActualMask;
4518 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4519 return true;
4520
4521 // TODO: check to see if missing bits are just not demanded.
4522
4523 // Otherwise, this pattern doesn't match.
4524 return false;
4525}
4526
4527/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4528/// the dag combiner simplified the 255, we still want to match. RHS is the
4529/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4530/// specified in the .td file (e.g. 255).
4531bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4532 int64_t DesiredMaskS) {
4533 uint64_t ActualMask = RHS->getValue();
4534 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4535
4536 // If the actual mask exactly matches, success!
4537 if (ActualMask == DesiredMask)
4538 return true;
4539
4540 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4541 if (ActualMask & ~DesiredMask)
4542 return false;
4543
4544 // Otherwise, the DAG Combiner may have proven that the value coming in is
4545 // either already zero or is not demanded. Check for known zero input bits.
4546 uint64_t NeededMask = DesiredMask & ~ActualMask;
4547
4548 uint64_t KnownZero, KnownOne;
4549 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4550
4551 // If all the missing bits in the or are already known to be set, match!
4552 if ((NeededMask & KnownOne) == NeededMask)
4553 return true;
4554
4555 // TODO: check to see if missing bits are just not demanded.
4556
4557 // Otherwise, this pattern doesn't match.
4558 return false;
4559}
4560
Jim Laskey9ff542f2006-08-01 18:29:48 +00004561
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004562/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4563/// by tblgen. Others should not call it.
4564void SelectionDAGISel::
4565SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4566 std::vector<SDOperand> InOps;
4567 std::swap(InOps, Ops);
4568
4569 Ops.push_back(InOps[0]); // input chain.
4570 Ops.push_back(InOps[1]); // input asm string.
4571
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004572 unsigned i = 2, e = InOps.size();
4573 if (InOps[e-1].getValueType() == MVT::Flag)
4574 --e; // Don't process a flag operand if it is here.
4575
4576 while (i != e) {
4577 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4578 if ((Flags & 7) != 4 /*MEM*/) {
4579 // Just skip over this operand, copying the operands verbatim.
4580 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4581 i += (Flags >> 3) + 1;
4582 } else {
4583 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4584 // Otherwise, this is a memory operand. Ask the target to select it.
4585 std::vector<SDOperand> SelOps;
4586 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004587 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004588 exit(1);
4589 }
4590
4591 // Add this to the output node.
Chris Lattner36d43962006-12-16 21:14:48 +00004592 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4593 MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004594 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4595 i += 2;
4596 }
4597 }
4598
4599 // Add the flag input back if present.
4600 if (e != InOps.size())
4601 Ops.push_back(InOps.back());
4602}