1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Aggregate Expr nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CodeGenModule.h" 16 #include "clang/AST/AST.h" 17 #include "llvm/Constants.h" 18 #include "llvm/Function.h" 19 #include "llvm/GlobalVariable.h" 20 #include "llvm/Support/Compiler.h" 21 #include "llvm/Intrinsics.h" 22 using namespace clang; 23 using namespace CodeGen; 24 25 //===----------------------------------------------------------------------===// 26 // Aggregate Expression Emitter 27 //===----------------------------------------------------------------------===// 28 29 namespace { 30 class VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> { 31 CodeGenFunction &CGF; 32 llvm::IRBuilder &Builder; 33 llvm::Value *DestPtr; 34 bool VolatileDest; 35 public: 36 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool volatileDest) 37 : CGF(cgf), Builder(CGF.Builder), 38 DestPtr(destPtr), VolatileDest(volatileDest) { 39 } 40 41 //===--------------------------------------------------------------------===// 42 // Utilities 43 //===--------------------------------------------------------------------===// 44 45 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 46 /// represents a value lvalue, this method emits the address of the lvalue, 47 /// then loads the result into DestPtr. 48 void EmitAggLoadOfLValue(const Expr *E); 49 50 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 51 QualType EltTy); 52 53 void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty); 54 55 void EmitNonConstInit(InitListExpr *E); 56 57 //===--------------------------------------------------------------------===// 58 // Visitor Methods 59 //===--------------------------------------------------------------------===// 60 61 void VisitStmt(Stmt *S) { 62 CGF.WarnUnsupported(S, "aggregate expression"); 63 } 64 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 65 66 // l-values. 67 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 68 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 69 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 70 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 71 72 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 73 EmitAggLoadOfLValue(E); 74 } 75 76 // Operators. 77 // case Expr::UnaryOperatorClass: 78 // case Expr::CastExprClass: 79 void VisitImplicitCastExpr(ImplicitCastExpr *E); 80 void VisitCallExpr(const CallExpr *E); 81 void VisitStmtExpr(const StmtExpr *E); 82 void VisitBinaryOperator(const BinaryOperator *BO); 83 void VisitBinAssign(const BinaryOperator *E); 84 void VisitOverloadExpr(const OverloadExpr *E); 85 86 87 void VisitConditionalOperator(const ConditionalOperator *CO); 88 void VisitInitListExpr(InitListExpr *E); 89 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 90 Visit(DAE->getExpr()); 91 } 92 93 void EmitInitializationToLValue(Expr *E, LValue Address); 94 void EmitNullInitializationToLValue(LValue Address, QualType T); 95 // case Expr::ChooseExprClass: 96 97 }; 98 } // end anonymous namespace. 99 100 //===----------------------------------------------------------------------===// 101 // Utilities 102 //===----------------------------------------------------------------------===// 103 104 void AggExprEmitter::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) { 105 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 106 107 // Aggregate assignment turns into llvm.memset. 108 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 109 if (DestPtr->getType() != BP) 110 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 111 112 // Get size and alignment info for this aggregate. 113 std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty); 114 115 // FIXME: Handle variable sized types. 116 const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth); 117 118 llvm::Value *MemSetOps[4] = { 119 DestPtr, 120 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty), 121 // TypeInfo.first describes size in bits. 122 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 123 llvm::ConstantInt::get(llvm::Type::Int32Ty, TypeInfo.second/8) 124 }; 125 126 Builder.CreateCall(CGF.CGM.getMemSetFn(), MemSetOps, MemSetOps+4); 127 } 128 129 void AggExprEmitter::EmitAggregateCopy(llvm::Value *DestPtr, 130 llvm::Value *SrcPtr, QualType Ty) { 131 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 132 133 // Aggregate assignment turns into llvm.memcpy. 134 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 135 if (DestPtr->getType() != BP) 136 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 137 if (SrcPtr->getType() != BP) 138 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 139 140 // Get size and alignment info for this aggregate. 141 std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty); 142 143 // FIXME: Handle variable sized types. 144 const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth); 145 146 llvm::Value *MemCpyOps[4] = { 147 DestPtr, SrcPtr, 148 // TypeInfo.first describes size in bits. 149 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 150 llvm::ConstantInt::get(llvm::Type::Int32Ty, TypeInfo.second/8) 151 }; 152 153 Builder.CreateCall(CGF.CGM.getMemCpyFn(), MemCpyOps, MemCpyOps+4); 154 } 155 156 157 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 158 /// represents a value lvalue, this method emits the address of the lvalue, 159 /// then loads the result into DestPtr. 160 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 161 LValue LV = CGF.EmitLValue(E); 162 assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc"); 163 llvm::Value *SrcPtr = LV.getAddress(); 164 165 // If the result is ignored, don't copy from the value. 166 if (DestPtr == 0) 167 // FIXME: If the source is volatile, we must read from it. 168 return; 169 170 EmitAggregateCopy(DestPtr, SrcPtr, E->getType()); 171 } 172 173 //===----------------------------------------------------------------------===// 174 // Visitor Methods 175 //===----------------------------------------------------------------------===// 176 177 void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E) 178 { 179 QualType STy = E->getSubExpr()->getType().getCanonicalType(); 180 QualType Ty = E->getType().getCanonicalType(); 181 182 assert(CGF.getContext().typesAreCompatible( 183 STy.getUnqualifiedType(), Ty.getUnqualifiedType()) 184 && "Implicit cast types must be compatible"); 185 186 Visit(E->getSubExpr()); 187 } 188 189 void AggExprEmitter::VisitCallExpr(const CallExpr *E) 190 { 191 RValue RV = CGF.EmitCallExpr(E); 192 assert(RV.isAggregate() && "Return value must be aggregate value!"); 193 194 // If the result is ignored, don't copy from the value. 195 if (DestPtr == 0) 196 // FIXME: If the source is volatile, we must read from it. 197 return; 198 199 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 200 } 201 202 void AggExprEmitter::VisitOverloadExpr(const OverloadExpr *E) 203 { 204 RValue RV = CGF.EmitCallExpr(E->getFn(), E->arg_begin(), 205 E->getNumArgs(CGF.getContext())); 206 assert(RV.isAggregate() && "Return value must be aggregate value!"); 207 208 // If the result is ignored, don't copy from the value. 209 if (DestPtr == 0) 210 // FIXME: If the source is volatile, we must read from it. 211 return; 212 213 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 214 } 215 216 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 217 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 218 } 219 220 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 221 CGF.WarnUnsupported(E, "aggregate binary expression"); 222 } 223 224 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 225 // For an assignment to work, the value on the right has 226 // to be compatible with the value on the left. 227 assert(CGF.getContext().typesAreCompatible( 228 E->getLHS()->getType().getUnqualifiedType(), 229 E->getRHS()->getType().getUnqualifiedType()) 230 && "Invalid assignment"); 231 LValue LHS = CGF.EmitLValue(E->getLHS()); 232 233 // Codegen the RHS so that it stores directly into the LHS. 234 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/); 235 236 if (DestPtr == 0) 237 return; 238 239 // If the result of the assignment is used, copy the RHS there also. 240 EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType()); 241 } 242 243 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 244 llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?"); 245 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:"); 246 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont"); 247 248 llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond()); 249 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock); 250 251 CGF.EmitBlock(LHSBlock); 252 253 // Handle the GNU extension for missing LHS. 254 assert(E->getLHS() && "Must have LHS for aggregate value"); 255 256 Visit(E->getLHS()); 257 Builder.CreateBr(ContBlock); 258 LHSBlock = Builder.GetInsertBlock(); 259 260 CGF.EmitBlock(RHSBlock); 261 262 Visit(E->getRHS()); 263 Builder.CreateBr(ContBlock); 264 RHSBlock = Builder.GetInsertBlock(); 265 266 CGF.EmitBlock(ContBlock); 267 } 268 269 void AggExprEmitter::EmitNonConstInit(InitListExpr *E) { 270 271 const llvm::PointerType *APType = 272 cast<llvm::PointerType>(DestPtr->getType()); 273 const llvm::Type *DestType = APType->getElementType(); 274 275 if (const llvm::ArrayType *AType = dyn_cast<llvm::ArrayType>(DestType)) { 276 unsigned NumInitElements = E->getNumInits(); 277 278 unsigned i; 279 for (i = 0; i != NumInitElements; ++i) { 280 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 281 Expr *Init = E->getInit(i); 282 if (isa<InitListExpr>(Init)) 283 CGF.EmitAggExpr(Init, NextVal, VolatileDest); 284 else 285 Builder.CreateStore(CGF.EmitScalarExpr(Init), NextVal); 286 } 287 288 // Emit remaining default initializers 289 unsigned NumArrayElements = AType->getNumElements(); 290 QualType QType = E->getInit(0)->getType(); 291 const llvm::Type *EType = AType->getElementType(); 292 for (/*Do not initialize i*/; i < NumArrayElements; ++i) { 293 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 294 if (EType->isFirstClassType()) 295 Builder.CreateStore(llvm::Constant::getNullValue(EType), NextVal); 296 else 297 EmitAggregateClear(NextVal, QType); 298 } 299 } else 300 assert(false && "Invalid initializer"); 301 } 302 303 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) { 304 // FIXME: Are initializers affected by volatile? 305 if (E->getType()->isComplexType()) { 306 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 307 } else if (CGF.hasAggregateLLVMType(E->getType())) { 308 CGF.EmitAnyExpr(E, LV.getAddress(), false); 309 } else { 310 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType()); 311 } 312 } 313 314 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 315 if (!CGF.hasAggregateLLVMType(T)) { 316 // For non-aggregates, we can store zero 317 const llvm::Type *T = 318 cast<llvm::PointerType>(LV.getAddress()->getType())->getElementType(); 319 Builder.CreateStore(llvm::Constant::getNullValue(T), LV.getAddress()); 320 } else { 321 // Otherwise, just memset the whole thing to zero. This is legal 322 // because in LLVM, all default initializers are guaranteed to have a 323 // bit pattern of all zeros. 324 // There's a potential optimization opportunity in combining 325 // memsets; that would be easy for arrays, but relatively 326 // difficult for structures with the current code. 327 llvm::Value *MemSet = CGF.CGM.getIntrinsic(llvm::Intrinsic::memset_i64); 328 uint64_t Size = CGF.getContext().getTypeSize(T); 329 330 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 331 llvm::Value* DestPtr = Builder.CreateBitCast(LV.getAddress(), BP, "tmp"); 332 Builder.CreateCall4(MemSet, DestPtr, 333 llvm::ConstantInt::get(llvm::Type::Int8Ty, 0), 334 llvm::ConstantInt::get(llvm::Type::Int64Ty, Size/8), 335 llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 336 } 337 } 338 339 340 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 341 if (E->isConstantExpr(CGF.getContext(), 0)) { 342 // FIXME: call into const expr emitter so that we can emit 343 // a memcpy instead of storing the individual members. 344 // This is purely for perf; both codepaths lead to equivalent 345 // (although not necessarily identical) code. 346 // It's worth noting that LLVM keeps on getting smarter, though, 347 // so it might not be worth bothering. 348 } 349 350 // Handle initialization of an array. 351 if (E->getType()->isArrayType()) { 352 const llvm::PointerType *APType = 353 cast<llvm::PointerType>(DestPtr->getType()); 354 const llvm::ArrayType *AType = 355 cast<llvm::ArrayType>(APType->getElementType()); 356 357 uint64_t NumInitElements = E->getNumInits(); 358 uint64_t NumArrayElements = AType->getNumElements(); 359 QualType ElementType = E->getType()->getAsArrayType()->getElementType(); 360 361 for (uint64_t i = 0; i != NumArrayElements; ++i) { 362 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 363 if (i < NumInitElements) 364 EmitInitializationToLValue(E->getInit(i), LValue::MakeAddr(NextVal)); 365 else 366 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal), 367 ElementType); 368 } 369 return; 370 } 371 372 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 373 374 // Do struct initialization; this code just sets each individual member 375 // to the approprate value. This makes bitfield support automatic; 376 // the disadvantage is that the generated code is more difficult for 377 // the optimizer, especially with bitfields. 378 unsigned NumInitElements = E->getNumInits(); 379 RecordDecl *SD = E->getType()->getAsRecordType()->getDecl(); 380 unsigned NumMembers = SD->getNumMembers() - SD->hasFlexibleArrayMember(); 381 unsigned CurInitVal = 0; 382 bool isUnion = E->getType()->isUnionType(); 383 384 // Here we iterate over the fields; this makes it simpler to both 385 // default-initialize fields and skip over unnamed fields. 386 for (unsigned CurFieldNo = 0; CurFieldNo != NumMembers; ++CurFieldNo) { 387 if (CurInitVal >= NumInitElements) { 388 // No more initializers; we're done. 389 break; 390 } 391 392 FieldDecl *CurField = SD->getMember(CurFieldNo); 393 if (CurField->getIdentifier() == 0) { 394 // Initializers can't initialize unnamed fields, e.g. "int : 20;" 395 continue; 396 } 397 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, CurField, isUnion); 398 if (CurInitVal < NumInitElements) { 399 // Store the initializer into the field 400 // This will probably have to get a bit smarter when we support 401 // designators in initializers 402 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc); 403 } else { 404 // We're out of initalizers; default-initialize to null 405 EmitNullInitializationToLValue(FieldLoc, CurField->getType()); 406 } 407 408 // Unions only initialize one field. 409 // (things can get weird with designators, but they aren't 410 // supported yet.) 411 if (E->getType()->isUnionType()) 412 break; 413 } 414 } 415 416 //===----------------------------------------------------------------------===// 417 // Entry Points into this File 418 //===----------------------------------------------------------------------===// 419 420 /// EmitAggExpr - Emit the computation of the specified expression of 421 /// aggregate type. The result is computed into DestPtr. Note that if 422 /// DestPtr is null, the value of the aggregate expression is not needed. 423 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 424 bool VolatileDest) { 425 assert(E && hasAggregateLLVMType(E->getType()) && 426 "Invalid aggregate expression to emit"); 427 428 AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E)); 429 } 430