blob: c18b5bc274ce23f23b6d6a6b088fffee4a329c08 [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 Laskeyb2efb852006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.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 Lattner1c08c712005-01-07 07:47:53 +000036#include "llvm/Target/TargetData.h"
37#include "llvm/Target/TargetFrameInfo.h"
38#include "llvm/Target/TargetInstrInfo.h"
39#include "llvm/Target/TargetLowering.h"
40#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000041#include "llvm/Target/TargetOptions.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000042#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000043#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000044#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000045#include "llvm/Support/Compiler.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000046#include <iostream>
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.
174 std::map<const Value*, unsigned> ValueMap;
175
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 =
Owen Andersona69571c2006-05-03 01:29:57 +0000247 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(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 // If the alignment of the value is smaller than the size of the
251 // value, and if the size of the value is particularly small
252 // (<= 8 bytes), round up to the size of the value for potentially
253 // better performance.
Chris Lattnera8217e32005-05-13 23:14:17 +0000254 //
255 // FIXME: This could be made better with a preferred alignment hook in
256 // TargetData. It serves primarily to 8-byte align doubles for X86.
257 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencerb83eb642006-10-20 07:07:24 +0000258 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000259 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000260 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000261 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000262 }
263
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000264 for (; BB != EB; ++BB)
265 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000266 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
267 if (!isa<AllocaInst>(I) ||
268 !StaticAllocaMap.count(cast<AllocaInst>(I)))
269 InitializeRegForValue(I);
270
271 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
272 // also creates the initial PHI MachineInstrs, though none of the input
273 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000274 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000275 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
276 MBBMap[BB] = MBB;
277 MF.getBasicBlockList().push_back(MBB);
278
279 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
280 // appropriate.
281 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000282 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
283 if (PN->use_empty()) continue;
284
285 MVT::ValueType VT = TLI.getValueType(PN->getType());
286 unsigned NumElements;
287 if (VT != MVT::Vector)
288 NumElements = TLI.getNumElements(VT);
289 else {
290 MVT::ValueType VT1,VT2;
291 NumElements =
292 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
293 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000294 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000295 unsigned PHIReg = ValueMap[PN];
296 assert(PHIReg && "PHI node does not have an assigned virtual register!");
297 for (unsigned i = 0; i != NumElements; ++i)
298 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
299 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000300 }
301}
302
Chris Lattner3c384492006-03-16 19:51:18 +0000303/// CreateRegForValue - Allocate the appropriate number of virtual registers of
304/// the correctly promoted or expanded types. Assign these registers
305/// consecutive vreg numbers and return the first assigned number.
306unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
307 MVT::ValueType VT = TLI.getValueType(V->getType());
308
309 // The number of multiples of registers that we need, to, e.g., split up
310 // a <2 x int64> -> 4 x i32 registers.
311 unsigned NumVectorRegs = 1;
312
313 // If this is a packed type, figure out what type it will decompose into
314 // and how many of the elements it will use.
315 if (VT == MVT::Vector) {
316 const PackedType *PTy = cast<PackedType>(V->getType());
317 unsigned NumElts = PTy->getNumElements();
318 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
319
320 // Divide the input until we get to a supported size. This will always
321 // end with a scalar if the target doesn't support vectors.
322 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
323 NumElts >>= 1;
324 NumVectorRegs <<= 1;
325 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000326 if (NumElts == 1)
327 VT = EltTy;
328 else
329 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000330 }
331
332 // The common case is that we will only create one register for this
333 // value. If we have that case, create and return the virtual register.
334 unsigned NV = TLI.getNumElements(VT);
335 if (NV == 1) {
336 // If we are promoting this value, pick the next largest supported type.
337 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
338 unsigned Reg = MakeReg(PromotedType);
339 // If this is a vector of supported or promoted types (e.g. 4 x i16),
340 // create all of the registers.
341 for (unsigned i = 1; i != NumVectorRegs; ++i)
342 MakeReg(PromotedType);
343 return Reg;
344 }
345
346 // If this value is represented with multiple target registers, make sure
347 // to create enough consecutive registers of the right (smaller) type.
348 unsigned NT = VT-1; // Find the type to use.
349 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
350 --NT;
351
352 unsigned R = MakeReg((MVT::ValueType)NT);
353 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
354 MakeReg((MVT::ValueType)NT);
355 return R;
356}
Chris Lattner1c08c712005-01-07 07:47:53 +0000357
358//===----------------------------------------------------------------------===//
359/// SelectionDAGLowering - This is the common target-independent lowering
360/// implementation that is parameterized by a TargetLowering object.
361/// Also, targets can overload any lowering method.
362///
363namespace llvm {
364class SelectionDAGLowering {
365 MachineBasicBlock *CurMBB;
366
367 std::map<const Value*, SDOperand> NodeMap;
368
Chris Lattnerd3948112005-01-17 22:19:26 +0000369 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
370 /// them up and then emit token factor nodes when possible. This allows us to
371 /// get simple disambiguation between loads without worrying about alias
372 /// analysis.
373 std::vector<SDOperand> PendingLoads;
374
Nate Begemanf15485a2006-03-27 01:32:24 +0000375 /// Case - A pair of values to record the Value for a switch case, and the
376 /// case's target basic block.
377 typedef std::pair<Constant*, MachineBasicBlock*> Case;
378 typedef std::vector<Case>::iterator CaseItr;
379 typedef std::pair<CaseItr, CaseItr> CaseRange;
380
381 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
382 /// of conditional branches.
383 struct CaseRec {
384 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
385 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
386
387 /// CaseBB - The MBB in which to emit the compare and branch
388 MachineBasicBlock *CaseBB;
389 /// LT, GE - If nonzero, we know the current case value must be less-than or
390 /// greater-than-or-equal-to these Constants.
391 Constant *LT;
392 Constant *GE;
393 /// Range - A pair of iterators representing the range of case values to be
394 /// processed at this point in the binary search tree.
395 CaseRange Range;
396 };
397
398 /// The comparison function for sorting Case values.
399 struct CaseCmp {
400 bool operator () (const Case& C1, const Case& C2) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000401 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
402 if (I1->getType()->isUnsigned())
403 return I1->getZExtValue() <
404 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000405
Reid Spencerb83eb642006-10-20 07:07:24 +0000406 return cast<const ConstantInt>(C1.first)->getSExtValue() <
407 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000408 }
409 };
410
Chris Lattner1c08c712005-01-07 07:47:53 +0000411public:
412 // TLI - This is information that describes the available target features we
413 // need for lowering. This indicates when operations are unavailable,
414 // implemented with a libcall, etc.
415 TargetLowering &TLI;
416 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000417 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000418
Nate Begemanf15485a2006-03-27 01:32:24 +0000419 /// SwitchCases - Vector of CaseBlock structures used to communicate
420 /// SwitchInst code generation information.
421 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000422 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000423
Chris Lattner1c08c712005-01-07 07:47:53 +0000424 /// FuncInfo - Information about the function as a whole.
425 ///
426 FunctionLoweringInfo &FuncInfo;
427
428 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000429 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000430 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000431 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000432 }
433
Chris Lattnera651cf62005-01-17 19:43:36 +0000434 /// getRoot - Return the current virtual root of the Selection DAG.
435 ///
436 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000437 if (PendingLoads.empty())
438 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000439
Chris Lattnerd3948112005-01-17 22:19:26 +0000440 if (PendingLoads.size() == 1) {
441 SDOperand Root = PendingLoads[0];
442 DAG.setRoot(Root);
443 PendingLoads.clear();
444 return Root;
445 }
446
447 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000448 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
449 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000450 PendingLoads.clear();
451 DAG.setRoot(Root);
452 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000453 }
454
Chris Lattner571e4342006-10-27 21:36:01 +0000455 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
456
Chris Lattner1c08c712005-01-07 07:47:53 +0000457 void visit(Instruction &I) { visit(I.getOpcode(), I); }
458
459 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000460 // Note: this doesn't use InstVisitor, because it has to work with
461 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000462 switch (Opcode) {
463 default: assert(0 && "Unknown instruction type encountered!");
464 abort();
465 // Build the switch statement using the Instruction.def file.
466#define HANDLE_INST(NUM, OPCODE, CLASS) \
467 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
468#include "llvm/Instruction.def"
469 }
470 }
471
472 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
473
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000474 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000475 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000476 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000477
478 SDOperand getIntPtrConstant(uint64_t Val) {
479 return DAG.getConstant(Val, TLI.getPointerTy());
480 }
481
Chris Lattner199862b2006-03-16 19:57:50 +0000482 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000483
484 const SDOperand &setValue(const Value *V, SDOperand NewN) {
485 SDOperand &N = NodeMap[V];
486 assert(N.Val == 0 && "Already set a value for this node!");
487 return N = NewN;
488 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000489
Chris Lattner864635a2006-02-22 22:37:12 +0000490 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
491 MVT::ValueType VT,
492 bool OutReg, bool InReg,
493 std::set<unsigned> &OutputRegs,
494 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000495
Chris Lattner571e4342006-10-27 21:36:01 +0000496 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
497 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
498 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000499 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000500 void ExportFromCurrentBlock(Value *V);
501
Chris Lattner1c08c712005-01-07 07:47:53 +0000502 // Terminator instructions.
503 void visitRet(ReturnInst &I);
504 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000505 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000506 void visitUnreachable(UnreachableInst &I) { /* noop */ }
507
Nate Begemanf15485a2006-03-27 01:32:24 +0000508 // Helper for visitSwitch
509 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000510 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000511
Chris Lattner1c08c712005-01-07 07:47:53 +0000512 // These all get lowered before this pass.
Chris Lattner1c08c712005-01-07 07:47:53 +0000513 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
514 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
515
Reid Spencer1628cec2006-10-26 06:15:43 +0000516 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
517 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000518 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000519 void visitAdd(User &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +0000520 if (I.getType()->isFloatingPoint())
521 visitFPBinary(I, ISD::FADD, ISD::VADD);
522 else
523 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000524 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000525 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000526 void visitMul(User &I) {
527 if (I.getType()->isFloatingPoint())
528 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
529 else
530 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000531 }
Reid Spencer0a783f72006-11-02 01:53:59 +0000532 void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
533 void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
534 void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
Reid Spencer1628cec2006-10-26 06:15:43 +0000535 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
536 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
Reid Spencer0a783f72006-11-02 01:53:59 +0000537 void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
Reid Spencer1628cec2006-10-26 06:15:43 +0000538 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
539 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
540 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000541 void visitShl(User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000542 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
543 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000544 void visitICmp(User &I);
545 void visitFCmp(User &I);
Evan Chengf6f95812006-05-23 06:40:47 +0000546 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
547 ISD::CondCode FPOpc);
548 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
549 ISD::SETOEQ); }
550 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
551 ISD::SETUNE); }
552 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
553 ISD::SETOLE); }
554 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
555 ISD::SETOGE); }
556 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
557 ISD::SETOLT); }
558 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
559 ISD::SETOGT); }
Reid Spencer3da59db2006-11-27 01:05:10 +0000560 // Visit the conversion instructions
561 void visitTrunc(User &I);
562 void visitZExt(User &I);
563 void visitSExt(User &I);
564 void visitFPTrunc(User &I);
565 void visitFPExt(User &I);
566 void visitFPToUI(User &I);
567 void visitFPToSI(User &I);
568 void visitUIToFP(User &I);
569 void visitSIToFP(User &I);
570 void visitPtrToInt(User &I);
571 void visitIntToPtr(User &I);
572 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000573
Chris Lattner2bbd8102006-03-29 00:11:43 +0000574 void visitExtractElement(User &I);
575 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000576 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000577
Chris Lattner1c08c712005-01-07 07:47:53 +0000578 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000579 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000580
581 void visitMalloc(MallocInst &I);
582 void visitFree(FreeInst &I);
583 void visitAlloca(AllocaInst &I);
584 void visitLoad(LoadInst &I);
585 void visitStore(StoreInst &I);
586 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
587 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000588 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000589 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000590 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000591
Chris Lattner1c08c712005-01-07 07:47:53 +0000592 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000593 void visitVAArg(VAArgInst &I);
594 void visitVAEnd(CallInst &I);
595 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000596 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000597
Chris Lattner7041ee32005-01-11 05:56:49 +0000598 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000599
600 void visitUserOp1(Instruction &I) {
601 assert(0 && "UserOp1 should not exist at instruction selection time!");
602 abort();
603 }
604 void visitUserOp2(Instruction &I) {
605 assert(0 && "UserOp2 should not exist at instruction selection time!");
606 abort();
607 }
608};
609} // end namespace llvm
610
Chris Lattner199862b2006-03-16 19:57:50 +0000611SDOperand SelectionDAGLowering::getValue(const Value *V) {
612 SDOperand &N = NodeMap[V];
613 if (N.Val) return N;
614
615 const Type *VTy = V->getType();
616 MVT::ValueType VT = TLI.getValueType(VTy);
617 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
618 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
619 visit(CE->getOpcode(), *CE);
620 assert(N.Val && "visit didn't populate the ValueMap!");
621 return N;
622 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
623 return N = DAG.getGlobalAddress(GV, VT);
624 } else if (isa<ConstantPointerNull>(C)) {
625 return N = DAG.getConstant(0, TLI.getPointerTy());
626 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000627 if (!isa<PackedType>(VTy))
628 return N = DAG.getNode(ISD::UNDEF, VT);
629
Chris Lattnerb2827b02006-03-19 00:52:58 +0000630 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000631 const PackedType *PTy = cast<PackedType>(VTy);
632 unsigned NumElements = PTy->getNumElements();
633 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
634
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000635 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000636 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
637
638 // Create a VConstant node with generic Vector type.
639 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
640 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000641 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
642 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000643 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
644 return N = DAG.getConstantFP(CFP->getValue(), VT);
645 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
646 unsigned NumElements = PTy->getNumElements();
647 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000648
649 // Now that we know the number and type of the elements, push a
650 // Constant or ConstantFP node onto the ops list for each element of
651 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000652 SmallVector<SDOperand, 8> Ops;
Chris Lattner199862b2006-03-16 19:57:50 +0000653 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000654 for (unsigned i = 0; i != NumElements; ++i)
655 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000656 } else {
657 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
658 SDOperand Op;
659 if (MVT::isFloatingPoint(PVT))
660 Op = DAG.getConstantFP(0, PVT);
661 else
662 Op = DAG.getConstant(0, PVT);
663 Ops.assign(NumElements, Op);
664 }
665
Chris Lattnerb2827b02006-03-19 00:52:58 +0000666 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000667 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
668 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000669 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000670 } else {
671 // Canonicalize all constant ints to be unsigned.
Reid Spencerb83eb642006-10-20 07:07:24 +0000672 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000673 }
674 }
675
676 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
677 std::map<const AllocaInst*, int>::iterator SI =
678 FuncInfo.StaticAllocaMap.find(AI);
679 if (SI != FuncInfo.StaticAllocaMap.end())
680 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
681 }
682
683 std::map<const Value*, unsigned>::const_iterator VMI =
684 FuncInfo.ValueMap.find(V);
685 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
686
687 unsigned InReg = VMI->second;
688
689 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000690 if (VT != MVT::Vector) {
691 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000692
Chris Lattner70c2a612006-03-31 02:06:56 +0000693 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
694 if (DestVT < VT) {
695 // Source must be expanded. This input value is actually coming from the
696 // register pair VMI->second and VMI->second+1.
697 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
698 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
699 } else if (DestVT > VT) { // Promotion case
Chris Lattner199862b2006-03-16 19:57:50 +0000700 if (MVT::isFloatingPoint(VT))
701 N = DAG.getNode(ISD::FP_ROUND, VT, N);
702 else
703 N = DAG.getNode(ISD::TRUNCATE, VT, N);
704 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000705 } else {
706 // Otherwise, if this is a vector, make it available as a generic vector
707 // here.
708 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner2e2ef952006-04-05 06:54:42 +0000709 const PackedType *PTy = cast<PackedType>(VTy);
710 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000711 PTyLegalElementVT);
712
713 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000714 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000715 if (PTyElementVT == PTyLegalElementVT) {
716 // If the value types are legal, just VBUILD the CopyFromReg nodes.
717 for (unsigned i = 0; i != NE; ++i)
718 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
719 PTyElementVT));
720 } else if (PTyElementVT < PTyLegalElementVT) {
721 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
722 for (unsigned i = 0; i != NE; ++i) {
723 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
724 PTyElementVT);
725 if (MVT::isFloatingPoint(PTyElementVT))
726 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
727 else
728 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
729 Ops.push_back(Op);
730 }
731 } else {
732 // If the register was expanded, use BUILD_PAIR.
733 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
734 for (unsigned i = 0; i != NE/2; ++i) {
735 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
736 PTyElementVT);
737 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
738 PTyElementVT);
739 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
740 }
741 }
742
743 Ops.push_back(DAG.getConstant(NE, MVT::i32));
744 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000745 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000746
747 // Finally, use a VBIT_CONVERT to make this available as the appropriate
748 // vector type.
749 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
750 DAG.getConstant(PTy->getNumElements(),
751 MVT::i32),
752 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000753 }
754
755 return N;
756}
757
758
Chris Lattner1c08c712005-01-07 07:47:53 +0000759void SelectionDAGLowering::visitRet(ReturnInst &I) {
760 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000761 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000762 return;
763 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000764 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000765 NewValues.push_back(getRoot());
766 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
767 SDOperand RetOp = getValue(I.getOperand(i));
Evan Cheng8e7d0562006-05-26 23:09:09 +0000768 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begemanee625572006-01-27 21:09:22 +0000769
770 // If this is an integer return value, we need to promote it ourselves to
771 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
772 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000773 // FIXME: C calling convention requires the return type to be promoted to
774 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000775 if (MVT::isInteger(RetOp.getValueType()) &&
776 RetOp.getValueType() < MVT::i64) {
777 MVT::ValueType TmpVT;
778 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
779 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
780 else
781 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000782
Evan Cheng8e7d0562006-05-26 23:09:09 +0000783 if (isSigned)
Nate Begemanee625572006-01-27 21:09:22 +0000784 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
785 else
786 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
787 }
788 NewValues.push_back(RetOp);
Evan Cheng8e7d0562006-05-26 23:09:09 +0000789 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000790 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000791 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
792 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000793}
794
Chris Lattner571e4342006-10-27 21:36:01 +0000795/// ExportFromCurrentBlock - If this condition isn't known to be exported from
796/// the current basic block, add it to ValueMap now so that we'll get a
797/// CopyTo/FromReg.
798void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
799 // No need to export constants.
800 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
801
802 // Already exported?
803 if (FuncInfo.isExportedInst(V)) return;
804
805 unsigned Reg = FuncInfo.InitializeRegForValue(V);
806 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
807}
808
Chris Lattner8c494ab2006-10-27 23:50:33 +0000809bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
810 const BasicBlock *FromBB) {
811 // The operands of the setcc have to be in this block. We don't know
812 // how to export them from some other block.
813 if (Instruction *VI = dyn_cast<Instruction>(V)) {
814 // Can export from current BB.
815 if (VI->getParent() == FromBB)
816 return true;
817
818 // Is already exported, noop.
819 return FuncInfo.isExportedInst(V);
820 }
821
822 // If this is an argument, we can export it if the BB is the entry block or
823 // if it is already exported.
824 if (isa<Argument>(V)) {
825 if (FromBB == &FromBB->getParent()->getEntryBlock())
826 return true;
827
828 // Otherwise, can only export this if it is already exported.
829 return FuncInfo.isExportedInst(V);
830 }
831
832 // Otherwise, constants can always be exported.
833 return true;
834}
835
Chris Lattner6a586c82006-10-29 21:01:20 +0000836static bool InBlock(const Value *V, const BasicBlock *BB) {
837 if (const Instruction *I = dyn_cast<Instruction>(V))
838 return I->getParent() == BB;
839 return true;
840}
841
Chris Lattner571e4342006-10-27 21:36:01 +0000842/// FindMergedConditions - If Cond is an expression like
843void SelectionDAGLowering::FindMergedConditions(Value *Cond,
844 MachineBasicBlock *TBB,
845 MachineBasicBlock *FBB,
846 MachineBasicBlock *CurBB,
847 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000848 // If this node is not part of the or/and tree, emit it as a branch.
849 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
850
851 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000852 BOp->getParent() != CurBB->getBasicBlock() ||
853 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
854 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000855 const BasicBlock *BB = CurBB->getBasicBlock();
856
Chris Lattnerdf19f272006-10-31 22:37:42 +0000857 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
858 if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
859 II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
860 // The operands of the setcc have to be in this block. We don't know
861 // how to export them from some other block. If this is the first
862 // block of the sequence, no exporting is needed.
863 (CurBB == CurMBB ||
864 (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
865 isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
866 SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
867 II->getOperand(2), TBB, FBB, CurBB);
868 SwitchCases.push_back(CB);
869 return;
870 }
871
872
Chris Lattner571e4342006-10-27 21:36:01 +0000873 // If the leaf of the tree is a setcond inst, merge the condition into the
874 // caseblock.
875 if (BOp && isa<SetCondInst>(BOp) &&
876 // The operands of the setcc have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000877 // how to export them from some other block. If this is the first block
878 // of the sequence, no exporting is needed.
879 (CurBB == CurMBB ||
880 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
881 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Chris Lattner571e4342006-10-27 21:36:01 +0000882 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
883 switch (BOp->getOpcode()) {
884 default: assert(0 && "Unknown setcc opcode!");
885 case Instruction::SetEQ:
886 SignCond = ISD::SETEQ;
887 UnsCond = ISD::SETEQ;
888 FPCond = ISD::SETOEQ;
889 break;
890 case Instruction::SetNE:
891 SignCond = ISD::SETNE;
892 UnsCond = ISD::SETNE;
893 FPCond = ISD::SETUNE;
894 break;
895 case Instruction::SetLE:
896 SignCond = ISD::SETLE;
897 UnsCond = ISD::SETULE;
898 FPCond = ISD::SETOLE;
899 break;
900 case Instruction::SetGE:
901 SignCond = ISD::SETGE;
902 UnsCond = ISD::SETUGE;
903 FPCond = ISD::SETOGE;
904 break;
905 case Instruction::SetLT:
906 SignCond = ISD::SETLT;
907 UnsCond = ISD::SETULT;
908 FPCond = ISD::SETOLT;
909 break;
910 case Instruction::SetGT:
911 SignCond = ISD::SETGT;
912 UnsCond = ISD::SETUGT;
913 FPCond = ISD::SETOGT;
914 break;
915 }
916
917 const Type *OpType = BOp->getOperand(0)->getType();
918 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
919 OpType = PTy->getElementType();
920
921 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
922 Condition = FPCond;
923 else if (OpType->isUnsigned())
924 Condition = UnsCond;
925 else
926 Condition = SignCond;
927
928 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
929 BOp->getOperand(1), TBB, FBB, CurBB);
930 SwitchCases.push_back(CB);
931 return;
932 }
933
934 // Create a CaseBlock record representing this branch.
935 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
936 TBB, FBB, CurBB);
937 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000938 return;
939 }
940
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000941
942 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000943 MachineFunction::iterator BBI = CurBB;
944 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
945 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
946
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000947 if (Opc == Instruction::Or) {
948 // Codegen X | Y as:
949 // jmp_if_X TBB
950 // jmp TmpBB
951 // TmpBB:
952 // jmp_if_Y TBB
953 // jmp FBB
954 //
Chris Lattner571e4342006-10-27 21:36:01 +0000955
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000956 // Emit the LHS condition.
957 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
958
959 // Emit the RHS condition into TmpBB.
960 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
961 } else {
962 assert(Opc == Instruction::And && "Unknown merge op!");
963 // Codegen X & Y as:
964 // jmp_if_X TmpBB
965 // jmp FBB
966 // TmpBB:
967 // jmp_if_Y TBB
968 // jmp FBB
969 //
970 // This requires creation of TmpBB after CurBB.
971
972 // Emit the LHS condition.
973 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
974
975 // Emit the RHS condition into TmpBB.
976 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
977 }
Chris Lattner571e4342006-10-27 21:36:01 +0000978}
979
Chris Lattnerdf19f272006-10-31 22:37:42 +0000980/// If the set of cases should be emitted as a series of branches, return true.
981/// If we should emit this as a bunch of and/or'd together conditions, return
982/// false.
983static bool
984ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
985 if (Cases.size() != 2) return true;
986
Chris Lattner0ccb5002006-10-31 23:06:00 +0000987 // If this is two comparisons of the same values or'd or and'd together, they
988 // will get folded into a single comparison, so don't emit two blocks.
989 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
990 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
991 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
992 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
993 return false;
994 }
995
Chris Lattnerdf19f272006-10-31 22:37:42 +0000996 return true;
997}
998
Chris Lattner1c08c712005-01-07 07:47:53 +0000999void SelectionDAGLowering::visitBr(BranchInst &I) {
1000 // Update machine-CFG edges.
1001 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001002
1003 // Figure out which block is immediately after the current one.
1004 MachineBasicBlock *NextBlock = 0;
1005 MachineFunction::iterator BBI = CurMBB;
1006 if (++BBI != CurMBB->getParent()->end())
1007 NextBlock = BBI;
1008
1009 if (I.isUnconditional()) {
1010 // If this is not a fall-through branch, emit the branch.
1011 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +00001012 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001013 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001014
Chris Lattner57ab6592006-10-24 17:57:59 +00001015 // Update machine-CFG edges.
1016 CurMBB->addSuccessor(Succ0MBB);
1017
1018 return;
1019 }
1020
1021 // If this condition is one of the special cases we handle, do special stuff
1022 // now.
1023 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001024 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001025
1026 // If this is a series of conditions that are or'd or and'd together, emit
1027 // this as a sequence of branches instead of setcc's with and/or operations.
1028 // For example, instead of something like:
1029 // cmp A, B
1030 // C = seteq
1031 // cmp D, E
1032 // F = setle
1033 // or C, F
1034 // jnz foo
1035 // Emit:
1036 // cmp A, B
1037 // je foo
1038 // cmp D, E
1039 // jle foo
1040 //
1041 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1042 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001043 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001044 BOp->getOpcode() == Instruction::Or)) {
1045 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001046 // If the compares in later blocks need to use values not currently
1047 // exported from this block, export them now. This block should always
1048 // be the first entry.
1049 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1050
Chris Lattnerdf19f272006-10-31 22:37:42 +00001051 // Allow some cases to be rejected.
1052 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001053 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1054 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1055 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1056 }
1057
1058 // Emit the branch for this block.
1059 visitSwitchCase(SwitchCases[0]);
1060 SwitchCases.erase(SwitchCases.begin());
1061 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001062 }
1063
Chris Lattner0ccb5002006-10-31 23:06:00 +00001064 // Okay, we decided not to do this, remove any inserted MBB's and clear
1065 // SwitchCases.
1066 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1067 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1068
Chris Lattnerdf19f272006-10-31 22:37:42 +00001069 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001070 }
1071 }
Chris Lattner24525952006-10-24 18:07:37 +00001072
1073 // Create a CaseBlock record representing this branch.
Chris Lattner571e4342006-10-27 21:36:01 +00001074 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +00001075 Succ0MBB, Succ1MBB, CurMBB);
1076 // Use visitSwitchCase to actually insert the fast branch sequence for this
1077 // cond branch.
1078 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001079}
1080
Nate Begemanf15485a2006-03-27 01:32:24 +00001081/// visitSwitchCase - Emits the necessary code to represent a single node in
1082/// the binary search tree resulting from lowering a switch instruction.
1083void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001084 SDOperand Cond;
1085 SDOperand CondLHS = getValue(CB.CmpLHS);
1086
Chris Lattner571e4342006-10-27 21:36:01 +00001087 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1088 // handle common cases produced by branch lowering.
1089 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +00001090 Cond = CondLHS;
Chris Lattner571e4342006-10-27 21:36:01 +00001091 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1092 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1093 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1094 } else
1095 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +00001096
1097 // Set NextBlock to be the MBB immediately after the current one, if any.
1098 // This is used to avoid emitting unnecessary branches to the next block.
1099 MachineBasicBlock *NextBlock = 0;
1100 MachineFunction::iterator BBI = CurMBB;
1101 if (++BBI != CurMBB->getParent()->end())
1102 NextBlock = BBI;
1103
1104 // If the lhs block is the next block, invert the condition so that we can
1105 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001106 if (CB.TrueBB == NextBlock) {
1107 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001108 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1109 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1110 }
1111 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001112 DAG.getBasicBlock(CB.TrueBB));
1113 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001114 DAG.setRoot(BrCond);
1115 else
1116 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001117 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001118 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001119 CurMBB->addSuccessor(CB.TrueBB);
1120 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001121}
1122
Nate Begeman37efe672006-04-22 18:53:45 +00001123void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001124 // Emit the code for the jump table
1125 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001126 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1127 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1128 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1129 Table, Index));
1130 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001131}
1132
Nate Begemanf15485a2006-03-27 01:32:24 +00001133void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1134 // Figure out which block is immediately after the current one.
1135 MachineBasicBlock *NextBlock = 0;
1136 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001137
Nate Begemanf15485a2006-03-27 01:32:24 +00001138 if (++BBI != CurMBB->getParent()->end())
1139 NextBlock = BBI;
1140
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001141 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1142
Nate Begemanf15485a2006-03-27 01:32:24 +00001143 // If there is only the default destination, branch to it if it is not the
1144 // next basic block. Otherwise, just fall through.
1145 if (I.getNumOperands() == 2) {
1146 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001147
Nate Begemanf15485a2006-03-27 01:32:24 +00001148 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001149 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001150 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001151 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001152
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001153 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001154 return;
1155 }
1156
1157 // If there are any non-default case statements, create a vector of Cases
1158 // representing each one, and sort the vector so that we can efficiently
1159 // create a binary search tree from them.
1160 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001161
Nate Begemanf15485a2006-03-27 01:32:24 +00001162 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1163 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1164 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1165 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001166
Nate Begemanf15485a2006-03-27 01:32:24 +00001167 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1168
1169 // Get the Value to be switched on and default basic blocks, which will be
1170 // inserted into CaseBlock records, representing basic blocks in the binary
1171 // search tree.
1172 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001173
1174 // Get the MachineFunction which holds the current MBB. This is used during
1175 // emission of jump tables, and when inserting any additional MBBs necessary
1176 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001177 MachineFunction *CurMF = CurMBB->getParent();
1178 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001179
1180 // If the switch has few cases (two or less) emit a series of specific
1181 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001182 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001183 // TODO: If any two of the cases has the same destination, and if one value
1184 // is the same as the other, but has one bit unset that the other has set,
1185 // use bit manipulation to do two compares at once. For example:
1186 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1187
Chris Lattnerb3543432006-10-23 18:38:22 +00001188 // Rearrange the case blocks so that the last one falls through if possible.
1189 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1190 // The last case block won't fall through into 'NextBlock' if we emit the
1191 // branches in this order. See if rearranging a case value would help.
1192 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1193 if (Cases[i].second == NextBlock) {
1194 std::swap(Cases[i], Cases.back());
1195 break;
1196 }
1197 }
1198 }
1199
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001200 // Create a CaseBlock record representing a conditional branch to
1201 // the Case's target mbb if the value being switched on SV is equal
1202 // to C.
1203 MachineBasicBlock *CurBlock = CurMBB;
1204 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1205 MachineBasicBlock *FallThrough;
1206 if (i != e-1) {
1207 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1208 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1209 } else {
1210 // If the last case doesn't match, go to the default block.
1211 FallThrough = Default;
1212 }
1213
1214 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1215 Cases[i].second, FallThrough, CurBlock);
1216
1217 // If emitting the first comparison, just call visitSwitchCase to emit the
1218 // code into the current block. Otherwise, push the CaseBlock onto the
1219 // vector to be later processed by SDISel, and insert the node's MBB
1220 // before the next MBB.
1221 if (CurBlock == CurMBB)
1222 visitSwitchCase(CB);
1223 else
1224 SwitchCases.push_back(CB);
1225
1226 CurBlock = FallThrough;
1227 }
1228 return;
1229 }
Nate Begeman37efe672006-04-22 18:53:45 +00001230
Nate Begeman17c275f2006-05-08 16:51:36 +00001231 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1232 // target supports indirect branches, then emit a jump table rather than
1233 // lowering the switch to a binary tree of conditional branches.
Evan Cheng3d4ce112006-10-30 08:00:44 +00001234 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1235 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001236 Cases.size() > 5) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001237 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1238 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001239 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1240
Nate Begeman17c275f2006-05-08 16:51:36 +00001241 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001242 // Create a new basic block to hold the code for loading the address
1243 // of the jump table, and jumping to it. Update successor information;
1244 // we will either branch to the default case for the switch, or the jump
1245 // table.
1246 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1247 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1248 CurMBB->addSuccessor(Default);
1249 CurMBB->addSuccessor(JumpTableBB);
1250
1251 // Subtract the lowest switch case value from the value being switched on
1252 // and conditional branch to default mbb if the result is greater than the
1253 // difference between smallest and largest cases.
1254 SDOperand SwitchOp = getValue(SV);
1255 MVT::ValueType VT = SwitchOp.getValueType();
1256 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1257 DAG.getConstant(First, VT));
1258
1259 // The SDNode we just created, which holds the value being switched on
1260 // minus the the smallest case value, needs to be copied to a virtual
1261 // register so it can be used as an index into the jump table in a
1262 // subsequent basic block. This value may be smaller or larger than the
1263 // target's pointer type, and therefore require extension or truncating.
1264 if (VT > TLI.getPointerTy())
1265 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1266 else
1267 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001268
Nate Begeman37efe672006-04-22 18:53:45 +00001269 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1270 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1271
1272 // Emit the range check for the jump table, and branch to the default
1273 // block for the switch statement if the value being switched on exceeds
1274 // the largest case in the switch.
1275 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1276 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1277 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1278 DAG.getBasicBlock(Default)));
1279
Nate Begemanf4360a42006-05-03 03:48:02 +00001280 // Build a vector of destination BBs, corresponding to each target
1281 // of the jump table. If the value of the jump table slot corresponds to
1282 // a case statement, push the case's BB onto the vector, otherwise, push
1283 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001284 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemanf4360a42006-05-03 03:48:02 +00001285 uint64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001286 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencerb83eb642006-10-20 07:07:24 +00001287 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001288 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001289 ++ii;
1290 } else {
1291 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001292 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001293
Chris Lattner8c494ab2006-10-27 23:50:33 +00001294 // Update successor info. Add one edge to each unique successor.
1295 // Vector bool would be better, but vector<bool> is really slow.
1296 std::vector<unsigned char> SuccsHandled;
1297 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1298
Chris Lattnerc66764c2006-09-10 06:36:57 +00001299 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner8c494ab2006-10-27 23:50:33 +00001300 E = DestBBs.end(); I != E; ++I) {
1301 if (!SuccsHandled[(*I)->getNumber()]) {
1302 SuccsHandled[(*I)->getNumber()] = true;
1303 JumpTableBB->addSuccessor(*I);
1304 }
1305 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001306
1307 // Create a jump table index for this jump table, or return an existing
1308 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001309 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1310
1311 // Set the jump table information so that we can codegen it as a second
1312 // MachineBasicBlock
1313 JT.Reg = JumpTableReg;
1314 JT.JTI = JTI;
1315 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001316 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001317 return;
1318 }
1319 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001320
1321 // Push the initial CaseRec onto the worklist
1322 std::vector<CaseRec> CaseVec;
1323 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1324
1325 while (!CaseVec.empty()) {
1326 // Grab a record representing a case range to process off the worklist
1327 CaseRec CR = CaseVec.back();
1328 CaseVec.pop_back();
1329
1330 // Size is the number of Cases represented by this range. If Size is 1,
1331 // then we are processing a leaf of the binary search tree. Otherwise,
1332 // we need to pick a pivot, and push left and right ranges onto the
1333 // worklist.
1334 unsigned Size = CR.Range.second - CR.Range.first;
1335
1336 if (Size == 1) {
1337 // Create a CaseBlock record representing a conditional branch to
1338 // the Case's target mbb if the value being switched on SV is equal
1339 // to C. Otherwise, branch to default.
1340 Constant *C = CR.Range.first->first;
1341 MachineBasicBlock *Target = CR.Range.first->second;
1342 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1343 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001344
Nate Begemanf15485a2006-03-27 01:32:24 +00001345 // If the MBB representing the leaf node is the current MBB, then just
1346 // call visitSwitchCase to emit the code into the current block.
1347 // Otherwise, push the CaseBlock onto the vector to be later processed
1348 // by SDISel, and insert the node's MBB before the next MBB.
1349 if (CR.CaseBB == CurMBB)
1350 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001351 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001352 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001353 } else {
1354 // split case range at pivot
1355 CaseItr Pivot = CR.Range.first + (Size / 2);
1356 CaseRange LHSR(CR.Range.first, Pivot);
1357 CaseRange RHSR(Pivot, CR.Range.second);
1358 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001359 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001360
Nate Begemanf15485a2006-03-27 01:32:24 +00001361 // We know that we branch to the LHS if the Value being switched on is
1362 // less than the Pivot value, C. We use this to optimize our binary
1363 // tree a bit, by recognizing that if SV is greater than or equal to the
1364 // LHS's Case Value, and that Case Value is exactly one less than the
1365 // Pivot's Value, then we can branch directly to the LHS's Target,
1366 // rather than creating a leaf node for it.
1367 if ((LHSR.second - LHSR.first) == 1 &&
1368 LHSR.first->first == CR.GE &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001369 cast<ConstantIntegral>(C)->getZExtValue() ==
1370 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001371 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001372 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001373 TrueBB = new MachineBasicBlock(LLVMBB);
1374 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1375 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001376 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001377
Nate Begemanf15485a2006-03-27 01:32:24 +00001378 // Similar to the optimization above, if the Value being switched on is
1379 // known to be less than the Constant CR.LT, and the current Case Value
1380 // is CR.LT - 1, then we can branch directly to the target block for
1381 // the current Case Value, rather than emitting a RHS leaf node for it.
1382 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001383 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1384 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001385 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001386 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001387 FalseBB = new MachineBasicBlock(LLVMBB);
1388 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1389 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001390 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001391
Nate Begemanf15485a2006-03-27 01:32:24 +00001392 // Create a CaseBlock record representing a conditional branch to
1393 // the LHS node if the value being switched on SV is less than C.
1394 // Otherwise, branch to LHS.
1395 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner57ab6592006-10-24 17:57:59 +00001396 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001397
Nate Begemanf15485a2006-03-27 01:32:24 +00001398 if (CR.CaseBB == CurMBB)
1399 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001400 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001401 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001402 }
1403 }
1404}
1405
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001406void SelectionDAGLowering::visitSub(User &I) {
1407 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +00001408 if (I.getType()->isFloatingPoint()) {
1409 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1410 if (CFP->isExactlyValue(-0.0)) {
1411 SDOperand Op2 = getValue(I.getOperand(1));
1412 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1413 return;
1414 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001415 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1416 } else
1417 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001418}
1419
Reid Spencer1628cec2006-10-26 06:15:43 +00001420void
1421SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001422 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001423 SDOperand Op1 = getValue(I.getOperand(0));
1424 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +00001425
Reid Spencer1628cec2006-10-26 06:15:43 +00001426 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001427 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1428 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1429 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer1628cec2006-10-26 06:15:43 +00001430 } else {
1431 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1432 }
1433}
1434
1435void
1436SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1437 const Type *Ty = I.getType();
1438 SDOperand Op1 = getValue(I.getOperand(0));
1439 SDOperand Op2 = getValue(I.getOperand(1));
1440
1441 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1442 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1443 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1444 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1445 } else {
1446 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001447 }
Nate Begemane21ea612005-11-18 07:42:56 +00001448}
Chris Lattner2c49f272005-01-19 22:31:21 +00001449
Nate Begemane21ea612005-11-18 07:42:56 +00001450void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1451 SDOperand Op1 = getValue(I.getOperand(0));
1452 SDOperand Op2 = getValue(I.getOperand(1));
1453
1454 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1455
Chris Lattner1c08c712005-01-07 07:47:53 +00001456 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1457}
1458
Reid Spencer45fb3f32006-11-20 01:22:35 +00001459void SelectionDAGLowering::visitICmp(User &I) {
1460 ICmpInst *IC = cast<ICmpInst>(&I);
1461 SDOperand Op1 = getValue(IC->getOperand(0));
1462 SDOperand Op2 = getValue(IC->getOperand(1));
1463 ISD::CondCode Opcode;
1464 switch (IC->getPredicate()) {
1465 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1466 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1467 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1468 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1469 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1470 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1471 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1472 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1473 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1474 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1475 default:
1476 assert(!"Invalid ICmp predicate value");
1477 Opcode = ISD::SETEQ;
1478 break;
1479 }
1480 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1481}
1482
1483void SelectionDAGLowering::visitFCmp(User &I) {
1484 FCmpInst *FC = cast<FCmpInst>(&I);
1485 SDOperand Op1 = getValue(FC->getOperand(0));
1486 SDOperand Op2 = getValue(FC->getOperand(1));
1487 ISD::CondCode Opcode;
1488 switch (FC->getPredicate()) {
1489 case FCmpInst::FCMP_FALSE : Opcode = ISD::SETFALSE;
1490 case FCmpInst::FCMP_OEQ : Opcode = ISD::SETOEQ;
1491 case FCmpInst::FCMP_OGT : Opcode = ISD::SETOGT;
1492 case FCmpInst::FCMP_OGE : Opcode = ISD::SETOGE;
1493 case FCmpInst::FCMP_OLT : Opcode = ISD::SETOLT;
1494 case FCmpInst::FCMP_OLE : Opcode = ISD::SETOLE;
1495 case FCmpInst::FCMP_ONE : Opcode = ISD::SETONE;
1496 case FCmpInst::FCMP_ORD : Opcode = ISD::SETO;
1497 case FCmpInst::FCMP_UNO : Opcode = ISD::SETUO;
1498 case FCmpInst::FCMP_UEQ : Opcode = ISD::SETUEQ;
1499 case FCmpInst::FCMP_UGT : Opcode = ISD::SETUGT;
1500 case FCmpInst::FCMP_UGE : Opcode = ISD::SETUGE;
1501 case FCmpInst::FCMP_ULT : Opcode = ISD::SETULT;
1502 case FCmpInst::FCMP_ULE : Opcode = ISD::SETULE;
1503 case FCmpInst::FCMP_UNE : Opcode = ISD::SETUNE;
1504 case FCmpInst::FCMP_TRUE : Opcode = ISD::SETTRUE;
1505 default:
1506 assert(!"Invalid FCmp predicate value");
1507 Opcode = ISD::SETFALSE;
1508 break;
1509 }
1510 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1511}
1512
Chris Lattner1c08c712005-01-07 07:47:53 +00001513void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Chengf6f95812006-05-23 06:40:47 +00001514 ISD::CondCode UnsignedOpcode,
1515 ISD::CondCode FPOpcode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001516 SDOperand Op1 = getValue(I.getOperand(0));
1517 SDOperand Op2 = getValue(I.getOperand(1));
1518 ISD::CondCode Opcode = SignedOpcode;
Evan Cheng80235d52006-05-23 18:18:46 +00001519 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Chengf6f95812006-05-23 06:40:47 +00001520 Opcode = FPOpcode;
1521 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner1c08c712005-01-07 07:47:53 +00001522 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +00001523 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +00001524}
1525
1526void SelectionDAGLowering::visitSelect(User &I) {
1527 SDOperand Cond = getValue(I.getOperand(0));
1528 SDOperand TrueVal = getValue(I.getOperand(1));
1529 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001530 if (!isa<PackedType>(I.getType())) {
1531 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1532 TrueVal, FalseVal));
1533 } else {
1534 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1535 *(TrueVal.Val->op_end()-2),
1536 *(TrueVal.Val->op_end()-1)));
1537 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001538}
1539
Reid Spencer3da59db2006-11-27 01:05:10 +00001540
1541void SelectionDAGLowering::visitTrunc(User &I) {
1542 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1543 SDOperand N = getValue(I.getOperand(0));
1544 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1545 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1546}
1547
1548void SelectionDAGLowering::visitZExt(User &I) {
1549 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1550 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1551 SDOperand N = getValue(I.getOperand(0));
1552 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1553 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1554}
1555
1556void SelectionDAGLowering::visitSExt(User &I) {
1557 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1558 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1559 SDOperand N = getValue(I.getOperand(0));
1560 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1561 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1562}
1563
1564void SelectionDAGLowering::visitFPTrunc(User &I) {
1565 // FPTrunc is never a no-op cast, no need to check
1566 SDOperand N = getValue(I.getOperand(0));
1567 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1568 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1569}
1570
1571void SelectionDAGLowering::visitFPExt(User &I){
1572 // FPTrunc is never a no-op cast, no need to check
1573 SDOperand N = getValue(I.getOperand(0));
1574 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1575 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1576}
1577
1578void SelectionDAGLowering::visitFPToUI(User &I) {
1579 // FPToUI is never a no-op cast, no need to check
1580 SDOperand N = getValue(I.getOperand(0));
1581 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1582 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1583}
1584
1585void SelectionDAGLowering::visitFPToSI(User &I) {
1586 // FPToSI is never a no-op cast, no need to check
1587 SDOperand N = getValue(I.getOperand(0));
1588 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1589 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1590}
1591
1592void SelectionDAGLowering::visitUIToFP(User &I) {
1593 // UIToFP is never a no-op cast, no need to check
1594 SDOperand N = getValue(I.getOperand(0));
1595 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1596 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1597}
1598
1599void SelectionDAGLowering::visitSIToFP(User &I){
1600 // UIToFP is never a no-op cast, no need to check
1601 SDOperand N = getValue(I.getOperand(0));
1602 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1603 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1604}
1605
1606void SelectionDAGLowering::visitPtrToInt(User &I) {
1607 // What to do depends on the size of the integer and the size of the pointer.
1608 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00001609 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001610 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001611 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001612 SDOperand Result;
1613 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1614 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1615 else
1616 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1617 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1618 setValue(&I, Result);
1619}
Chris Lattner1c08c712005-01-07 07:47:53 +00001620
Reid Spencer3da59db2006-11-27 01:05:10 +00001621void SelectionDAGLowering::visitIntToPtr(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.
1624 SDOperand N = getValue(I.getOperand(0));
1625 MVT::ValueType SrcVT = N.getValueType();
1626 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1627 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1628 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1629 else
1630 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1631 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1632}
1633
1634void SelectionDAGLowering::visitBitCast(User &I) {
1635 SDOperand N = getValue(I.getOperand(0));
1636 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001637 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001638 // This is a cast to a vector from something else.
1639 // Get information about the output vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001640 const PackedType *DestTy = cast<PackedType>(I.getType());
1641 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1642 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1643 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1644 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00001645 return;
1646 }
1647 MVT::ValueType SrcVT = N.getValueType();
1648 if (SrcVT == MVT::Vector) {
1649 // This is a cast from a vctor to something else.
1650 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001651 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00001652 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001653 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001654
1655 // BitCast assures us that source and destination are the same size so this
1656 // is either a BIT_CONVERT or a no-op.
1657 if (DestVT != N.getValueType())
1658 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1659 else
1660 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00001661}
1662
Chris Lattner2bbd8102006-03-29 00:11:43 +00001663void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001664 SDOperand InVec = getValue(I.getOperand(0));
1665 SDOperand InVal = getValue(I.getOperand(1));
1666 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1667 getValue(I.getOperand(2)));
1668
Chris Lattner2332b9f2006-03-19 01:17:20 +00001669 SDOperand Num = *(InVec.Val->op_end()-2);
1670 SDOperand Typ = *(InVec.Val->op_end()-1);
1671 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1672 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001673}
1674
Chris Lattner2bbd8102006-03-29 00:11:43 +00001675void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001676 SDOperand InVec = getValue(I.getOperand(0));
1677 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1678 getValue(I.getOperand(1)));
1679 SDOperand Typ = *(InVec.Val->op_end()-1);
1680 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1681 TLI.getValueType(I.getType()), InVec, InIdx));
1682}
Chris Lattnerc7029802006-03-18 01:44:44 +00001683
Chris Lattner3e104b12006-04-08 04:15:24 +00001684void SelectionDAGLowering::visitShuffleVector(User &I) {
1685 SDOperand V1 = getValue(I.getOperand(0));
1686 SDOperand V2 = getValue(I.getOperand(1));
1687 SDOperand Mask = getValue(I.getOperand(2));
1688
1689 SDOperand Num = *(V1.Val->op_end()-2);
1690 SDOperand Typ = *(V2.Val->op_end()-1);
1691 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1692 V1, V2, Mask, Num, Typ));
1693}
1694
1695
Chris Lattner1c08c712005-01-07 07:47:53 +00001696void SelectionDAGLowering::visitGetElementPtr(User &I) {
1697 SDOperand N = getValue(I.getOperand(0));
1698 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001699
1700 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1701 OI != E; ++OI) {
1702 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001703 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001704 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001705 if (Field) {
1706 // N = N + Offset
Owen Andersona69571c2006-05-03 01:29:57 +00001707 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner1c08c712005-01-07 07:47:53 +00001708 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001709 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001710 }
1711 Ty = StTy->getElementType(Field);
1712 } else {
1713 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001714
Chris Lattner7c0104b2005-11-09 04:45:33 +00001715 // If this is a constant subscript, handle it quickly.
1716 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001717 if (CI->getZExtValue() == 0) continue;
Chris Lattner7c0104b2005-11-09 04:45:33 +00001718 uint64_t Offs;
Reid Spencerb83eb642006-10-20 07:07:24 +00001719 if (CI->getType()->isSigned())
1720 Offs = (int64_t)
1721 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001722 else
Reid Spencerb83eb642006-10-20 07:07:24 +00001723 Offs =
1724 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001725 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1726 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001727 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001728
1729 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001730 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001731 SDOperand IdxN = getValue(Idx);
1732
1733 // If the index is smaller or larger than intptr_t, truncate or extend
1734 // it.
1735 if (IdxN.getValueType() < N.getValueType()) {
1736 if (Idx->getType()->isSigned())
1737 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1738 else
1739 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1740 } else if (IdxN.getValueType() > N.getValueType())
1741 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1742
1743 // If this is a multiply by a power of two, turn it into a shl
1744 // immediately. This is a very common case.
1745 if (isPowerOf2_64(ElementSize)) {
1746 unsigned Amt = Log2_64(ElementSize);
1747 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001748 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001749 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1750 continue;
1751 }
1752
1753 SDOperand Scale = getIntPtrConstant(ElementSize);
1754 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1755 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001756 }
1757 }
1758 setValue(&I, N);
1759}
1760
1761void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1762 // If this is a fixed sized alloca in the entry block of the function,
1763 // allocate it statically on the stack.
1764 if (FuncInfo.StaticAllocaMap.count(&I))
1765 return; // getValue will auto-populate this.
1766
1767 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001768 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1769 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +00001770 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001771
1772 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001773 MVT::ValueType IntPtr = TLI.getPointerTy();
1774 if (IntPtr < AllocSize.getValueType())
1775 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1776 else if (IntPtr > AllocSize.getValueType())
1777 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001778
Chris Lattner68cd65e2005-01-22 23:04:37 +00001779 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001780 getIntPtrConstant(TySize));
1781
1782 // Handle alignment. If the requested alignment is less than or equal to the
1783 // stack alignment, ignore it and round the size of the allocation up to the
1784 // stack alignment size. If the size is greater than the stack alignment, we
1785 // note this in the DYNAMIC_STACKALLOC node.
1786 unsigned StackAlign =
1787 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1788 if (Align <= StackAlign) {
1789 Align = 0;
1790 // Add SA-1 to the size.
1791 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1792 getIntPtrConstant(StackAlign-1));
1793 // Mask out the low bits for alignment purposes.
1794 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1795 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1796 }
1797
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001798 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001799 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1800 MVT::Other);
1801 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner1c08c712005-01-07 07:47:53 +00001802 DAG.setRoot(setValue(&I, DSA).getValue(1));
1803
1804 // Inform the Frame Information that we have just allocated a variable-sized
1805 // object.
1806 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1807}
1808
Chris Lattner1c08c712005-01-07 07:47:53 +00001809void SelectionDAGLowering::visitLoad(LoadInst &I) {
1810 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001811
Chris Lattnerd3948112005-01-17 22:19:26 +00001812 SDOperand Root;
1813 if (I.isVolatile())
1814 Root = getRoot();
1815 else {
1816 // Do not serialize non-volatile loads against each other.
1817 Root = DAG.getRoot();
1818 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001819
Evan Cheng466685d2006-10-09 20:57:25 +00001820 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001821 Root, I.isVolatile()));
1822}
1823
1824SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001825 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001826 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001827 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001828 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001829 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001830 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1831 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001832 } else {
Evan Cheng466685d2006-10-09 20:57:25 +00001833 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001834 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001835
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001836 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001837 DAG.setRoot(L.getValue(1));
1838 else
1839 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001840
1841 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001842}
1843
1844
1845void SelectionDAGLowering::visitStore(StoreInst &I) {
1846 Value *SrcV = I.getOperand(0);
1847 SDOperand Src = getValue(SrcV);
1848 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng8b2794a2006-10-13 21:14:26 +00001849 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1850 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001851}
1852
Chris Lattner0eade312006-03-24 02:22:33 +00001853/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1854/// access memory and has no other side effects at all.
1855static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1856#define GET_NO_MEMORY_INTRINSICS
1857#include "llvm/Intrinsics.gen"
1858#undef GET_NO_MEMORY_INTRINSICS
1859 return false;
1860}
1861
Chris Lattnere58a7802006-04-02 03:41:14 +00001862// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1863// have any side-effects or if it only reads memory.
1864static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1865#define GET_SIDE_EFFECT_INFO
1866#include "llvm/Intrinsics.gen"
1867#undef GET_SIDE_EFFECT_INFO
1868 return false;
1869}
1870
Chris Lattner0eade312006-03-24 02:22:33 +00001871/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1872/// node.
1873void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1874 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001875 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001876 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001877
1878 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001879 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001880 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1881 if (OnlyLoad) {
1882 // We don't need to serialize loads against other loads.
1883 Ops.push_back(DAG.getRoot());
1884 } else {
1885 Ops.push_back(getRoot());
1886 }
1887 }
Chris Lattner0eade312006-03-24 02:22:33 +00001888
1889 // Add the intrinsic ID as an integer operand.
1890 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1891
1892 // Add all operands of the call to the operand list.
1893 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1894 SDOperand Op = getValue(I.getOperand(i));
1895
1896 // If this is a vector type, force it to the right packed type.
1897 if (Op.getValueType() == MVT::Vector) {
1898 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1899 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1900
1901 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1902 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1903 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1904 }
1905
1906 assert(TLI.isTypeLegal(Op.getValueType()) &&
1907 "Intrinsic uses a non-legal type?");
1908 Ops.push_back(Op);
1909 }
1910
1911 std::vector<MVT::ValueType> VTs;
1912 if (I.getType() != Type::VoidTy) {
1913 MVT::ValueType VT = TLI.getValueType(I.getType());
1914 if (VT == MVT::Vector) {
1915 const PackedType *DestTy = cast<PackedType>(I.getType());
1916 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1917
1918 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1919 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1920 }
1921
1922 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1923 VTs.push_back(VT);
1924 }
1925 if (HasChain)
1926 VTs.push_back(MVT::Other);
1927
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001928 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1929
Chris Lattner0eade312006-03-24 02:22:33 +00001930 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001931 SDOperand Result;
1932 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001933 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1934 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001935 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001936 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1937 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001938 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001939 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1940 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001941
Chris Lattnere58a7802006-04-02 03:41:14 +00001942 if (HasChain) {
1943 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1944 if (OnlyLoad)
1945 PendingLoads.push_back(Chain);
1946 else
1947 DAG.setRoot(Chain);
1948 }
Chris Lattner0eade312006-03-24 02:22:33 +00001949 if (I.getType() != Type::VoidTy) {
1950 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1951 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1952 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1953 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1954 DAG.getValueType(EVT));
1955 }
1956 setValue(&I, Result);
1957 }
1958}
1959
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001960/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1961/// we want to emit this as a call to a named external function, return the name
1962/// otherwise lower it and return null.
1963const char *
1964SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1965 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001966 default:
1967 // By default, turn this into a target intrinsic node.
1968 visitTargetIntrinsic(I, Intrinsic);
1969 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001970 case Intrinsic::vastart: visitVAStart(I); return 0;
1971 case Intrinsic::vaend: visitVAEnd(I); return 0;
1972 case Intrinsic::vacopy: visitVACopy(I); return 0;
1973 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1974 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1975 case Intrinsic::setjmp:
1976 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1977 break;
1978 case Intrinsic::longjmp:
1979 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1980 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001981 case Intrinsic::memcpy_i32:
1982 case Intrinsic::memcpy_i64:
1983 visitMemIntrinsic(I, ISD::MEMCPY);
1984 return 0;
1985 case Intrinsic::memset_i32:
1986 case Intrinsic::memset_i64:
1987 visitMemIntrinsic(I, ISD::MEMSET);
1988 return 0;
1989 case Intrinsic::memmove_i32:
1990 case Intrinsic::memmove_i64:
1991 visitMemIntrinsic(I, ISD::MEMMOVE);
1992 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001993
Chris Lattner86cb6432005-12-13 17:40:33 +00001994 case Intrinsic::dbg_stoppoint: {
Jim Laskeyce72b172006-02-11 01:01:30 +00001995 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001996 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001997 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001998 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00001999
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002000 Ops[0] = getRoot();
2001 Ops[1] = getValue(SPI.getLineValue());
2002 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002003
Jim Laskey43970fe2006-03-23 18:06:46 +00002004 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002005 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002006 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2007
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002008 Ops[3] = DAG.getString(CompileUnit->getFileName());
2009 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002010
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002011 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002012 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002013
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002014 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002015 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002016 case Intrinsic::dbg_region_start: {
2017 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2018 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00002019 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00002020 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002021 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
2022 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002023 }
2024
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002025 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002026 }
2027 case Intrinsic::dbg_region_end: {
2028 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2029 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00002030 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00002031 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002032 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2033 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002034 }
2035
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002036 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002037 }
2038 case Intrinsic::dbg_func_start: {
2039 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2040 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00002041 if (DebugInfo && FSI.getSubprogram() &&
2042 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00002043 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002044 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2045 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002046 }
2047
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002048 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002049 }
2050 case Intrinsic::dbg_declare: {
2051 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2052 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeybf7637d2006-03-28 13:45:20 +00002053 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002054 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002055 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey43970fe2006-03-23 18:06:46 +00002056 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002057 }
2058
2059 return 0;
2060 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002061
Reid Spencer0b118202006-01-16 21:12:35 +00002062 case Intrinsic::isunordered_f32:
2063 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002064 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
2065 getValue(I.getOperand(2)), ISD::SETUO));
2066 return 0;
2067
Reid Spencer0b118202006-01-16 21:12:35 +00002068 case Intrinsic::sqrt_f32:
2069 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002070 setValue(&I, DAG.getNode(ISD::FSQRT,
2071 getValue(I.getOperand(1)).getValueType(),
2072 getValue(I.getOperand(1))));
2073 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002074 case Intrinsic::powi_f32:
2075 case Intrinsic::powi_f64:
2076 setValue(&I, DAG.getNode(ISD::FPOWI,
2077 getValue(I.getOperand(1)).getValueType(),
2078 getValue(I.getOperand(1)),
2079 getValue(I.getOperand(2))));
2080 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002081 case Intrinsic::pcmarker: {
2082 SDOperand Tmp = getValue(I.getOperand(1));
2083 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2084 return 0;
2085 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002086 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002087 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002088 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2089 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2090 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002091 setValue(&I, Tmp);
2092 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002093 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002094 }
Nate Begemand88fc032006-01-14 03:14:10 +00002095 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00002096 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00002097 case Intrinsic::bswap_i64:
2098 setValue(&I, DAG.getNode(ISD::BSWAP,
2099 getValue(I.getOperand(1)).getValueType(),
2100 getValue(I.getOperand(1))));
2101 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002102 case Intrinsic::cttz_i8:
2103 case Intrinsic::cttz_i16:
2104 case Intrinsic::cttz_i32:
2105 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002106 setValue(&I, DAG.getNode(ISD::CTTZ,
2107 getValue(I.getOperand(1)).getValueType(),
2108 getValue(I.getOperand(1))));
2109 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002110 case Intrinsic::ctlz_i8:
2111 case Intrinsic::ctlz_i16:
2112 case Intrinsic::ctlz_i32:
2113 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002114 setValue(&I, DAG.getNode(ISD::CTLZ,
2115 getValue(I.getOperand(1)).getValueType(),
2116 getValue(I.getOperand(1))));
2117 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002118 case Intrinsic::ctpop_i8:
2119 case Intrinsic::ctpop_i16:
2120 case Intrinsic::ctpop_i32:
2121 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002122 setValue(&I, DAG.getNode(ISD::CTPOP,
2123 getValue(I.getOperand(1)).getValueType(),
2124 getValue(I.getOperand(1))));
2125 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00002126 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002127 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002128 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2129 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002130 setValue(&I, Tmp);
2131 DAG.setRoot(Tmp.getValue(1));
2132 return 0;
2133 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002134 case Intrinsic::stackrestore: {
2135 SDOperand Tmp = getValue(I.getOperand(1));
2136 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002137 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002138 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002139 case Intrinsic::prefetch:
2140 // FIXME: Currently discarding prefetches.
2141 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002142 }
2143}
2144
2145
Chris Lattner1c08c712005-01-07 07:47:53 +00002146void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002147 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002148 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002149 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002150 if (unsigned IID = F->getIntrinsicID()) {
2151 RenameFn = visitIntrinsicCall(I, IID);
2152 if (!RenameFn)
2153 return;
2154 } else { // Not an LLVM intrinsic.
2155 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002156 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2157 if (I.getNumOperands() == 3 && // Basic sanity checks.
2158 I.getOperand(1)->getType()->isFloatingPoint() &&
2159 I.getType() == I.getOperand(1)->getType() &&
2160 I.getType() == I.getOperand(2)->getType()) {
2161 SDOperand LHS = getValue(I.getOperand(1));
2162 SDOperand RHS = getValue(I.getOperand(2));
2163 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2164 LHS, RHS));
2165 return;
2166 }
2167 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002168 if (I.getNumOperands() == 2 && // Basic sanity checks.
2169 I.getOperand(1)->getType()->isFloatingPoint() &&
2170 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002171 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002172 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2173 return;
2174 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002175 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002176 if (I.getNumOperands() == 2 && // Basic sanity checks.
2177 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002178 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002179 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002180 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2181 return;
2182 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002183 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002184 if (I.getNumOperands() == 2 && // Basic sanity checks.
2185 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002186 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002187 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002188 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2189 return;
2190 }
2191 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002192 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002193 } else if (isa<InlineAsm>(I.getOperand(0))) {
2194 visitInlineAsm(I);
2195 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002196 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002197
Chris Lattner64e14b12005-01-08 22:48:57 +00002198 SDOperand Callee;
2199 if (!RenameFn)
2200 Callee = getValue(I.getOperand(0));
2201 else
2202 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00002203 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002204 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00002205 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2206 Value *Arg = I.getOperand(i);
2207 SDOperand ArgNode = getValue(Arg);
2208 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2209 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002210
Nate Begeman8e21e712005-03-26 01:29:23 +00002211 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2212 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00002213
Chris Lattnercf5734d2005-01-08 19:26:18 +00002214 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00002215 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00002216 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00002217 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00002218 setValue(&I, Result.first);
2219 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002220}
2221
Chris Lattner864635a2006-02-22 22:37:12 +00002222SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002223 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002224 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2225 Chain = Val.getValue(1);
2226 Flag = Val.getValue(2);
2227
2228 // If the result was expanded, copy from the top part.
2229 if (Regs.size() > 1) {
2230 assert(Regs.size() == 2 &&
2231 "Cannot expand to more than 2 elts yet!");
2232 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002233 Chain = Hi.getValue(1);
2234 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002235 if (DAG.getTargetLoweringInfo().isLittleEndian())
2236 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2237 else
2238 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002239 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002240
Chris Lattnercf752aa2006-06-08 18:22:48 +00002241 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002242 // appropriate type.
2243 if (RegVT == ValueVT)
2244 return Val;
2245
Chris Lattnercf752aa2006-06-08 18:22:48 +00002246 if (MVT::isInteger(RegVT)) {
2247 if (ValueVT < RegVT)
2248 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2249 else
2250 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2251 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002252 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002253 }
Chris Lattner864635a2006-02-22 22:37:12 +00002254}
2255
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002256/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2257/// specified value into the registers specified by this object. This uses
2258/// Chain/Flag as the input and updates them for the output Chain/Flag.
2259void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002260 SDOperand &Chain, SDOperand &Flag,
2261 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002262 if (Regs.size() == 1) {
2263 // If there is a single register and the types differ, this must be
2264 // a promotion.
2265 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002266 if (MVT::isInteger(RegVT)) {
2267 if (RegVT < ValueVT)
2268 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2269 else
2270 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2271 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002272 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2273 }
2274 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2275 Flag = Chain.getValue(1);
2276 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002277 std::vector<unsigned> R(Regs);
2278 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2279 std::reverse(R.begin(), R.end());
2280
2281 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002282 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002283 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002284 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002285 Flag = Chain.getValue(1);
2286 }
2287 }
2288}
Chris Lattner864635a2006-02-22 22:37:12 +00002289
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002290/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2291/// operand list. This adds the code marker and includes the number of
2292/// values added into it.
2293void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002294 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002295 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2296 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2297 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2298}
Chris Lattner864635a2006-02-22 22:37:12 +00002299
2300/// isAllocatableRegister - If the specified register is safe to allocate,
2301/// i.e. it isn't a stack pointer or some other special register, return the
2302/// register class for the register. Otherwise, return null.
2303static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002304isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2305 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002306 MVT::ValueType FoundVT = MVT::Other;
2307 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002308 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2309 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002310 MVT::ValueType ThisVT = MVT::Other;
2311
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002312 const TargetRegisterClass *RC = *RCI;
2313 // If none of the the value types for this register class are valid, we
2314 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002315 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2316 I != E; ++I) {
2317 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002318 // If we have already found this register in a different register class,
2319 // choose the one with the largest VT specified. For example, on
2320 // PowerPC, we favor f64 register classes over f32.
2321 if (FoundVT == MVT::Other ||
2322 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2323 ThisVT = *I;
2324 break;
2325 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002326 }
2327 }
2328
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002329 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002330
Chris Lattner864635a2006-02-22 22:37:12 +00002331 // NOTE: This isn't ideal. In particular, this might allocate the
2332 // frame pointer in functions that need it (due to them not being taken
2333 // out of allocation, because a variable sized allocation hasn't been seen
2334 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002335 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2336 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002337 if (*I == Reg) {
2338 // We found a matching register class. Keep looking at others in case
2339 // we find one with larger registers that this physreg is also in.
2340 FoundRC = RC;
2341 FoundVT = ThisVT;
2342 break;
2343 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002344 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002345 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002346}
2347
2348RegsForValue SelectionDAGLowering::
2349GetRegistersForValue(const std::string &ConstrCode,
2350 MVT::ValueType VT, bool isOutReg, bool isInReg,
2351 std::set<unsigned> &OutputRegs,
2352 std::set<unsigned> &InputRegs) {
2353 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2354 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2355 std::vector<unsigned> Regs;
2356
2357 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2358 MVT::ValueType RegVT;
2359 MVT::ValueType ValueVT = VT;
2360
Chris Lattner2a821602006-11-02 01:41:49 +00002361 // If this is a constraint for a specific physical register, like {r17},
2362 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002363 if (PhysReg.first) {
2364 if (VT == MVT::Other)
2365 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002366
2367 // Get the actual register value type. This is important, because the user
2368 // may have asked for (e.g.) the AX register in i32 type. We need to
2369 // remember that AX is actually i16 to get the right extension.
2370 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002371
2372 // This is a explicit reference to a physical register.
2373 Regs.push_back(PhysReg.first);
2374
2375 // If this is an expanded reference, add the rest of the regs to Regs.
2376 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002377 TargetRegisterClass::iterator I = PhysReg.second->begin();
2378 TargetRegisterClass::iterator E = PhysReg.second->end();
2379 for (; *I != PhysReg.first; ++I)
2380 assert(I != E && "Didn't find reg!");
2381
2382 // Already added the first reg.
2383 --NumRegs; ++I;
2384 for (; NumRegs; --NumRegs, ++I) {
2385 assert(I != E && "Ran out of registers to allocate!");
2386 Regs.push_back(*I);
2387 }
2388 }
2389 return RegsForValue(Regs, RegVT, ValueVT);
2390 }
2391
Chris Lattner2a821602006-11-02 01:41:49 +00002392 // Otherwise, if this was a reference to an LLVM register class, create vregs
2393 // for this reference.
2394 std::vector<unsigned> RegClassRegs;
2395 if (PhysReg.second) {
2396 // If this is an early clobber or tied register, our regalloc doesn't know
2397 // how to maintain the constraint. If it isn't, go ahead and create vreg
2398 // and let the regalloc do the right thing.
2399 if (!isOutReg || !isInReg) {
2400 if (VT == MVT::Other)
2401 ValueVT = *PhysReg.second->vt_begin();
2402 RegVT = *PhysReg.second->vt_begin();
2403
2404 // Create the appropriate number of virtual registers.
2405 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2406 for (; NumRegs; --NumRegs)
2407 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2408
2409 return RegsForValue(Regs, RegVT, ValueVT);
2410 }
2411
2412 // Otherwise, we can't allocate it. Let the code below figure out how to
2413 // maintain these constraints.
2414 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2415
2416 } else {
2417 // This is a reference to a register class that doesn't directly correspond
2418 // to an LLVM register class. Allocate NumRegs consecutive, available,
2419 // registers from the class.
2420 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2421 }
Chris Lattner864635a2006-02-22 22:37:12 +00002422
2423 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2424 MachineFunction &MF = *CurMBB->getParent();
2425 unsigned NumAllocated = 0;
2426 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2427 unsigned Reg = RegClassRegs[i];
2428 // See if this register is available.
2429 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2430 (isInReg && InputRegs.count(Reg))) { // Already used.
2431 // Make sure we find consecutive registers.
2432 NumAllocated = 0;
2433 continue;
2434 }
2435
2436 // Check to see if this register is allocatable (i.e. don't give out the
2437 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002438 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002439 if (!RC) {
2440 // Make sure we find consecutive registers.
2441 NumAllocated = 0;
2442 continue;
2443 }
2444
2445 // Okay, this register is good, we can use it.
2446 ++NumAllocated;
2447
2448 // If we allocated enough consecutive
2449 if (NumAllocated == NumRegs) {
2450 unsigned RegStart = (i-NumAllocated)+1;
2451 unsigned RegEnd = i+1;
2452 // Mark all of the allocated registers used.
2453 for (unsigned i = RegStart; i != RegEnd; ++i) {
2454 unsigned Reg = RegClassRegs[i];
2455 Regs.push_back(Reg);
2456 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2457 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2458 }
2459
2460 return RegsForValue(Regs, *RC->vt_begin(), VT);
2461 }
2462 }
2463
2464 // Otherwise, we couldn't allocate enough registers for this.
2465 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002466}
2467
Chris Lattner864635a2006-02-22 22:37:12 +00002468
Chris Lattnerce7518c2006-01-26 22:24:51 +00002469/// visitInlineAsm - Handle a call to an InlineAsm object.
2470///
2471void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2472 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2473
2474 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2475 MVT::Other);
2476
Chris Lattner2cc2f662006-02-01 01:28:23 +00002477 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002478 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002479
2480 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2481 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2482 /// if it is a def of that register.
2483 std::vector<SDOperand> AsmNodeOperands;
2484 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2485 AsmNodeOperands.push_back(AsmStr);
2486
2487 SDOperand Chain = getRoot();
2488 SDOperand Flag;
2489
Chris Lattner4e4b5762006-02-01 18:59:47 +00002490 // We fully assign registers here at isel time. This is not optimal, but
2491 // should work. For register classes that correspond to LLVM classes, we
2492 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2493 // over the constraints, collecting fixed registers that we know we can't use.
2494 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002495 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002496 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2497 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2498 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00002499
Chris Lattner1efa40f2006-02-22 00:56:39 +00002500 MVT::ValueType OpVT;
2501
2502 // Compute the value type for each operand and add it to ConstraintVTs.
2503 switch (Constraints[i].Type) {
2504 case InlineAsm::isOutput:
2505 if (!Constraints[i].isIndirectOutput) {
2506 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2507 OpVT = TLI.getValueType(I.getType());
2508 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002509 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002510 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2511 OpNum++; // Consumes a call operand.
2512 }
2513 break;
2514 case InlineAsm::isInput:
2515 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2516 OpNum++; // Consumes a call operand.
2517 break;
2518 case InlineAsm::isClobber:
2519 OpVT = MVT::Other;
2520 break;
2521 }
2522
2523 ConstraintVTs.push_back(OpVT);
2524
Chris Lattner864635a2006-02-22 22:37:12 +00002525 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2526 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002527
Chris Lattner864635a2006-02-22 22:37:12 +00002528 // Build a list of regs that this operand uses. This always has a single
2529 // element for promoted/expanded operands.
2530 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2531 false, false,
2532 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002533
2534 switch (Constraints[i].Type) {
2535 case InlineAsm::isOutput:
2536 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002537 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002538 // If this is an early-clobber output, it cannot be assigned to the same
2539 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002540 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002541 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002542 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002543 case InlineAsm::isInput:
2544 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002545 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002546 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002547 case InlineAsm::isClobber:
2548 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002549 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2550 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002551 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002552 }
2553 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002554
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002555 // Loop over all of the inputs, copying the operand values into the
2556 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002557 RegsForValue RetValRegs;
2558 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002559 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002560
Chris Lattner6656dd12006-01-31 02:03:41 +00002561 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00002562 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2563 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00002564
Chris Lattner2cc2f662006-02-01 01:28:23 +00002565 switch (Constraints[i].Type) {
2566 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002567 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2568 if (ConstraintCode.size() == 1) // not a physreg name.
2569 CTy = TLI.getConstraintType(ConstraintCode[0]);
2570
2571 if (CTy == TargetLowering::C_Memory) {
2572 // Memory output.
2573 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2574
2575 // Check that the operand (the address to store to) isn't a float.
2576 if (!MVT::isInteger(InOperandVal.getValueType()))
2577 assert(0 && "MATCH FAIL!");
2578
2579 if (!Constraints[i].isIndirectOutput)
2580 assert(0 && "MATCH FAIL!");
2581
2582 OpNum++; // Consumes a call operand.
2583
2584 // Extend/truncate to the right pointer type if needed.
2585 MVT::ValueType PtrType = TLI.getPointerTy();
2586 if (InOperandVal.getValueType() < PtrType)
2587 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2588 else if (InOperandVal.getValueType() > PtrType)
2589 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2590
2591 // Add information to the INLINEASM node to know about this output.
2592 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2593 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2594 AsmNodeOperands.push_back(InOperandVal);
2595 break;
2596 }
2597
2598 // Otherwise, this is a register output.
2599 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2600
Chris Lattner864635a2006-02-22 22:37:12 +00002601 // If this is an early-clobber output, or if there is an input
2602 // constraint that matches this, we need to reserve the input register
2603 // so no other inputs allocate to it.
2604 bool UsesInputRegister = false;
2605 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2606 UsesInputRegister = true;
2607
2608 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002609 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002610 RegsForValue Regs =
2611 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2612 true, UsesInputRegister,
2613 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00002614 if (Regs.Regs.empty()) {
2615 std::cerr << "Couldn't allocate output reg for contraint '"
2616 << ConstraintCode << "'!\n";
2617 exit(1);
2618 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00002619
Chris Lattner2cc2f662006-02-01 01:28:23 +00002620 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002621 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002622 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002623 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002624 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002625 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002626 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2627 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002628 OpNum++; // Consumes a call operand.
2629 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002630
2631 // Add information to the INLINEASM node to know that this register is
2632 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002633 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002634 break;
2635 }
2636 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002637 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002638 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002639
Chris Lattner2223aea2006-02-02 00:25:23 +00002640 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2641 // If this is required to match an output register we have already set,
2642 // just use its register.
2643 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002644
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002645 // Scan until we find the definition we already emitted of this operand.
2646 // When we find it, create a RegsForValue operand.
2647 unsigned CurOp = 2; // The first operand.
2648 for (; OperandNo; --OperandNo) {
2649 // Advance to the next operand.
2650 unsigned NumOps =
2651 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002652 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2653 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002654 "Skipped past definitions?");
2655 CurOp += (NumOps>>3)+1;
2656 }
2657
2658 unsigned NumOps =
2659 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2660 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2661 "Skipped past definitions?");
2662
2663 // Add NumOps>>3 registers to MatchedRegs.
2664 RegsForValue MatchedRegs;
2665 MatchedRegs.ValueVT = InOperandVal.getValueType();
2666 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2667 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2668 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2669 MatchedRegs.Regs.push_back(Reg);
2670 }
2671
2672 // Use the produced MatchedRegs object to
Evan Chenga8441262006-06-15 08:11:54 +00002673 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2674 TLI.getPointerTy());
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002675 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002676 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00002677 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002678
2679 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2680 if (ConstraintCode.size() == 1) // not a physreg name.
2681 CTy = TLI.getConstraintType(ConstraintCode[0]);
2682
2683 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00002684 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2685 ConstraintCode[0], DAG);
2686 if (!InOperandVal.Val) {
2687 std::cerr << "Invalid operand for inline asm constraint '"
2688 << ConstraintCode << "'!\n";
2689 exit(1);
2690 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002691
2692 // Add information to the INLINEASM node to know about this input.
2693 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2694 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2695 AsmNodeOperands.push_back(InOperandVal);
2696 break;
2697 } else if (CTy == TargetLowering::C_Memory) {
2698 // Memory input.
2699
2700 // Check that the operand isn't a float.
2701 if (!MVT::isInteger(InOperandVal.getValueType()))
2702 assert(0 && "MATCH FAIL!");
2703
2704 // Extend/truncate to the right pointer type if needed.
2705 MVT::ValueType PtrType = TLI.getPointerTy();
2706 if (InOperandVal.getValueType() < PtrType)
2707 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2708 else if (InOperandVal.getValueType() > PtrType)
2709 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2710
2711 // Add information to the INLINEASM node to know about this input.
2712 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2713 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2714 AsmNodeOperands.push_back(InOperandVal);
2715 break;
2716 }
2717
2718 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2719
2720 // Copy the input into the appropriate registers.
2721 RegsForValue InRegs =
2722 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2723 false, true, OutputRegs, InputRegs);
2724 // FIXME: should be match fail.
2725 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2726
Evan Chenga8441262006-06-15 08:11:54 +00002727 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002728
2729 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002730 break;
2731 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002732 case InlineAsm::isClobber: {
2733 RegsForValue ClobberedRegs =
2734 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2735 OutputRegs, InputRegs);
2736 // Add the clobbered value to the operand list, so that the register
2737 // allocator is aware that the physreg got clobbered.
2738 if (!ClobberedRegs.Regs.empty())
2739 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002740 break;
2741 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002742 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002743 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002744
2745 // Finish up input operands.
2746 AsmNodeOperands[0] = Chain;
2747 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2748
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002749 Chain = DAG.getNode(ISD::INLINEASM,
2750 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002751 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002752 Flag = Chain.getValue(1);
2753
Chris Lattner6656dd12006-01-31 02:03:41 +00002754 // If this asm returns a register value, copy the result from that register
2755 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002756 if (!RetValRegs.Regs.empty())
2757 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002758
Chris Lattner6656dd12006-01-31 02:03:41 +00002759 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2760
2761 // Process indirect outputs, first output all of the flagged copies out of
2762 // physregs.
2763 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002764 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002765 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002766 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2767 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002768 }
2769
2770 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002771 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002772 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002773 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002774 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002775 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002776 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002777 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2778 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002779 DAG.setRoot(Chain);
2780}
2781
2782
Chris Lattner1c08c712005-01-07 07:47:53 +00002783void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2784 SDOperand Src = getValue(I.getOperand(0));
2785
2786 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002787
2788 if (IntPtr < Src.getValueType())
2789 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2790 else if (IntPtr > Src.getValueType())
2791 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002792
2793 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002794 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002795 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2796 Src, getIntPtrConstant(ElementSize));
2797
2798 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Andersona69571c2006-05-03 01:29:57 +00002799 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00002800
2801 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002802 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002803 DAG.getExternalSymbol("malloc", IntPtr),
2804 Args, DAG);
2805 setValue(&I, Result.first); // Pointers always fit in registers
2806 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002807}
2808
2809void SelectionDAGLowering::visitFree(FreeInst &I) {
2810 std::vector<std::pair<SDOperand, const Type*> > Args;
2811 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Andersona69571c2006-05-03 01:29:57 +00002812 TLI.getTargetData()->getIntPtrType()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002813 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002814 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002815 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002816 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2817 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002818}
2819
Chris Lattner025c39b2005-08-26 20:54:47 +00002820// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2821// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2822// instructions are special in various ways, which require special support to
2823// insert. The specified MachineInstr is created but not inserted into any
2824// basic blocks, and the scheduler passes ownership of it to this method.
2825MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2826 MachineBasicBlock *MBB) {
2827 std::cerr << "If a target marks an instruction with "
2828 "'usesCustomDAGSchedInserter', it must implement "
2829 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2830 abort();
2831 return 0;
2832}
2833
Chris Lattner39ae3622005-01-09 00:00:49 +00002834void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002835 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2836 getValue(I.getOperand(1)),
2837 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002838}
2839
2840void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002841 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2842 getValue(I.getOperand(0)),
2843 DAG.getSrcValue(I.getOperand(0)));
2844 setValue(&I, V);
2845 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002846}
2847
2848void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002849 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2850 getValue(I.getOperand(1)),
2851 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002852}
2853
2854void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002855 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2856 getValue(I.getOperand(1)),
2857 getValue(I.getOperand(2)),
2858 DAG.getSrcValue(I.getOperand(1)),
2859 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002860}
2861
Chris Lattnerfdfded52006-04-12 16:20:43 +00002862/// TargetLowering::LowerArguments - This is the default LowerArguments
2863/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002864/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2865/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00002866std::vector<SDOperand>
2867TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2868 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2869 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002870 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00002871 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2872 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2873
2874 // Add one result value for each formal argument.
2875 std::vector<MVT::ValueType> RetVals;
2876 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2877 MVT::ValueType VT = getValueType(I->getType());
2878
2879 switch (getTypeAction(VT)) {
2880 default: assert(0 && "Unknown type action!");
2881 case Legal:
2882 RetVals.push_back(VT);
2883 break;
2884 case Promote:
2885 RetVals.push_back(getTypeToTransformTo(VT));
2886 break;
2887 case Expand:
2888 if (VT != MVT::Vector) {
2889 // If this is a large integer, it needs to be broken up into small
2890 // integers. Figure out what the destination type is and how many small
2891 // integers it turns into.
2892 MVT::ValueType NVT = getTypeToTransformTo(VT);
2893 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2894 for (unsigned i = 0; i != NumVals; ++i)
2895 RetVals.push_back(NVT);
2896 } else {
2897 // Otherwise, this is a vector type. We only support legal vectors
2898 // right now.
2899 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2900 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002901
Chris Lattnerfdfded52006-04-12 16:20:43 +00002902 // Figure out if there is a Packed type corresponding to this Vector
2903 // type. If so, convert to the packed type.
2904 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2905 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2906 RetVals.push_back(TVT);
2907 } else {
2908 assert(0 && "Don't support illegal by-val vector arguments yet!");
2909 }
2910 }
2911 break;
2912 }
2913 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00002914
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002915 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002916
2917 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002918 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2919 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002920 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002921
2922 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002923
2924 // Set up the return result vector.
2925 Ops.clear();
2926 unsigned i = 0;
2927 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2928 MVT::ValueType VT = getValueType(I->getType());
2929
2930 switch (getTypeAction(VT)) {
2931 default: assert(0 && "Unknown type action!");
2932 case Legal:
2933 Ops.push_back(SDOperand(Result, i++));
2934 break;
2935 case Promote: {
2936 SDOperand Op(Result, i++);
2937 if (MVT::isInteger(VT)) {
2938 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2939 : ISD::AssertZext;
2940 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2941 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2942 } else {
2943 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2944 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2945 }
2946 Ops.push_back(Op);
2947 break;
2948 }
2949 case Expand:
2950 if (VT != MVT::Vector) {
2951 // If this is a large integer, it needs to be reassembled from small
2952 // integers. Figure out what the source elt type is and how many small
2953 // integers it is.
2954 MVT::ValueType NVT = getTypeToTransformTo(VT);
2955 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2956 if (NumVals == 2) {
2957 SDOperand Lo = SDOperand(Result, i++);
2958 SDOperand Hi = SDOperand(Result, i++);
2959
2960 if (!isLittleEndian())
2961 std::swap(Lo, Hi);
2962
2963 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2964 } else {
2965 // Value scalarized into many values. Unimp for now.
2966 assert(0 && "Cannot expand i64 -> i16 yet!");
2967 }
2968 } else {
2969 // Otherwise, this is a vector type. We only support legal vectors
2970 // right now.
Evan Cheng020c41f2006-04-28 05:25:15 +00002971 const PackedType *PTy = cast<PackedType>(I->getType());
2972 unsigned NumElems = PTy->getNumElements();
2973 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002974
Chris Lattnerfdfded52006-04-12 16:20:43 +00002975 // Figure out if there is a Packed type corresponding to this Vector
2976 // type. If so, convert to the packed type.
2977 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00002978 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00002979 SDOperand N = SDOperand(Result, i++);
2980 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00002981 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2982 DAG.getConstant(NumElems, MVT::i32),
2983 DAG.getValueType(getValueType(EltTy)));
2984 Ops.push_back(N);
2985 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002986 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00002987 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002988 }
2989 }
2990 break;
2991 }
2992 }
2993 return Ops;
2994}
2995
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002996
2997/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2998/// implementation, which just inserts an ISD::CALL node, which is later custom
2999/// lowered by the target to something concrete. FIXME: When all targets are
3000/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3001std::pair<SDOperand, SDOperand>
3002TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
3003 unsigned CallingConv, bool isTailCall,
3004 SDOperand Callee,
3005 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003006 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003007 Ops.push_back(Chain); // Op#0 - Chain
3008 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3009 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3010 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3011 Ops.push_back(Callee);
3012
3013 // Handle all of the outgoing arguments.
3014 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3015 MVT::ValueType VT = getValueType(Args[i].second);
3016 SDOperand Op = Args[i].first;
Evan Chengf6d62c22006-05-25 00:55:32 +00003017 bool isSigned = Args[i].second->isSigned();
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003018 switch (getTypeAction(VT)) {
3019 default: assert(0 && "Unknown type action!");
3020 case Legal:
3021 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003022 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003023 break;
3024 case Promote:
3025 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00003026 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003027 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3028 } else {
3029 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3030 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3031 }
3032 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003033 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003034 break;
3035 case Expand:
3036 if (VT != MVT::Vector) {
3037 // If this is a large integer, it needs to be broken down into small
3038 // integers. Figure out what the source elt type is and how many small
3039 // integers it is.
3040 MVT::ValueType NVT = getTypeToTransformTo(VT);
3041 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
3042 if (NumVals == 2) {
3043 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
3044 DAG.getConstant(0, getPointerTy()));
3045 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
3046 DAG.getConstant(1, getPointerTy()));
3047 if (!isLittleEndian())
3048 std::swap(Lo, Hi);
3049
3050 Ops.push_back(Lo);
Evan Chengd61c4822006-05-26 23:13:20 +00003051 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003052 Ops.push_back(Hi);
Evan Chengd61c4822006-05-26 23:13:20 +00003053 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003054 } else {
3055 // Value scalarized into many values. Unimp for now.
3056 assert(0 && "Cannot expand i64 -> i16 yet!");
3057 }
3058 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003059 // Otherwise, this is a vector type. We only support legal vectors
3060 // right now.
3061 const PackedType *PTy = cast<PackedType>(Args[i].second);
3062 unsigned NumElems = PTy->getNumElements();
3063 const Type *EltTy = PTy->getElementType();
3064
3065 // Figure out if there is a Packed type corresponding to this Vector
3066 // type. If so, convert to the packed type.
3067 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003068 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3069 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3070 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3071 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003072 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003073 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003074 assert(0 && "Don't support illegal by-val vector call args yet!");
3075 abort();
3076 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003077 }
3078 break;
3079 }
3080 }
3081
3082 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003083 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003084
3085 if (RetTy != Type::VoidTy) {
3086 MVT::ValueType VT = getValueType(RetTy);
3087 switch (getTypeAction(VT)) {
3088 default: assert(0 && "Unknown type action!");
3089 case Legal:
3090 RetTys.push_back(VT);
3091 break;
3092 case Promote:
3093 RetTys.push_back(getTypeToTransformTo(VT));
3094 break;
3095 case Expand:
3096 if (VT != MVT::Vector) {
3097 // If this is a large integer, it needs to be reassembled from small
3098 // integers. Figure out what the source elt type is and how many small
3099 // integers it is.
3100 MVT::ValueType NVT = getTypeToTransformTo(VT);
3101 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
3102 for (unsigned i = 0; i != NumVals; ++i)
3103 RetTys.push_back(NVT);
3104 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003105 // Otherwise, this is a vector type. We only support legal vectors
3106 // right now.
3107 const PackedType *PTy = cast<PackedType>(RetTy);
3108 unsigned NumElems = PTy->getNumElements();
3109 const Type *EltTy = PTy->getElementType();
3110
3111 // Figure out if there is a Packed type corresponding to this Vector
3112 // type. If so, convert to the packed type.
3113 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3114 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3115 RetTys.push_back(TVT);
3116 } else {
3117 assert(0 && "Don't support illegal by-val vector call results yet!");
3118 abort();
3119 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003120 }
3121 }
3122 }
3123
3124 RetTys.push_back(MVT::Other); // Always has a chain.
3125
3126 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003127 SDOperand Res = DAG.getNode(ISD::CALL,
3128 DAG.getVTList(&RetTys[0], RetTys.size()),
3129 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003130
3131 // This returns a pair of operands. The first element is the
3132 // return value for the function (if RetTy is not VoidTy). The second
3133 // element is the outgoing token chain.
3134 SDOperand ResVal;
3135 if (RetTys.size() != 1) {
3136 MVT::ValueType VT = getValueType(RetTy);
3137 if (RetTys.size() == 2) {
3138 ResVal = Res;
3139
3140 // If this value was promoted, truncate it down.
3141 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003142 if (VT == MVT::Vector) {
3143 // Insert a VBITCONVERT to convert from the packed result type to the
3144 // MVT::Vector type.
3145 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3146 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3147
3148 // Figure out if there is a Packed type corresponding to this Vector
3149 // type. If so, convert to the packed type.
3150 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3151 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003152 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3153 // "N x PTyElementVT" MVT::Vector type.
3154 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003155 DAG.getConstant(NumElems, MVT::i32),
3156 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003157 } else {
3158 abort();
3159 }
3160 } else if (MVT::isInteger(VT)) {
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003161 unsigned AssertOp = RetTy->isSigned() ?
3162 ISD::AssertSext : ISD::AssertZext;
3163 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3164 DAG.getValueType(VT));
3165 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3166 } else {
3167 assert(MVT::isFloatingPoint(VT));
3168 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3169 }
3170 }
3171 } else if (RetTys.size() == 3) {
3172 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3173 Res.getValue(0), Res.getValue(1));
3174
3175 } else {
3176 assert(0 && "Case not handled yet!");
3177 }
3178 }
3179
3180 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3181}
3182
3183
3184
Chris Lattner39ae3622005-01-09 00:00:49 +00003185// It is always conservatively correct for llvm.returnaddress and
3186// llvm.frameaddress to return 0.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003187//
3188// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3189// expanded to 0 if the target wants.
Chris Lattner39ae3622005-01-09 00:00:49 +00003190std::pair<SDOperand, SDOperand>
3191TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3192 unsigned Depth, SelectionDAG &DAG) {
3193 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00003194}
3195
Chris Lattner50381b62005-05-14 05:50:48 +00003196SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003197 assert(0 && "LowerOperation not implemented for this target!");
3198 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003199 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003200}
3201
Nate Begeman0aed7842006-01-28 03:14:31 +00003202SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3203 SelectionDAG &DAG) {
3204 assert(0 && "CustomPromoteOperation not implemented for this target!");
3205 abort();
3206 return SDOperand();
3207}
3208
Chris Lattner39ae3622005-01-09 00:00:49 +00003209void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003210 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner39ae3622005-01-09 00:00:49 +00003211 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00003212 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00003213 setValue(&I, Result.first);
3214 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003215}
3216
Evan Cheng74d0aa92006-02-15 21:59:04 +00003217/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003218/// operand.
3219static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003220 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003221 MVT::ValueType CurVT = VT;
3222 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3223 uint64_t Val = C->getValue() & 255;
3224 unsigned Shift = 8;
3225 while (CurVT != MVT::i8) {
3226 Val = (Val << Shift) | Val;
3227 Shift <<= 1;
3228 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003229 }
3230 return DAG.getConstant(Val, VT);
3231 } else {
3232 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3233 unsigned Shift = 8;
3234 while (CurVT != MVT::i8) {
3235 Value =
3236 DAG.getNode(ISD::OR, VT,
3237 DAG.getNode(ISD::SHL, VT, Value,
3238 DAG.getConstant(Shift, MVT::i8)), Value);
3239 Shift <<= 1;
3240 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003241 }
3242
3243 return Value;
3244 }
3245}
3246
Evan Cheng74d0aa92006-02-15 21:59:04 +00003247/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3248/// used when a memcpy is turned into a memset when the source is a constant
3249/// string ptr.
3250static SDOperand getMemsetStringVal(MVT::ValueType VT,
3251 SelectionDAG &DAG, TargetLowering &TLI,
3252 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003253 uint64_t Val = 0;
3254 unsigned MSB = getSizeInBits(VT) / 8;
3255 if (TLI.isLittleEndian())
3256 Offset = Offset + MSB - 1;
3257 for (unsigned i = 0; i != MSB; ++i) {
3258 Val = (Val << 8) | Str[Offset];
3259 Offset += TLI.isLittleEndian() ? -1 : 1;
3260 }
3261 return DAG.getConstant(Val, VT);
3262}
3263
Evan Cheng1db92f92006-02-14 08:22:34 +00003264/// getMemBasePlusOffset - Returns base and offset node for the
3265static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3266 SelectionDAG &DAG, TargetLowering &TLI) {
3267 MVT::ValueType VT = Base.getValueType();
3268 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3269}
3270
Evan Chengc4f8eee2006-02-14 20:12:38 +00003271/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003272/// to replace the memset / memcpy is below the threshold. It also returns the
3273/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003274static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3275 unsigned Limit, uint64_t Size,
3276 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003277 MVT::ValueType VT;
3278
3279 if (TLI.allowsUnalignedMemoryAccesses()) {
3280 VT = MVT::i64;
3281 } else {
3282 switch (Align & 7) {
3283 case 0:
3284 VT = MVT::i64;
3285 break;
3286 case 4:
3287 VT = MVT::i32;
3288 break;
3289 case 2:
3290 VT = MVT::i16;
3291 break;
3292 default:
3293 VT = MVT::i8;
3294 break;
3295 }
3296 }
3297
Evan Cheng80e89d72006-02-14 09:11:59 +00003298 MVT::ValueType LVT = MVT::i64;
3299 while (!TLI.isTypeLegal(LVT))
3300 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3301 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003302
Evan Cheng80e89d72006-02-14 09:11:59 +00003303 if (VT > LVT)
3304 VT = LVT;
3305
Evan Chengdea72452006-02-14 23:05:54 +00003306 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003307 while (Size != 0) {
3308 unsigned VTSize = getSizeInBits(VT) / 8;
3309 while (VTSize > Size) {
3310 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003311 VTSize >>= 1;
3312 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003313 assert(MVT::isInteger(VT));
3314
3315 if (++NumMemOps > Limit)
3316 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003317 MemOps.push_back(VT);
3318 Size -= VTSize;
3319 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003320
3321 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003322}
3323
Chris Lattner7041ee32005-01-11 05:56:49 +00003324void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003325 SDOperand Op1 = getValue(I.getOperand(1));
3326 SDOperand Op2 = getValue(I.getOperand(2));
3327 SDOperand Op3 = getValue(I.getOperand(3));
3328 SDOperand Op4 = getValue(I.getOperand(4));
3329 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3330 if (Align == 0) Align = 1;
3331
3332 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3333 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003334
3335 // Expand memset / memcpy to a series of load / store ops
3336 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003337 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003338 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003339 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003340 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003341 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3342 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003343 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003344 unsigned Offset = 0;
3345 for (unsigned i = 0; i < NumMemOps; i++) {
3346 MVT::ValueType VT = MemOps[i];
3347 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003348 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003349 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003350 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003351 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003352 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003353 Offset += VTSize;
3354 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003355 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003356 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003357 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003358 case ISD::MEMCPY: {
3359 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3360 Size->getValue(), Align, TLI)) {
3361 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003362 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003363 GlobalAddressSDNode *G = NULL;
3364 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003365 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003366
3367 if (Op2.getOpcode() == ISD::GlobalAddress)
3368 G = cast<GlobalAddressSDNode>(Op2);
3369 else if (Op2.getOpcode() == ISD::ADD &&
3370 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3371 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3372 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003373 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003374 }
3375 if (G) {
3376 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00003377 if (GV) {
Evan Cheng09371032006-03-10 23:52:03 +00003378 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003379 if (!Str.empty()) {
3380 CopyFromStr = true;
3381 SrcOff += SrcDelta;
3382 }
3383 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003384 }
3385
Evan Chengc080d6f2006-02-15 01:54:51 +00003386 for (unsigned i = 0; i < NumMemOps; i++) {
3387 MVT::ValueType VT = MemOps[i];
3388 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003389 SDOperand Value, Chain, Store;
3390
Evan Chengcffbb512006-02-16 23:11:42 +00003391 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003392 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3393 Chain = getRoot();
3394 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003395 DAG.getStore(Chain, Value,
3396 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003397 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003398 } else {
3399 Value = DAG.getLoad(VT, getRoot(),
3400 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003401 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003402 Chain = Value.getValue(1);
3403 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003404 DAG.getStore(Chain, Value,
3405 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003406 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003407 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003408 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003409 SrcOff += VTSize;
3410 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003411 }
3412 }
3413 break;
3414 }
3415 }
3416
3417 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003418 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3419 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003420 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003421 }
3422 }
3423
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003424 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003425}
3426
Chris Lattner7041ee32005-01-11 05:56:49 +00003427//===----------------------------------------------------------------------===//
3428// SelectionDAGISel code
3429//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003430
3431unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3432 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3433}
3434
Chris Lattner495a0b52005-08-17 06:37:43 +00003435void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003436 // FIXME: we only modify the CFG to split critical edges. This
3437 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003438 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003439}
Chris Lattner1c08c712005-01-07 07:47:53 +00003440
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003441
Chris Lattner90323642006-05-05 21:17:49 +00003442/// OptimizeNoopCopyExpression - We have determined that the specified cast
3443/// instruction is a noop copy (e.g. it's casting from one pointer type to
3444/// another, int->uint, or int->sbyte on PPC.
3445///
3446/// Return true if any changes are made.
3447static bool OptimizeNoopCopyExpression(CastInst *CI) {
3448 BasicBlock *DefBB = CI->getParent();
3449
3450 /// InsertedCasts - Only insert a cast in each block once.
3451 std::map<BasicBlock*, CastInst*> InsertedCasts;
3452
3453 bool MadeChange = false;
3454 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3455 UI != E; ) {
3456 Use &TheUse = UI.getUse();
3457 Instruction *User = cast<Instruction>(*UI);
3458
3459 // Figure out which BB this cast is used in. For PHI's this is the
3460 // appropriate predecessor block.
3461 BasicBlock *UserBB = User->getParent();
3462 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3463 unsigned OpVal = UI.getOperandNo()/2;
3464 UserBB = PN->getIncomingBlock(OpVal);
3465 }
3466
3467 // Preincrement use iterator so we don't invalidate it.
3468 ++UI;
3469
3470 // If this user is in the same block as the cast, don't change the cast.
3471 if (UserBB == DefBB) continue;
3472
3473 // If we have already inserted a cast into this block, use it.
3474 CastInst *&InsertedCast = InsertedCasts[UserBB];
3475
3476 if (!InsertedCast) {
3477 BasicBlock::iterator InsertPt = UserBB->begin();
3478 while (isa<PHINode>(InsertPt)) ++InsertPt;
3479
3480 InsertedCast =
Reid Spencer3da59db2006-11-27 01:05:10 +00003481 CastInst::createInferredCast(CI->getOperand(0), CI->getType(), "",
3482 InsertPt);
Chris Lattner90323642006-05-05 21:17:49 +00003483 MadeChange = true;
3484 }
3485
3486 // Replace a use of the cast with a use of the new casat.
3487 TheUse = InsertedCast;
3488 }
3489
3490 // If we removed all uses, nuke the cast.
3491 if (CI->use_empty())
3492 CI->eraseFromParent();
3493
3494 return MadeChange;
3495}
3496
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003497/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3498/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003499static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3500 Instruction *GEPI, Value *Ptr,
3501 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003502 if (V) return V; // Already computed.
3503
Reid Spencer3da59db2006-11-27 01:05:10 +00003504 // Figure out the insertion point
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003505 BasicBlock::iterator InsertPt;
3506 if (BB == GEPI->getParent()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003507 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003508 InsertPt = GEPI;
3509 ++InsertPt;
3510 } else {
3511 // Otherwise, insert at the top of BB, after any PHI nodes
3512 InsertPt = BB->begin();
3513 while (isa<PHINode>(InsertPt)) ++InsertPt;
3514 }
3515
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003516 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3517 // BB so that there is only one value live across basic blocks (the cast
3518 // operand).
3519 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3520 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencer3da59db2006-11-27 01:05:10 +00003521 Ptr = CastInst::createInferredCast(CI->getOperand(0), CI->getType(), "",
3522 InsertPt);
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003523
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003524 // Add the offset, cast it to the right type.
3525 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer3da59db2006-11-27 01:05:10 +00003526 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3527 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3528 "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003529}
3530
Chris Lattner90323642006-05-05 21:17:49 +00003531/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3532/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3533/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3534/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3535/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3536/// the constant add into a load or store instruction. Additionally, if a user
3537/// is a pointer-pointer cast, we look through it to find its users.
3538static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3539 Constant *PtrOffset, BasicBlock *DefBB,
3540 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003541 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003542 while (!RepPtr->use_empty()) {
3543 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003544
Reid Spencer3da59db2006-11-27 01:05:10 +00003545 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3546 // used for a Pointer-Pointer cast.
3547 if (isa<BitCastInst>(User)) {
Chris Lattner90323642006-05-05 21:17:49 +00003548 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003549
Chris Lattner90323642006-05-05 21:17:49 +00003550 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3551 // could invalidate an iterator.
3552 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3553 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003554 }
3555
Chris Lattner90323642006-05-05 21:17:49 +00003556 // If this is a load of the pointer, or a store through the pointer, emit
3557 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003558 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003559 if (isa<LoadInst>(User) ||
3560 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3561 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3562 User->getParent(), GEPI,
3563 Ptr, PtrOffset);
3564 } else {
3565 // If this use is not foldable into the addressing mode, use a version
3566 // emitted in the GEP block.
3567 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3568 Ptr, PtrOffset);
3569 }
3570
Chris Lattnerf0df8822006-05-06 09:10:37 +00003571 if (GEPI->getType() != RepPtr->getType()) {
3572 BasicBlock::iterator IP = NewVal;
3573 ++IP;
Reid Spencer3da59db2006-11-27 01:05:10 +00003574 // NewVal must be a GEP which must be pointer type, so BitCast
3575 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003576 }
Chris Lattner90323642006-05-05 21:17:49 +00003577 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003578 }
3579}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003580
Chris Lattner90323642006-05-05 21:17:49 +00003581
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003582/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3583/// selection, we want to be a bit careful about some things. In particular, if
3584/// we have a GEP instruction that is used in a different block than it is
3585/// defined, the addressing expression of the GEP cannot be folded into loads or
3586/// stores that use it. In this case, decompose the GEP and move constant
3587/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003588static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003589 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003590 // If this GEP is only used inside the block it is defined in, there is no
3591 // need to rewrite it.
3592 bool isUsedOutsideDefBB = false;
3593 BasicBlock *DefBB = GEPI->getParent();
3594 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3595 UI != E; ++UI) {
3596 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3597 isUsedOutsideDefBB = true;
3598 break;
3599 }
3600 }
Chris Lattner90323642006-05-05 21:17:49 +00003601 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003602
3603 // If this GEP has no non-zero constant indices, there is nothing we can do,
3604 // ignore it.
3605 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003606 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003607 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3608 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003609 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003610 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003611 hasConstantIndex = true;
3612 break;
3613 }
Chris Lattner90323642006-05-05 21:17:49 +00003614 } else {
3615 hasVariableIndex = true;
3616 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003617 }
Chris Lattner90323642006-05-05 21:17:49 +00003618
3619 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3620 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003621 /// The GEP operand must be a pointer, so must its result -> BitCast
3622 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner90323642006-05-05 21:17:49 +00003623 GEPI->getName(), GEPI);
3624 GEPI->replaceAllUsesWith(NC);
3625 GEPI->eraseFromParent();
3626 return true;
3627 }
3628
Chris Lattner3802c252005-12-11 09:05:13 +00003629 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003630 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3631 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003632
3633 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3634 // constant offset (which we now know is non-zero) and deal with it later.
3635 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003636 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer3da59db2006-11-27 01:05:10 +00003637 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003638 const Type *Ty = GEPI->getOperand(0)->getType();
3639
3640 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3641 E = GEPI->op_end(); OI != E; ++OI) {
3642 Value *Idx = *OI;
3643 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003644 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003645 if (Field)
Owen Andersona69571c2006-05-03 01:29:57 +00003646 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003647 Ty = StTy->getElementType(Field);
3648 } else {
3649 Ty = cast<SequentialType>(Ty)->getElementType();
3650
3651 // Handle constant subscripts.
3652 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003653 if (CI->getZExtValue() == 0) continue;
3654 if (CI->getType()->isSigned())
3655 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003656 else
Reid Spencerb83eb642006-10-20 07:07:24 +00003657 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003658 continue;
3659 }
3660
3661 // Ptr = Ptr + Idx * ElementSize;
3662
3663 // Cast Idx to UIntPtrTy if needed.
Reid Spencer3da59db2006-11-27 01:05:10 +00003664 Idx = CastInst::createInferredCast(Idx, UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003665
Owen Andersona69571c2006-05-03 01:29:57 +00003666 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003667 // Mask off bits that should not be set.
3668 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003669 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003670
3671 // Multiply by the element size and add to the base.
3672 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3673 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3674 }
3675 }
3676
3677 // Make sure that the offset fits in uintptr_t.
3678 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003679 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003680
3681 // Okay, we have now emitted all of the variable index parts to the BB that
3682 // the GEP is defined in. Loop over all of the using instructions, inserting
3683 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003684 // instruction to use the newly computed value, making GEPI dead. When the
3685 // user is a load or store instruction address, we emit the add into the user
3686 // block, otherwise we use a canonical version right next to the gep (these
3687 // won't be foldable as addresses, so we might as well share the computation).
3688
Chris Lattnerf0df8822006-05-06 09:10:37 +00003689 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003690 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003691
3692 // Finally, the GEP is dead, remove it.
3693 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003694
3695 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003696}
3697
Chris Lattnerbad7f482006-10-28 19:22:10 +00003698
3699/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3700/// successor if it will improve codegen. We only do this if the successor has
3701/// phi nodes (otherwise critical edges are ok). If there is already another
3702/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3703/// instead of introducing a new block.
3704static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3705 BasicBlock *TIBB = TI->getParent();
3706 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3707 assert(isa<PHINode>(Dest->begin()) &&
3708 "This should only be called if Dest has a PHI!");
3709
3710 /// TIPHIValues - This array is lazily computed to determine the values of
3711 /// PHIs in Dest that TI would provide.
3712 std::vector<Value*> TIPHIValues;
3713
3714 // Check to see if Dest has any blocks that can be used as a split edge for
3715 // this terminator.
3716 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3717 BasicBlock *Pred = *PI;
3718 // To be usable, the pred has to end with an uncond branch to the dest.
3719 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3720 if (!PredBr || !PredBr->isUnconditional() ||
3721 // Must be empty other than the branch.
3722 &Pred->front() != PredBr)
3723 continue;
3724
3725 // Finally, since we know that Dest has phi nodes in it, we have to make
3726 // sure that jumping to Pred will have the same affect as going to Dest in
3727 // terms of PHI values.
3728 PHINode *PN;
3729 unsigned PHINo = 0;
3730 bool FoundMatch = true;
3731 for (BasicBlock::iterator I = Dest->begin();
3732 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3733 if (PHINo == TIPHIValues.size())
3734 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3735
3736 // If the PHI entry doesn't work, we can't use this pred.
3737 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3738 FoundMatch = false;
3739 break;
3740 }
3741 }
3742
3743 // If we found a workable predecessor, change TI to branch to Succ.
3744 if (FoundMatch) {
3745 Dest->removePredecessor(TIBB);
3746 TI->setSuccessor(SuccNum, Pred);
3747 return;
3748 }
3749 }
3750
3751 SplitCriticalEdge(TI, SuccNum, P, true);
3752}
3753
3754
Chris Lattner1c08c712005-01-07 07:47:53 +00003755bool SelectionDAGISel::runOnFunction(Function &Fn) {
3756 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3757 RegMap = MF.getSSARegMap();
3758 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3759
Chris Lattner47e32e62006-10-28 17:04:37 +00003760 // First, split all critical edges.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003761 //
Chris Lattner7e598092006-05-05 01:04:50 +00003762 // In this pass we also look for GEP and cast instructions that are used
3763 // across basic blocks and rewrite them to improve basic-block-at-a-time
3764 // selection.
3765 //
Chris Lattner90323642006-05-05 21:17:49 +00003766 bool MadeChange = true;
3767 while (MadeChange) {
3768 MadeChange = false;
Chris Lattner36b708f2005-08-18 17:35:14 +00003769 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnerbad7f482006-10-28 19:22:10 +00003770 // Split all critical edges where the dest block has a PHI.
Chris Lattner47e32e62006-10-28 17:04:37 +00003771 TerminatorInst *BBTI = BB->getTerminator();
3772 if (BBTI->getNumSuccessors() > 1) {
3773 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbad7f482006-10-28 19:22:10 +00003774 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3775 isCriticalEdge(BBTI, i, true))
3776 SplitEdgeNicely(BBTI, i, this);
Chris Lattner47e32e62006-10-28 17:04:37 +00003777 }
3778
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003779
Chris Lattner57f9a432006-09-28 06:17:10 +00003780 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00003781 Instruction *I = BBI++;
3782 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00003783 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00003784 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00003785 // If the source of the cast is a constant, then this should have
3786 // already been constant folded. The only reason NOT to constant fold
3787 // it is if something (e.g. LSR) was careful to place the constant
3788 // evaluation in a block other than then one that uses it (e.g. to hoist
3789 // the address of globals out of a loop). If this is the case, we don't
3790 // want to forward-subst the cast.
3791 if (isa<Constant>(CI->getOperand(0)))
3792 continue;
3793
Chris Lattner7e598092006-05-05 01:04:50 +00003794 // If this is a noop copy, sink it into user blocks to reduce the number
3795 // of virtual registers that must be created and coallesced.
3796 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3797 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3798
3799 // This is an fp<->int conversion?
3800 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3801 continue;
3802
3803 // If this is an extension, it will be a zero or sign extension, which
3804 // isn't a noop.
3805 if (SrcVT < DstVT) continue;
3806
3807 // If these values will be promoted, find out what they will be promoted
3808 // to. This helps us consider truncates on PPC as noop copies when they
3809 // are.
3810 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3811 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3812 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3813 DstVT = TLI.getTypeToTransformTo(DstVT);
3814
3815 // If, after promotion, these are the same types, this is a noop copy.
3816 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00003817 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00003818 }
3819 }
Chris Lattner36b708f2005-08-18 17:35:14 +00003820 }
Chris Lattner90323642006-05-05 21:17:49 +00003821 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003822
Chris Lattner1c08c712005-01-07 07:47:53 +00003823 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3824
3825 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3826 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00003827
Chris Lattner1c08c712005-01-07 07:47:53 +00003828 return true;
3829}
3830
Chris Lattner571e4342006-10-27 21:36:01 +00003831SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3832 unsigned Reg) {
3833 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00003834 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003835 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00003836 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003837
3838 // If this type is not legal, we must make sure to not create an invalid
3839 // register use.
3840 MVT::ValueType SrcVT = Op.getValueType();
3841 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003842 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00003843 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003844 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00003845 // Handle copies from generic vectors to registers.
3846 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3847 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3848 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003849
Chris Lattner70c2a612006-03-31 02:06:56 +00003850 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3851 // MVT::Vector type.
3852 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3853 DAG.getConstant(NE, MVT::i32),
3854 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00003855
Chris Lattner70c2a612006-03-31 02:06:56 +00003856 // Loop over all of the elements of the resultant vector,
3857 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3858 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003859 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00003860 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00003861 for (unsigned i = 0; i != NE; ++i) {
3862 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003863 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003864 if (PTyElementVT == PTyLegalElementVT) {
3865 // Elements are legal.
3866 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3867 } else if (PTyLegalElementVT > PTyElementVT) {
3868 // Elements are promoted.
3869 if (MVT::isFloatingPoint(PTyLegalElementVT))
3870 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3871 else
3872 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3873 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3874 } else {
3875 // Elements are expanded.
3876 // The src value is expanded into multiple registers.
3877 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003878 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003879 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003880 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003881 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3882 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3883 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00003884 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003885 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3886 &OutChains[0], OutChains.size());
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003887 } else if (SrcVT < DestVT) {
3888 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00003889 if (MVT::isFloatingPoint(SrcVT))
3890 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3891 else
Chris Lattnerfab08872005-09-02 00:19:37 +00003892 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00003893 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003894 } else {
3895 // The src value is expanded into multiple registers.
3896 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003897 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003898 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003899 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00003900 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003901 return DAG.getCopyToReg(Op, Reg+1, Hi);
3902 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003903}
3904
Chris Lattner068a81e2005-01-17 17:15:02 +00003905void SelectionDAGISel::
3906LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3907 std::vector<SDOperand> &UnorderedChains) {
3908 // If this is the entry block, emit arguments.
3909 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00003910 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00003911 SDOperand OldRoot = SDL.DAG.getRoot();
3912 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00003913
Chris Lattnerbf209482005-10-30 19:42:35 +00003914 unsigned a = 0;
3915 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3916 AI != E; ++AI, ++a)
3917 if (!AI->use_empty()) {
3918 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00003919
Chris Lattnerbf209482005-10-30 19:42:35 +00003920 // If this argument is live outside of the entry block, insert a copy from
3921 // whereever we got it to the vreg that other BB's will reference it as.
3922 if (FuncInfo.ValueMap.count(AI)) {
3923 SDOperand Copy =
Chris Lattner571e4342006-10-27 21:36:01 +00003924 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattnerbf209482005-10-30 19:42:35 +00003925 UnorderedChains.push_back(Copy);
3926 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00003927 }
Chris Lattnerbf209482005-10-30 19:42:35 +00003928
Chris Lattnerbf209482005-10-30 19:42:35 +00003929 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00003930 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00003931 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00003932}
3933
Chris Lattner1c08c712005-01-07 07:47:53 +00003934void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3935 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00003936 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00003937 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003938
3939 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00003940
Chris Lattnerbf209482005-10-30 19:42:35 +00003941 // Lower any arguments needed in this block if this is the entry block.
3942 if (LLVMBB == &LLVMBB->getParent()->front())
3943 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00003944
3945 BB = FuncInfo.MBBMap[LLVMBB];
3946 SDL.setCurrentBasicBlock(BB);
3947
3948 // Lower all of the non-terminator instructions.
3949 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3950 I != E; ++I)
3951 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00003952
Chris Lattner1c08c712005-01-07 07:47:53 +00003953 // Ensure that all instructions which are used outside of their defining
3954 // blocks are available as virtual registers.
3955 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00003956 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00003957 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00003958 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00003959 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00003960 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00003961 }
3962
3963 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3964 // ensure constants are generated when needed. Remember the virtual registers
3965 // that need to be added to the Machine PHI nodes as input. We cannot just
3966 // directly add them, because expansion might result in multiple MBB's for one
3967 // BB. As such, the start of the BB might correspond to a different MBB than
3968 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00003969 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00003970 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00003971
3972 // Emit constants only once even if used by multiple PHI nodes.
3973 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003974
Chris Lattner8c494ab2006-10-27 23:50:33 +00003975 // Vector bool would be better, but vector<bool> is really slow.
3976 std::vector<unsigned char> SuccsHandled;
3977 if (TI->getNumSuccessors())
3978 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3979
Chris Lattner1c08c712005-01-07 07:47:53 +00003980 // Check successor nodes PHI nodes that expect a constant to be available from
3981 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00003982 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3983 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003984 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00003985 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003986
Chris Lattner8c494ab2006-10-27 23:50:33 +00003987 // If this terminator has multiple identical successors (common for
3988 // switches), only handle each succ once.
3989 unsigned SuccMBBNo = SuccMBB->getNumber();
3990 if (SuccsHandled[SuccMBBNo]) continue;
3991 SuccsHandled[SuccMBBNo] = true;
3992
3993 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00003994 PHINode *PN;
3995
3996 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3997 // nodes and Machine PHI nodes, but the incoming operands have not been
3998 // emitted yet.
3999 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004000 (PN = dyn_cast<PHINode>(I)); ++I) {
4001 // Ignore dead phi's.
4002 if (PN->use_empty()) continue;
4003
4004 unsigned Reg;
4005 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4006 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4007 unsigned &RegOut = ConstantsOut[C];
4008 if (RegOut == 0) {
4009 RegOut = FuncInfo.CreateRegForValue(C);
4010 UnorderedChains.push_back(
4011 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004012 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004013 Reg = RegOut;
4014 } else {
4015 Reg = FuncInfo.ValueMap[PHIOp];
4016 if (Reg == 0) {
4017 assert(isa<AllocaInst>(PHIOp) &&
4018 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4019 "Didn't codegen value into a register!??");
4020 Reg = FuncInfo.CreateRegForValue(PHIOp);
4021 UnorderedChains.push_back(
4022 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004023 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004024 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004025
4026 // Remember that this register needs to added to the machine PHI node as
4027 // the input for this MBB.
4028 MVT::ValueType VT = TLI.getValueType(PN->getType());
4029 unsigned NumElements;
4030 if (VT != MVT::Vector)
4031 NumElements = TLI.getNumElements(VT);
4032 else {
4033 MVT::ValueType VT1,VT2;
4034 NumElements =
4035 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4036 VT1, VT2);
4037 }
4038 for (unsigned i = 0, e = NumElements; i != e; ++i)
4039 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4040 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004041 }
4042 ConstantsOut.clear();
4043
Chris Lattnerddb870b2005-01-13 17:59:43 +00004044 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004045 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004046 SDOperand Root = SDL.getRoot();
4047 if (Root.getOpcode() != ISD::EntryToken) {
4048 unsigned i = 0, e = UnorderedChains.size();
4049 for (; i != e; ++i) {
4050 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4051 if (UnorderedChains[i].Val->getOperand(0) == Root)
4052 break; // Don't add the root if we already indirectly depend on it.
4053 }
4054
4055 if (i == e)
4056 UnorderedChains.push_back(Root);
4057 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004058 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4059 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004060 }
4061
Chris Lattner1c08c712005-01-07 07:47:53 +00004062 // Lower the terminator after the copies are emitted.
4063 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004064
Nate Begemanf15485a2006-03-27 01:32:24 +00004065 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004066 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004067 SwitchCases.clear();
4068 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00004069 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00004070
Chris Lattnera651cf62005-01-17 19:43:36 +00004071 // Make sure the root of the DAG is up-to-date.
4072 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004073}
4074
Nate Begemanf15485a2006-03-27 01:32:24 +00004075void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004076 // Get alias analysis for load/store combining.
4077 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4078
Chris Lattneraf21d552005-10-10 16:47:10 +00004079 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004080 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004081
Chris Lattner1c08c712005-01-07 07:47:53 +00004082 DEBUG(std::cerr << "Lowered selection DAG:\n");
4083 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004084
Chris Lattner1c08c712005-01-07 07:47:53 +00004085 // Second step, hack on the DAG until it only uses operations and types that
4086 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004087 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004088
Chris Lattner1c08c712005-01-07 07:47:53 +00004089 DEBUG(std::cerr << "Legalized selection DAG:\n");
4090 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004091
Chris Lattneraf21d552005-10-10 16:47:10 +00004092 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004093 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004094
Evan Chenga9c20912006-01-21 02:32:06 +00004095 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004096
Chris Lattnera33ef482005-03-30 01:10:47 +00004097 // Third, instruction select all of the operations to machine code, adding the
4098 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004099 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004100
Chris Lattner1c08c712005-01-07 07:47:53 +00004101 DEBUG(std::cerr << "Selected machine code:\n");
4102 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004103}
Chris Lattner1c08c712005-01-07 07:47:53 +00004104
Nate Begemanf15485a2006-03-27 01:32:24 +00004105void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4106 FunctionLoweringInfo &FuncInfo) {
4107 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4108 {
4109 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4110 CurDAG = &DAG;
4111
4112 // First step, lower LLVM code to some DAG. This DAG may use operations and
4113 // types that are not supported by the target.
4114 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4115
4116 // Second step, emit the lowered DAG as machine code.
4117 CodeGenAndEmitDAG(DAG);
4118 }
4119
Chris Lattnera33ef482005-03-30 01:10:47 +00004120 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004121 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00004122 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004123 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4124 MachineInstr *PHI = PHINodesToUpdate[i].first;
4125 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4126 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004127 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004128 PHI->addMachineBasicBlockOperand(BB);
4129 }
4130 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004131 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004132
Nate Begeman9453eea2006-04-23 06:26:20 +00004133 // If the JumpTable record is filled in, then we need to emit a jump table.
4134 // Updating the PHI nodes is tricky in this case, since we need to determine
4135 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00004136 if (JT.Reg) {
4137 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4138 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4139 CurDAG = &SDAG;
4140 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00004141 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00004142 // Set the current basic block to the mbb we wish to insert the code into
4143 BB = JT.MBB;
4144 SDL.setCurrentBasicBlock(BB);
4145 // Emit the code
4146 SDL.visitJumpTable(JT);
4147 SDAG.setRoot(SDL.getRoot());
4148 CodeGenAndEmitDAG(SDAG);
4149 // Update PHI Nodes
4150 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4151 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4152 MachineBasicBlock *PHIBB = PHI->getParent();
4153 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4154 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00004155 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004156 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004157 PHI->addMachineBasicBlockOperand(RangeBB);
4158 }
4159 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004160 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004161 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004162 }
4163 }
4164 return;
4165 }
4166
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004167 // If the switch block involved a branch to one of the actual successors, we
4168 // need to update PHI nodes in that block.
4169 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4170 MachineInstr *PHI = PHINodesToUpdate[i].first;
4171 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4172 "This is not a machine PHI node that we are updating!");
4173 if (BB->isSuccessor(PHI->getParent())) {
4174 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4175 PHI->addMachineBasicBlockOperand(BB);
4176 }
4177 }
4178
Nate Begemanf15485a2006-03-27 01:32:24 +00004179 // If we generated any switch lowering information, build and codegen any
4180 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004181 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004182 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4183 CurDAG = &SDAG;
4184 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004185
Nate Begemanf15485a2006-03-27 01:32:24 +00004186 // Set the current basic block to the mbb we wish to insert the code into
4187 BB = SwitchCases[i].ThisBB;
4188 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004189
Nate Begemanf15485a2006-03-27 01:32:24 +00004190 // Emit the code
4191 SDL.visitSwitchCase(SwitchCases[i]);
4192 SDAG.setRoot(SDL.getRoot());
4193 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004194
4195 // Handle any PHI nodes in successors of this chunk, as if we were coming
4196 // from the original BB before switch expansion. Note that PHI nodes can
4197 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4198 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004199 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004200 for (MachineBasicBlock::iterator Phi = BB->begin();
4201 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4202 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4203 for (unsigned pn = 0; ; ++pn) {
4204 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4205 if (PHINodesToUpdate[pn].first == Phi) {
4206 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4207 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4208 break;
4209 }
4210 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004211 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004212
4213 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004214 if (BB == SwitchCases[i].FalseBB)
4215 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004216
4217 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004218 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004219 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004220 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004221 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004222 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004223}
Evan Chenga9c20912006-01-21 02:32:06 +00004224
Jim Laskey13ec7022006-08-01 14:21:23 +00004225
Evan Chenga9c20912006-01-21 02:32:06 +00004226//===----------------------------------------------------------------------===//
4227/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4228/// target node in the graph.
4229void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4230 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004231
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004232 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004233
4234 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004235 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004236 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004237 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004238
Jim Laskey9ff542f2006-08-01 18:29:48 +00004239 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004240 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004241 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004242}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004243
Chris Lattner03fc53c2006-03-06 00:22:00 +00004244
Jim Laskey9ff542f2006-08-01 18:29:48 +00004245HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4246 return new HazardRecognizer();
4247}
4248
Chris Lattner75548062006-10-11 03:58:02 +00004249//===----------------------------------------------------------------------===//
4250// Helper functions used by the generated instruction selector.
4251//===----------------------------------------------------------------------===//
4252// Calls to these methods are generated by tblgen.
4253
4254/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4255/// the dag combiner simplified the 255, we still want to match. RHS is the
4256/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4257/// specified in the .td file (e.g. 255).
4258bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4259 int64_t DesiredMaskS) {
4260 uint64_t ActualMask = RHS->getValue();
4261 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4262
4263 // If the actual mask exactly matches, success!
4264 if (ActualMask == DesiredMask)
4265 return true;
4266
4267 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4268 if (ActualMask & ~DesiredMask)
4269 return false;
4270
4271 // Otherwise, the DAG Combiner may have proven that the value coming in is
4272 // either already zero or is not demanded. Check for known zero input bits.
4273 uint64_t NeededMask = DesiredMask & ~ActualMask;
4274 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4275 return true;
4276
4277 // TODO: check to see if missing bits are just not demanded.
4278
4279 // Otherwise, this pattern doesn't match.
4280 return false;
4281}
4282
4283/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4284/// the dag combiner simplified the 255, we still want to match. RHS is the
4285/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4286/// specified in the .td file (e.g. 255).
4287bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4288 int64_t DesiredMaskS) {
4289 uint64_t ActualMask = RHS->getValue();
4290 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4291
4292 // If the actual mask exactly matches, success!
4293 if (ActualMask == DesiredMask)
4294 return true;
4295
4296 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4297 if (ActualMask & ~DesiredMask)
4298 return false;
4299
4300 // Otherwise, the DAG Combiner may have proven that the value coming in is
4301 // either already zero or is not demanded. Check for known zero input bits.
4302 uint64_t NeededMask = DesiredMask & ~ActualMask;
4303
4304 uint64_t KnownZero, KnownOne;
4305 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4306
4307 // If all the missing bits in the or are already known to be set, match!
4308 if ((NeededMask & KnownOne) == NeededMask)
4309 return true;
4310
4311 // TODO: check to see if missing bits are just not demanded.
4312
4313 // Otherwise, this pattern doesn't match.
4314 return false;
4315}
4316
Jim Laskey9ff542f2006-08-01 18:29:48 +00004317
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004318/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4319/// by tblgen. Others should not call it.
4320void SelectionDAGISel::
4321SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4322 std::vector<SDOperand> InOps;
4323 std::swap(InOps, Ops);
4324
4325 Ops.push_back(InOps[0]); // input chain.
4326 Ops.push_back(InOps[1]); // input asm string.
4327
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004328 unsigned i = 2, e = InOps.size();
4329 if (InOps[e-1].getValueType() == MVT::Flag)
4330 --e; // Don't process a flag operand if it is here.
4331
4332 while (i != e) {
4333 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4334 if ((Flags & 7) != 4 /*MEM*/) {
4335 // Just skip over this operand, copying the operands verbatim.
4336 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4337 i += (Flags >> 3) + 1;
4338 } else {
4339 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4340 // Otherwise, this is a memory operand. Ask the target to select it.
4341 std::vector<SDOperand> SelOps;
4342 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4343 std::cerr << "Could not match memory address. Inline asm failure!\n";
4344 exit(1);
4345 }
4346
4347 // Add this to the output node.
4348 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4349 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4350 i += 2;
4351 }
4352 }
4353
4354 // Add the flag input back if present.
4355 if (e != InOps.size())
4356 Ops.push_back(InOps.back());
4357}